diff --git a/activity.php b/activity.php new file mode 100644 index 0000000..8de67ea --- /dev/null +++ b/activity.php @@ -0,0 +1,142 @@ +assign('page_title', $position['title']); // 页面标题 +$smarty->assign('ur_here', $position['ur_here']); // 当前位置 + $smarty->assign('categories', get_categories_tree()); // 分类树 + +// 数据准备 + + /* 取得用户等级 */ + $user_rank_list = array(); + $user_rank_list[0] = $_LANG['not_user']; + $sql = "SELECT rank_id, rank_name FROM " . $ecs->table('user_rank'); + $res = $db->query($sql); + while ($row = $db->fetchRow($res)) + { + $user_rank_list[$row['rank_id']] = $row['rank_name']; + } + + +// 开始工作 + +$sql = "SELECT * FROM " . $ecs->table('favourable_activity'). " ORDER BY `sort_order` ASC,`end_time` DESC"; +$res = $db->query($sql); + +$list = array(); +while ($row = $db->fetchRow($res)) +{ + $row['start_time'] = local_date('Y-m-d H:i', $row['start_time']); + $row['end_time'] = local_date('Y-m-d H:i', $row['end_time']); + + //享受优惠会员等级 + $user_rank = explode(',', $row['user_rank']); + $row['user_rank'] = array(); + foreach($user_rank as $val) + { + if (isset($user_rank_list[$val])) + { + $row['user_rank'][] = $user_rank_list[$val]; + } + } + + //优惠范围类型、内容 + if ($row['act_range'] != FAR_ALL && !empty($row['act_range_ext'])) + { + if ($row['act_range'] == FAR_CATEGORY) + { + $row['act_range'] = $_LANG['far_category']; + $row['program'] = 'category.php?id='; + $sql = "SELECT cat_id AS id, cat_name AS name FROM " . $ecs->table('category') . + " WHERE cat_id " . db_create_in($row['act_range_ext']); + } + elseif ($row['act_range'] == FAR_BRAND) + { + $row['act_range'] = $_LANG['far_brand']; + $row['program'] = 'brand.php?id='; + $sql = "SELECT brand_id AS id, brand_name AS name FROM " . $ecs->table('brand') . + " WHERE brand_id " . db_create_in($row['act_range_ext']); + } + else + { + $row['act_range'] = $_LANG['far_goods']; + $row['program'] = 'goods.php?id='; + $sql = "SELECT goods_id AS id, goods_name AS name FROM " . $ecs->table('goods') . + " WHERE goods_id " . db_create_in($row['act_range_ext']); + } + $act_range_ext = $db->getAll($sql); + $row['act_range_ext'] = $act_range_ext; + } + else + { + $row['act_range'] = $_LANG['far_all']; + } + + //优惠方式 + + switch($row['act_type']) + { + case 0: + $row['act_type'] = $_LANG['fat_goods']; + $row['gift'] = unserialize($row['gift']); + if(is_array($row['gift'])) + { + foreach($row['gift'] as $k=>$v) + { + $row['gift'][$k]['thumb'] = get_image_path($v['id'], $db->getOne("SELECT goods_thumb FROM " . $ecs->table('goods') . " WHERE goods_id = '" . $v['id'] . "'"), true); + } + } + break; + case 1: + $row['act_type'] = $_LANG['fat_price']; + $row['act_type_ext'] .= $_LANG['unit_yuan']; + $row['gift'] = array(); + break; + case 2: + $row['act_type'] = $_LANG['fat_discount']; + $row['act_type_ext'] .= "%"; + $row['gift'] = array(); + break; + } + + $list[] = $row; +} + +//print_r($list); +$smarty->assign('list', $list); + +$smarty->assign('helps', get_shop_help()); // 网店帮助 +$smarty->assign('lang', $_LANG); + +$smarty->assign('feed_url', ($_CFG['rewrite'] == 1) ? "feed-typeactivity.xml" : 'feed.php?type=activity'); // RSS URL +$smarty->display('activity.dwt'); + diff --git a/affiche.php b/affiche.php new file mode 100644 index 0000000..a493da8 --- /dev/null +++ b/affiche.php @@ -0,0 +1,165 @@ +url(); + $str = ""; + + /* 取得广告的信息 */ + $sql = 'SELECT ad.ad_id, ad.ad_name, ad.ad_link, ad.ad_code '. + 'FROM ' . $ecs->table('ad') . ' AS ad ' . + 'LEFT JOIN ' . $ecs->table('ad_position') . ' AS p ON ad.position_id = p.position_id '. + "WHERE ad.ad_id = '$ad_id' and " . gmtime() . " >= ad.start_time and " . gmtime() . "<= ad.end_time"; + + $ad_info = $db->getRow($sql); + + if (!empty($ad_info)) + { + /* 转换编码 */ + if ($_GET['charset'] != 'UTF8') + { + $ad_info['ad_name'] = ecs_iconv('UTF8', $_GET['charset'], $ad_info['ad_name']); + $ad_info['ad_code'] = ecs_iconv('UTF8', $_GET['charset'], $ad_info['ad_code']); + } + + /* 初始化广告的类型和来源 */ + $_GET['type'] = !empty($_GET['type']) ? intval($_GET['type']) : 0; + $_GET['from'] = !empty($_GET['from']) ? urlencode($_GET['from']) : ''; + + $str = ''; + switch ($_GET['type']) + { + case '0': + /* 图片广告 */ + $src = (strpos($ad_info['ad_code'], 'http://') === false && strpos($ad_info['ad_code'], 'https://') === false) ? $url . DATA_DIR . "/afficheimg/$ad_info[ad_code]" : $ad_info['ad_code']; + $str = '' . + '' . $ad_info['ad_name'] . ''; + break; + + case '1': + /* Falsh广告 */ + $src = (strpos($ad_info['ad_code'], 'http://') === false && strpos($ad_info['ad_code'], 'https://') === false) ? $url . DATA_DIR . '/afficheimg/' . $ad_info['ad_code'] : $ad_info['ad_code']; + $str = ' '; + break; + + case '2': + /* 代码广告 */ + $str = $ad_info['ad_code']; + break; + + case 3: + /* 文字广告 */ + $str = '' . nl2br(htmlspecialchars(addslashes($ad_info['ad_code']))). ''; + break; + } + } + echo "document.writeln('$str');"; +} +else +{ + /* 获取投放站点的名称 */ + $site_name = !empty($_GET['from']) ? $_GET['from'] : addslashes($_LANG['self_site']); + + /* 商品的ID */ + $goods_id = !empty($_GET['goods_id']) ? intval($_GET['goods_id']) : 0; + + /* 存入SESSION中,购物后一起存到订单数据表里 */ + $_SESSION['from_ad'] = $ad_id; + $_SESSION['referer'] = stripslashes($site_name); + + /* 如果是商品的站外JS */ + if ($ad_id == '-1') + { + $sql = "SELECT count(*) FROM " . $ecs->table('adsense') . " WHERE from_ad = '-1' AND referer = '" . $site_name . "'"; + if($db->getOne($sql) > 0) + { + $sql = "UPDATE " . $ecs->table('adsense') . " SET clicks = clicks + 1 WHERE from_ad = '-1' AND referer = '" . $site_name . "'"; + } + else + { + $sql = "INSERT INTO " . $ecs->table('adsense') . "(from_ad, referer, clicks) VALUES ('-1', '" . $site_name . "', '1')"; + } + $db->query($sql); + //$db->autoReplace($ecs->table('adsense'), array('from_ad' => -1, 'referer' => $site_name, 'clicks' => 1), array('clicks' => 1)); + $sql = "SELECT goods_name FROM " .$ecs->table('goods'). " WHERE goods_id = $goods_id"; + $res = $db->query($sql); + + $row = $db->fetchRow($res); + + $uri = build_uri('goods', array('gid' => $goods_id), $row['goods_name']); + + ecs_header("Location: $uri\n"); + + exit; + } + else + { + /* 更新站内广告的点击次数 */ + $db->query('UPDATE ' . $ecs->table('ad') . " SET click_count = click_count + 1 WHERE ad_id = '$ad_id'"); + + $sql = "SELECT count(*) FROM " . $ecs->table('adsense') . " WHERE from_ad = '" . $ad_id . "' AND referer = '" . $site_name . "'"; + if($db->getOne($sql) > 0) + { + $sql = "UPDATE " . $ecs->table('adsense') . " SET clicks = clicks + 1 WHERE from_ad = '" . $ad_id . "' AND referer = '" . $site_name . "'"; + } + else + { + $sql = "INSERT INTO " . $ecs->table('adsense') . "(from_ad, referer, clicks) VALUES ('" . $ad_id . "', '" . $site_name . "', '1')"; + } + $db->query($sql); + + /* 跳转到广告的链接页面 */ + if (!empty($_GET['uri'])) + { + $uri = (strpos($_GET['uri'], 'http://') === false && strpos($_GET['uri'], 'https://') === false) ? $ecs->http() . urldecode($_GET['uri']) : urldecode($_GET['uri']); + } + else + { + $uri = $ecs->url(); + } + + ecs_header("Location: $uri\n"); + exit; + } +} + +?> \ No newline at end of file diff --git a/affiliate.php b/affiliate.php new file mode 100644 index 0000000..b1bcf42 --- /dev/null +++ b/affiliate.php @@ -0,0 +1,87 @@ +caching = true; +} + +//$charset = empty($_GET['charset']) ? 'UTF8' : $_GET['charset']; +$display_mode = empty($_GET['display_mode']) ? 'javascript' : $_GET['display_mode']; + +if ( $display_mode == 'javascript' ) +{ + $charset_array=array('UTF8','GBK','gbk','utf8','GB2312','gb2312'); + if(!in_array($charset,$charset_array)) + { + $charset='UTF8'; + } + header('content-type: application/x-javascript; charset=' . ($charset == 'UTF8' ? 'utf-8' : $charset)); +} + +/*------------------------------------------------------ */ +//-- 鍒ゆ柇鏄?惁瀛樺湪缂撳瓨锛屽?鏋滃瓨鍦ㄥ垯璋冪敤缂撳瓨锛屽弽涔嬭?鍙栫浉搴斿唴瀹 +/*------------------------------------------------------ */ +/* 缂撳瓨缂栧彿 */ +$cache_id = sprintf('%X', crc32($_SERVER['QUERY_STRING'])); + +$goodsid = intval($_GET['gid']); +$userid = intval($_GET['u']); +$type = intval($_GET['type']); + + +$tpl = ROOT_PATH . DATA_DIR . '/affiliate.html'; +if (!$smarty->is_cached($tpl, $cache_id)) +{ + $time = gmtime(); + /* 鏍规嵁鍙傛暟鐢熸垚鏌ヨ?璇?彞 */ + + $goods_url = $ecs->url() . "goods.php?u=$userid&id="; + $goods = get_goods_info($goodsid); + $goods['goods_thumb'] = (strpos($goods['goods_thumb'], 'http://') === false && strpos($goods['goods_thumb'], 'https://') === false) ? $ecs->url() . $goods['goods_thumb'] : $goods['goods_thumb']; + $goods['goods_img'] = (strpos($goods['goods_img'], 'http://') === false && strpos($goods['goods_img'], 'https://') === false) ? $ecs->url() . $goods['goods_img'] : $goods['goods_img']; + $goods['shop_price'] = price_format($goods['shop_price']); + + /*if ($charset != 'UTF8') + { + $goods['goods_name'] = ecs_iconv('UTF8', $charset, htmlentities($goods['goods_name'], ENT_QUOTES, 'UTF-8')); + $goods['shop_price'] = ecs_iconv('UTF8', $charset, $goods['shop_price']); + }*/ + + $smarty->assign('goods', $goods); + $smarty->assign('userid', $userid); + $smarty->assign('type', $type); + + $smarty->assign('url', $ecs->url()); + $smarty->assign('goods_url', $goods_url); +} +$output = $smarty->fetch($tpl, $cache_id); +$output = str_replace("\r", '', $output); +$output = str_replace("\n", '', $output); + +if ( $display_mode == 'javascript' ) +{ + echo "document.write('$output');"; +} +else if ( $display_mode == 'iframe' ) +{ + echo $output; +} + +?> \ No newline at end of file diff --git a/animated_favicon.gif b/animated_favicon.gif new file mode 100644 index 0000000..e63152d Binary files /dev/null and b/animated_favicon.gif differ diff --git a/api.php b/api.php new file mode 100644 index 0000000..f23dea8 --- /dev/null +++ b/api.php @@ -0,0 +1,522 @@ +table('goods') . + " WHERE is_delete = 0 AND is_on_sale = 1 AND (last_update > '" . $_POST['last_modify_st_time'] . "' OR last_update = 0)"; + $date_count = $GLOBALS['db']->getRow($sql); + + if (empty($date_count)) + { + api_err('0x003', 'no data to back'); //无符合条件数据 + } + + $page = empty($_POST['pages']) ? 1 : $_POST['pages']; //确定读取哪些记录 + $counts = empty($_POST['counts']) ? 100 : $_POST['counts']; + + $sql = 'SELECT goods_id, last_update AS last_modify' . + ' FROM ' . $GLOBALS['ecs']->table('goods') . + " WHERE is_delete = 0 AND is_on_sale = 1 AND (last_update > '" . $_POST['last_modify_st_time'] . "' OR last_update = 0)". + " LIMIT ".($page - 1) * $counts . ', ' . $counts; + $date_arr = $GLOBALS['db']->getAll($sql); + + if (!empty($_POST['columns'])) + { + $column_arr = explode('|', $_POST['columns']); + foreach ($date_arr as $k => $v) + { + foreach ($v as $key => $val) + { + if (in_array($key, $column_arr)) + { + $re_arr['data_info'][$k][$key] = $val; + } + } + } + } + else + { + $re_arr['data_info'] = $date_arr; + } + + /* 处理更新时间等于0的数据 */ + $sql = 'UPDATE ' . $GLOBALS['ecs']->table('goods') . + " SET last_update = 1 WHERE is_delete = 0 AND is_on_sale = 1 AND last_update = 0"; + $GLOBALS['db']->query($sql, 'SILENT'); + + $re_arr['counts'] = $date_count['count']; + data_back($re_arr, '', RETURN_TYPE); //返回数据 + } + else + { + api_err('0x003', 'required date invalid'); //请求数据异常 + } +} + +/** + * 商品详细信息接口函数 + */ +function search_goods_detail() +{ + check_auth(); //检查基本权限 + + $version = '1.0'; //版本号 + + if ($_POST['api_version'] != $version) //网店的接口版本低 + { + api_err('0x008', 'a low version api'); + } + + if (!empty($_POST['goods_id']) && is_numeric($_POST['goods_id'])) + { + $sql = 'SELECT g.goods_id, g.last_update AS last_modify, g.cat_id, c.cat_name AS category_name, g.brand_id, b.brand_name, g.shop_price AS price, g.goods_sn AS bn, g.goods_name AS name, g.is_on_sale AS marketable, g.goods_weight AS weight, g.goods_number AS store , g.give_integral AS score, g.add_time AS uptime, g.original_img AS image_default, g.goods_desc AS intro' . + ' FROM ' . $GLOBALS['ecs']->table('category') . ' AS c, ' . $GLOBALS['ecs']->table('goods') . ' AS g LEFT JOIN ' . $GLOBALS['ecs']->table('brand') . ' AS b ON g.brand_id = b.brand_id'. + ' WHERE g.cat_id = c.cat_id AND g.goods_id = ' . $_POST['goods_id']; + $goods_data = $GLOBALS['db']->getRow($sql); + + if (empty($goods_data)) + { + api_err('0x003', 'no data to back'); //无符合条件数据 + } + + $goods_data['goods_link'] = 'http://' . $_SERVER['HTTP_HOST'] . '/goods.php?id=' . $goods_data['goods_id']; + $goods_data['image_default'] = 'http://' . $_SERVER['HTTP_HOST'] . '/' . $goods_data['image_default']; + $goods_data['unit'] = '千克'; + $goods_data['brand_name'] = empty($goods_data['brand_name']) ? '' : $goods_data['brand_name']; + + $prop = create_goods_properties($_POST['goods_id']); + $goods_data['props_name'] = $prop['props_name']; + $goods_data['props'] = $prop['props']; + + if (!empty($_POST['columns'])) + { + $column_arr = explode('|', $_POST['columns']); + foreach ($goods_data as $key=>$val) + { + if (in_array($key, $column_arr)) + { + $re_arr['data_info'][$key] = $val; + } + } + } + else + { + $re_arr['data_info'] = $goods_data; + } + + data_back($re_arr, '', RETURN_TYPE); //返回数据 + } + else + { + api_err('0x003', 'required date invalid'); //请求数据异常 + } +} + +/** + * 被删除商品列表接口函数 + */ +function search_deleted_goods_list() +{ + api_err('0x007', '暂时不提供此服务功能'); //服务不可用 +} + +/** + * 获取货品列表接口函数 + */ +function search_products_list() +{ + check_auth(); //检查基本权限 + + $version = '1.0'; //版本号 + + if ($_POST['api_version'] != $version) //网店的接口版本低 + { + api_err('0x008', 'a low version api'); + } + + if (!empty($_POST['goods_id']) && is_numeric($_POST['goods_id']) || !empty($_POST['bn'])) + { + $sql = 'SELECT goods_id, last_update AS last_modify, shop_price AS price, goods_sn AS bn, goods_name AS name, goods_weight AS weight, goods_number AS store, add_time AS uptime' . + ' FROM ' . $GLOBALS['ecs']->table('goods') . + ' WHERE ' . empty($_POST['bn']) ? "goods_id = $_POST[goods_id]" : "goods_sn = $_POST[bn]"; + $goods_data = $GLOBALS['db']->getRow($sql); + + if (empty($goods_data)) + { + api_err('0x003', 'no data to back'); //无符合条件数据 + } + + $goods_data['product_id'] = $_POST['goods_id']; + $goods_data['cost'] = $goods_data['price']; + + $prop = create_goods_properties($_POST['goods_id']); + $goods_data['props'] = $prop['props']; + + if (!empty($_POST['columns'])) + { + $column_arr = explode('|', $_POST['columns']); + foreach ($goods_data as $key=>$val) + { + if (in_array($key, $column_arr)) + { + $re_arr['data_info'][$key] = $val; + } + } + } + else + { + $re_arr['data_info'] = $goods_data; + } + + data_back($re_arr, '', RETURN_TYPE); //返回数据 + } + else + { + api_err('0x003', 'required date invalid'); //请求数据异常 + } +} + +/** + * 获取站点信息接口函数 + */ +function search_site_info() +{ + check_auth(); //检查基本权限 + + $version = '1.0'; //版本号 + + if ($_POST['api_version'] != $version) //网店的接口版本低 + { + api_err('0x008', 'a low version api'); + } + + $sql = 'SELECT code, value'. + ' FROM ' . $GLOBALS['ecs']->table('shop_config') . + " WHERE code IN ('shop_name', 'service_phone')"; + + $siteinfo['data_info'] = $GLOBALS['db']->getRow($sql); + + $siteinfo['data_info']['site_address'] = $_SERVER['SERVER_NAME']; + + data_back($siteinfo, '', RETURN_TYPE); //返回数据 +} + +/** + * 权限校验函数 + */ +function check_auth() +{ + $license = get_shop_license(); // 取出网店 license信息 + if (empty($license['certificate_id']) || empty($license['token']) || empty($license['certi'])) + { + api_err('0x006', 'no certificate'); //没有证书数据,输出系统级错误:用户权限不够 + } + + if (!check_shopex_ac($_POST, $license['token'])) + { + api_err('0x009'); //输出系统级错误:签名无效 + } + + /* 对应用申请的session进行验证 */ + $certi['certificate_id'] = $license['certificate_id']; // 网店证书ID + $certi['app_id'] = 'ecshop_b2c'; // 说明客户端来源 + $certi['app_instance_id'] = 'webcollect'; // 应用服务ID + $certi['version'] = VERSION . '#' . RELEASE; // 网店软件版本号 + $certi['format'] = 'json'; // 官方返回数据格式 + $certi['certi_app'] = 'sess.valid_session'; // 证书方法 + $certi['certi_session'] = $_POST['app_session']; //应用服务器申请的session值 + $certi['certi_ac'] = make_shopex_ac($certi, $license['token']); // 网店验证字符串 + + $request_arr = exchange_shop_license($certi, $license); + if ($request_arr['res'] != 'succ') + { + api_err('0x001', 'session is invalid'); //输出系统级错误:身份验证失败 + } +} + +/** + * 验证POST签名 + * + * @param string $post_params POST传递参数 + * @param string $token 证书加密码 + * + * @return boolean 返回是否有效 + */ +function check_shopex_ac($post_params,$token) +{ + ksort($post_params); + $str = ''; + foreach($post_params as $key=>$value) + { + if ($key!='ac') + { + $str.=$value; + } + } + if ($post_params['ac'] == md5($str.$token)) + { + return true; + } + else + { + return false; + } +} + +/** + * 系统级错误处理 + * + * @param string $err_type 错误类型代号 + * @param string $err_info 错误说明 + * + */ +function api_err($err_type, $err_info = '') +{ + /* 系统级错误列表 */ + $err_arr = array(); + $err_arr['0x001'] = 'Verify fail'; //身份验证失败 + $err_arr['0x002'] = 'Time out'; //请求/执行超时 + $err_arr['0x003'] = 'Data fail'; //数据异常 + $err_arr['0x004'] = 'Db error'; //数据库执行失败 + $err_arr['0x005'] = 'Service error'; //服务器导常 + $err_arr['0x006'] = 'User permissions'; //用户权限不够 + $err_arr['0x007'] = 'Service unavailable'; //服务不可用 + $err_arr['0x008'] = 'Missing Method'; //方法不可用 + $err_arr['0x009'] = 'Missing signature'; //签名无效 + $err_arr['0x010'] = 'Missing api version'; //版本丢失 + $err_arr['0x011'] = 'Api verion error'; //API版本异常 + $err_arr['0x012'] = 'Api need update'; //API需要升级 + $err_arr['0x013'] = 'Shop Error'; //网痁服务异常 + $err_arr['0x014'] = 'Shop Space Error'; //网店空间不足 + + data_back($err_info == '' ? $err_arr[$err_type] : $err_info, $err_type, RETURN_TYPE, 'fail'); //回复请求以错误信息 +} + +/** + * 返回结果集 + * + * @param mixed $info 返回的有效数据集或是错误说明 + * @param string $msg 为空或是错误类型代号 + * @param string $result 请求成功或是失败的标识 + * @param int $post 1为xml方式,2为json方式 + * + */ +function data_back($info, $msg = '', $post, $result = 'success') +{ + /* 分为xml和json两种方式 */ + $data_arr = array('result'=>$result, 'msg'=>$msg, 'info'=>$info); + $data_arr = to_utf8_iconv($data_arr); //确保传递的编码为UTF-8 + + if ($post == 1) + { + /* xml方式 */ + if (class_exists('DOMDocument')) + { + $doc=new DOMDocument('1.0','UTF-8'); + $doc->formatOutput=true; + + $shopex=$doc->createElement('shopex'); + $doc->appendChild($shopex); + + $result=$doc->createElement('result'); + $shopex->appendChild($result); + $result->appendChild($doc->createCDATASection($data_arr['result'])); + + $msg=$doc->createElement('msg'); + $shopex->appendChild($msg); + $msg->appendChild($doc->createCDATASection($data_arr['msg'])); + + $info=$doc->createElement('info'); + $shopex->appendChild($info); + + create_tree($doc, $info, $data_arr['info']); + die($doc->saveXML()); + } + + die('' . array2xml($data_arr)) ; + } + else + { + /* json方式 */ + $json = new JSON; + die($json->encode($data_arr)); //把生成的返回字符串打印出来 + } +} + +/** + * 循环生成xml节点 + * + * @param handle $doc xml实例句柄 + * @param handle $top 当前父节点 + * @param array $info_arr 需要解析的数组 + * @param boolean $have_item 是否是数据数组,是则需要在每条数据上加item父节点 + * + */ +function create_tree($doc, $top, $info_arr, $have_item = false) +{ + if (is_array($info_arr)) + { + foreach ($info_arr as $key => $val) + { + if (is_array($val)) + { + if ($have_item == false) + { + $data_info=$doc->createElement('data_info'); + $top->appendChild($data_info); + create_tree($doc, $data_info, $val, true); + } + else + { + $item=$doc->createElement('item'); + $top->appendChild($item); + $key_code = $doc->createAttribute('key'); + $item->appendChild($key_code); + $key_code->appendChild($doc->createTextNode($key)); + create_tree($doc, $item, $val); + } + } + else + { + $text_code=$doc->createElement($key); + $top->appendChild($text_code); + if (is_string($val)) + { + $text_code->appendChild($doc->createCDATASection($val)); + } + else + { + $text_code->appendChild($doc->createTextNode($val)); + } + } + } + } + else + { + $top->appendChild($doc->createCDATASection($info_arr)); + } +} + +function array2xml($data,$root='shopex'){ + $xml='<'.$root.'>'; + _array2xml($data,$xml); + $xml.=''; + return $xml; +} + +function _array2xml(&$data,&$xml){ + if(is_array($data)){ + foreach($data as $k=>$v){ + if(is_numeric($k)){ + $xml.=''; + $xml.=_array2xml($v,$xml); + $xml.=''; + }else{ + $xml.='<'.$k.'>'; + $xml.=_array2xml($v,$xml); + $xml.=''; + } + } + }elseif(is_numeric($data)){ + $xml.=$data; + }elseif(is_string($data)){ + $xml.=''; + } +} + +function create_goods_properties($goods_id) +{ + /* 对属性进行重新排序和分组 + $sql = "SELECT attr_group ". + "FROM " . $GLOBALS['ecs']->table('goods_type') . " AS gt, " . $GLOBALS['ecs']->table('goods') . " AS g ". + "WHERE g.goods_id='$goods_id' AND gt.cat_id=g.goods_type"; + $grp = $GLOBALS['db']->getOne($sql); + + if (!empty($grp)) + { + $groups = explode("\n", strtr($grp, "\r", '')); + } + */ + + /* 获得商品的规格 */ + $sql = "SELECT a.attr_id, a.attr_name, a.attr_group, a.is_linked, a.attr_type, ". + "g.goods_attr_id, g.attr_value, g.attr_price " . + 'FROM ' . $GLOBALS['ecs']->table('goods_attr') . ' AS g ' . + 'LEFT JOIN ' . $GLOBALS['ecs']->table('attribute') . ' AS a ON a.attr_id = g.attr_id ' . + "WHERE g.goods_id = '$goods_id' " . + 'ORDER BY a.sort_order, g.attr_price, g.goods_attr_id'; + $res = $GLOBALS['db']->getAll($sql); + + $arr = array(); + $arr['props_name'] = array(); // props_name + $arr['props'] = array(); // props + + foreach ($res AS $row) + { + if ($row['attr_type'] == 0) + { + //$group = (isset($groups[$row['attr_group']])) ? $groups[$row['attr_group']] : $GLOBALS['_LANG']['goods_attr']; + + //$arr['props_name'][$row['attr_group']]['name'] = $group; + $arr['props_name'][] = array('name' => $row['attr_name'], 'value' => $row['attr_value']); + + $arr['props'][] = array('pid' => $row['attr_id'], 'vid' => $row['goods_attr_id']); + } + } + + return $arr; +} +?> \ No newline at end of file diff --git a/api/checkorder.php b/api/checkorder.php new file mode 100644 index 0000000..31b4888 --- /dev/null +++ b/api/checkorder.php @@ -0,0 +1,54 @@ + 0, 'new_orders' => 0, 'new_paid' => 0); +$_REQUEST['username'] = urlencode(serialize(json_str_iconv($_REQUEST['username']))); + +/* 检查密码是否正确 */ +$sql = "SELECT COUNT(*) ". + " FROM " . $ecs->table('admin_user') . + " WHERE user_name = '" . trim($_REQUEST['username']). "' AND password = '" . md5(trim($_REQUEST['password'])) . "'"; + +if ($db->getOne($sql)) +{ + /* 新订单 */ + $sql = 'SELECT COUNT(*) FROM ' . $ecs->table('order_info'). + " WHERE order_status = " . OS_UNCONFIRMED; + $res['new_orders'] = $db->getOne($sql); + + /* 待发货的订单: */ + $sql = 'SELECT COUNT(*)'. + ' FROM ' .$ecs->table('order_info') . + " WHERE 1 ". order_query_sql('await_ship'); + $res['new_paid'] = $db->getOne($sql); +} +else +{ + $res['error'] = 1; +} + +$val = $json->encode($res); + +die($val); + +?> \ No newline at end of file diff --git a/api/client/api.php b/api/client/api.php new file mode 100644 index 0000000..c651782 --- /dev/null +++ b/api/client/api.php @@ -0,0 +1,8 @@ + \ No newline at end of file diff --git a/api/client/includes/init.php b/api/client/includes/init.php new file mode 100644 index 0000000..65fa934 --- /dev/null +++ b/api/client/includes/init.php @@ -0,0 +1,112 @@ +set_disable_cache_tables(array($ecs->table('sessions'), $ecs->table('sessions_data'), $ecs->table('cart'))); +$db_host = $db_user = $db_pass = $db_name = NULL; + +/* 载入系统参数 */ +$_CFG = load_config(); + +/* 载入语言包 */ +require(ROOT_PATH.'languages/' .$_CFG['lang']. '/admin/common.php'); +require(ROOT_PATH.'languages/' .$_CFG['lang']. '/admin/log_action.php'); + +/* 初始化session */ +include(ROOT_PATH . 'includes/cls_session.php'); + +$sess = new cls_session($db, $ecs->table('sessions'), $ecs->table('sessions_data'), 'CL_ECSCP_ID'); + +define('SESS_ID', $sess->get_session_id()); + +/* 判断是否登录了 */ +if ((!isset($_SESSION['admin_id']) || intval($_SESSION['admin_id']) <= 0) && ($_POST['Action'] != 'UserLogin')) +{ + client_show_message(110); +} + +if ($_CFG['shop_closed'] == 1) +{ + /* 商店关闭了,输出关闭的消息 */ + client_show_message(105); +} + +?> \ No newline at end of file diff --git a/api/client/includes/lib_api.php b/api/client/includes/lib_api.php new file mode 100644 index 0000000..f94a33e --- /dev/null +++ b/api/client/includes/lib_api.php @@ -0,0 +1,1328 @@ +decode($str, 1); + $_POST = $json_obj; + } + + function show_json(&$json, $array, $convert = false) + { + $json_str = $json->encode($array, false); + if (!$convert && defined('EC_CHARSET') && EC_CHARSET == 'gbk') + { + $json_str = ecs_iconv('UTF-8', 'GBK', $json_str); + } + @header('Content-type:text/html; charset='.EC_CHARSET); + exit($json_str); + } + + function admin_privilege($priv_str) + { + if(isset($_SESSION['admin_id']) && intval($_SESSION['admin_id']) > 0) + { + if ($_SESSION['action_list'] == 'all') + { + return true; + } + if (strpos(',' . $_SESSION['action_list'] . ',', ',' . $priv_str . ',') !== false) + { + return true; + } + } + client_show_message(101); + } + + /** + * 检查分类是否已经存在 + * + * @param string $cat_name 分类名称 + * @param integer $parent_cat 上级分类 + * @param integer $exclude 排除的分类ID + * + * @return boolean + */ + function cat_is_exists($cat_name, $parent_cat, $exclude = 0) + { + $sql = "SELECT COUNT(*) FROM " .$GLOBALS['ecs']->table('category'). + " WHERE parent_id = '$parent_cat' AND cat_name = '$cat_name' AND cat_id<>'$exclude'"; + return ($GLOBALS['db']->getOne($sql) > 0) ? true : false; + } + + function debug_text($str='') + { + $file = 'D:/debug.txt'; + $fp = fopen($file, 'a'); + if($str == ''){ + $str .= implode('', $_POST); + $str .= implode('', $_GET); + $str .= implode('', $_REQUEST); + } + fwrite($fp, $str); + fclose($fp); + } + + /** + * 生成随机的数字串 + * + * @author: weber liu + * @return string + */ + function random_filename() + { + $str = ''; + for($i = 0; $i < 9; $i++) + { + $str .= mt_rand(0, 9); + } + + return gmtime() . $str; + } + + /** + * 生成指定目录不重名的文件名 + * + * @access public + * @param string $dir 要检查是否有同名文件的目录 + * + * @return string 文件名 + */ + function unique_name($dir) + { + $filename = ''; + while (empty($filename)) + { + $filename = random_filename(); + if (file_exists($dir . $filename . '.jpg') || file_exists($dir . $filename . '.gif') || file_exists($dir . $filename . '.png')) + { + $filename = ''; + } + } + + return $filename; + } + + /** + * 上传图片 + * + * @param string $str 二进制字符串 + * @param string $dir 目录路径 + * @param string $img_name 图片名称 + * @return 图片名称 或 假值 + */ + function upload_image($str, $dir='', $img_name='') + { + if(empty($str['Data'])) + { + return false; + } + $allow_file_type = array('jpg', 'jpeg', 'png', 'gif', 'bmp'); + if (empty($dir)) + { + /* 创建当月目录 */ + $dir = date('Ym'); + $dir = ROOT_PATH . '/images/'.$dir; + } + else + { + /* 创建目录 */ + $dir = ROOT_PATH . '/'.$dir; + if ($img_name) + { + /* 判断$img_name文件后缀与路径 */ + $img_name = basename($img_name); + $img_name_ext = substr($img_name,strrpos($img_name, '.')+1); + if (!in_array($img_name_ext, $allow_file_type)) + { + return false; + } + $img_name = $dir.'/' . $img_name; // 将图片定位到正确地址 + } + } + if (!file_exists($dir)) + { + if (!make_dir($dir)) + { + /* 创建目录失败 */ + return false; + } + } + if (empty($img_name)) + { + $img_name = unique_name($dir); + $img_name = $dir . '/' . $img_name . '.' . $str['Type']; + } + $binary_data = base64_decode($str['Data']); + if($fp = @fopen($img_name, 'wb')) + { + @fwrite($fp, $binary_data); + @fclose($fp); + return str_replace(ROOT_PATH . '/', '', $img_name); + } + else + { + return false; + } + } + + /** + * 输出信息到客户端 + * + * @param int $code 错误代号 + * @param boolean $result 返回结果 + * @param string $msg 错误信息 + * @param int $id 返回值 + */ + function client_show_message($code=0, $result=false, $message = '', $id=0, $custom_message=false, $charset='') + { + $msg = $GLOBALS['common_message']; + $msg['Result'] = $result; + $msg['MessageCode'] = $code; + $msg['MessageString'] = ($custom_message === false) ? $GLOBALS['_ALANG'][$code] . $message : $message; + $msg['InsertID'] = $id; + $msg['Charset'] = $charset; + show_json($GLOBALS['json'], $msg); + } + + function client_check_image_size($str) + { + $max_size = 2097152; // 2M + return $max_size > strlen($str['Data']); + } + + function get_goods_image_url($goods_id, $img_url, $thumb = false) + { + return str_replace('/api.php', '', preg_replace("/\/api\/client/", '', $GLOBALS['ecs']->url())) . $img_url; + } + + /** + * 处理替换数组中的十六进制字符值 + * + * @param array $array 替换数组 + * + * @return array + */ + function process_replace_array($array) + { + foreach ($array['search'] as $key => $val) + { + $array['search'][$key] = chr(hexdec($val{0}.$val{1})).chr(hexdec($val{2}.$val{3})); + } + return $array; + } + + if (!function_exists("htmlspecialchars_decode")) + { + function htmlspecialchars_decode($string, $quote_style = ENT_COMPAT) + { + return strtr($string, array_flip(get_html_translation_table(HTML_SPECIALCHARS, $quote_style))); + } + } + + /** + * 用户登录函数 + * 验证登录,设置COOKIE + * + * @param array $post + */ + function API_UserLogin($post) + { + $post['username'] = isset($post['UserId']) ? trim($post['UserId']) : ''; + $post['password'] = isset($post['Password']) ? strtolower(trim($post['Password'])) : ''; + + /* 检查密码是否正确 */ + $sql = "SELECT user_id, user_name, password, action_list, last_login". + " FROM " . $GLOBALS['ecs']->table('admin_user') . + " WHERE user_name = '" . $post['username']. "'"; + + $row = $GLOBALS['db']->getRow($sql); + + if ($row) + { + if ($row['password'] != $post['password']) + { + client_show_message(103); + } + require_once(ROOT_PATH. ADMIN_PATH . '/includes/lib_main.php'); + // 登录成功 + set_admin_session($row['user_id'], $row['user_name'], $row['action_list'], $row['last_login']); + + // 更新最后登录时间和IP + $GLOBALS['db']->query("UPDATE " .$GLOBALS['ecs']->table('admin_user'). + " SET last_login='" . gmtime() . "', last_ip='" . real_ip() . "'". + " WHERE user_id='$_SESSION[admin_id]'"); + client_show_message(100, true, VERSION, 0, true, EC_CHARSET); + } + else + { + client_show_message(103); + } + } + + /** + * 添加分类 + * + * @param array $post + */ + function API_AddCategory($post) + { + /* 加载后台主操作函数 */ + require_once(ROOT_PATH. ADMIN_PATH . '/includes/lib_main.php'); + + /* 检查权限 */ + admin_privilege('cat_manage'); + /* 初始化变量 */ + $cat = array(); + $cat['cat_id'] = !empty($_POST['cat_id']) ? intval($_POST['cat_id']) : 0; + $cat['parent_id'] = !empty($_POST['parent_id']) ? intval($_POST['parent_id']) : 0; + $cat['sort_order'] = !empty($_POST['sort_order']) ? intval($_POST['sort_order']) : 0; + $cat['keywords'] = !empty($_POST['keywords']) ? trim($_POST['keywords']) : ''; + $cat['cat_desc'] = !empty($_POST['cat_desc']) ? $_POST['cat_desc'] : ''; + $cat['measure_unit'] = !empty($_POST['measure_unit']) ? trim($_POST['measure_unit']) : ''; + $cat['cat_name'] = !empty($_POST['cat_name']) ? trim($_POST['cat_name']) : ''; + $cat['show_in_nav'] = !empty($_POST['show_in_nav']) ? intval($_POST['show_in_nav']): 0; + $cat['style'] = !empty($_POST['style']) ? trim($_POST['style']) : ''; + $cat['is_show'] = !empty($_POST['is_show']) ? intval($_POST['is_show']) : 0; + $cat['grade'] = !empty($_POST['grade']) ? intval($_POST['grade']) : 0; + $cat['filter_attr'] = !empty($_POST['filter_attr']) ? intval($_POST['filter_attr']) : 0; + + if (cat_is_exists($cat['cat_name'], $cat['parent_id'])) + { + /* 同级别下不能有重复的分类名称 */ + client_show_message(403); + } + if($cat['grade'] > 10 || $cat['grade'] < 0) + { + /* 价格区间数超过范围 */ + client_show_message(402); + } + if ($GLOBALS['db']->autoExecute($GLOBALS['ecs']->table('category'), $cat) !== false) + { + $insert_id = $GLOBALS['db']->insert_id(); + if($cat['show_in_nav'] == 1) + { + $vieworder = $GLOBALS['db']->getOne("SELECT max(vieworder) FROM ". $GLOBALS['ecs']->table('nav') . " WHERE type = 'middle'"); + $vieworder += 2; + //显示在自定义导航栏中 + $sql = "INSERT INTO " . $GLOBALS['ecs']->table('nav') . + " (name, ctype, cid, ifshow, vieworder, opennew, url, type)". + " VALUES('" . $cat['cat_name'] . "', 'c', '".$insert_id."','1','$vieworder','0', '" . build_uri('category', array('cid'=> $insert_id), $cat['cat_name']) . "','middle')"; + $GLOBALS['db']->query($sql); + } + + admin_log($_POST['cat_name'], 'add', 'category'); // 记录管理员操作 + clear_cache_files(); // 清除缓存 + + /*添加链接*/ + client_show_message(0, true); + } + } + + /** + * 获取分类 + * + * @param array $post + */ + function API_GetCategory($post) + { + $sql = "SELECT c.cat_id, c.cat_name, c.keywords, c.cat_desc, c.parent_id, c.sort_order, c.measure_unit, c.show_in_nav, c.style, c.is_show, c.grade, c.filter_attr, COUNT(s.cat_id) AS has_children ". + 'FROM ' . $GLOBALS['ecs']->table('category') . " AS c ". + "LEFT JOIN " . $GLOBALS['ecs']->table('category') . " AS s ON s.parent_id=c.cat_id ". + " GROUP BY c.cat_id ". + 'ORDER BY parent_id, sort_order ASC'; + $result = $GLOBALS['db']->getAllCached($sql); + foreach ($result as $key => $cat) + { + $result[$key]['is_show'] = ($cat['is_show'] == 1); + $result[$key]['show_in_nav'] = ($cat['show_in_nav'] == 1); + } + show_json($GLOBALS['json'], $result, true); + } + + /** + * 添加品牌 + * + * @param array $post + */ + function API_AddBrand($post) + { + + /* 加载后台主操作函数 */ + require_once(ROOT_PATH . ADMIN_PATH . '/includes/lib_main.php'); + require_once(ROOT_PATH . ADMIN_PATH . '/includes/cls_exchange.php'); + require_once(ROOT_PATH . 'includes/cls_image.php'); + + /* 检查权限 */ + admin_privilege('brand_manage'); + + $is_show = isset($_POST['is_show']) ? 1 : 0; + + /*检查品牌名是否重复*/ + $exc = new exchange($GLOBALS['ecs']->table("brand"), $GLOBALS['db'], 'brand_id', 'brand_name'); + $is_only = $exc->is_only('brand_name', $_POST['brand_name'], '', ''); + + if (!$is_only) + { + client_show_message(301); + } + + /* 处理图片 */ + $img_name = upload_image($_POST['brand_logo'], 'brandlogo'); + if($img_name !== false) + { + $img_name = basename($img_name); + } + else + { + $img_name = ''; + } + /*插入数据*/ + + $sql = "INSERT INTO ".$GLOBALS['ecs']->table('brand')."(brand_name, site_url, brand_desc, brand_logo, is_show, sort_order) ". + "VALUES ('$_POST[brand_name]', '$_POST[site_url]', '$_POST[brand_desc]', '$img_name', '$is_show', '$_POST[sort_order]')"; + //debug_text($sql); + $GLOBALS['db']->query($sql); + + $insert_id = $GLOBALS['db']->insert_id(); + admin_log($_POST['brand_name'],'add','brand'); + + /* 清除缓存 */ + clear_cache_files(); + + client_show_message(0, true); + } + + /** + * 获取品牌数据 + * + * @param array $post + */ + function API_GetBrand($post) + { + $sql = "SELECT brand_id, brand_name, brand_logo, brand_desc, site_url, is_show FROM ".$GLOBALS['ecs']->table('brand')." ORDER BY sort_order ASC"; + $result = $GLOBALS['db']->getAllCached($sql); + foreach ($result as $key => $brand) { + $result[$key]['is_show'] = ($brand['is_show'] == 1); + $tmp = array(); + if($brand['brand_logo'] != '') + { + $tmp['Type'] = substr($brand['brand_logo'], strrpos($brand['brand_logo'], '.')+1); + $tmp['Data'] = 'data/brandlogo/' . $brand['brand_logo']; + } + else + { + $tmp['Type'] = ''; + $tmp['Data'] = ''; + } + + $result[$key]['brand_logo'] = $tmp; + } + show_json($GLOBALS['json'], $result, true); + } + + /** + * 添加商品 + * + * @param array $post + */ + function API_AddGoods($post) + { + //debug_text(); + global $_CFG; + + /* 加载后台操作类与函数 */ + require_once(ROOT_PATH . ADMIN_PATH . '/includes/lib_main.php'); + require_once(ROOT_PATH . ADMIN_PATH . '/includes/lib_goods.php'); + require_once(ROOT_PATH . 'includes/cls_image.php'); + + /* 检查权限 */ + admin_privilege('goods_manage'); + + $image = new cls_image($GLOBALS['_CFG']['bgcolor']); + $code = empty($_POST['extension_code']) ? '' : trim($_POST['extension_code']); + + /* 插入还是更新的标识 */ + $is_insert = $_POST['act'] == 'insert'; + + /* 如果是更新,先检查该商品是否存在,不存在,则退出。 */ + if (!$is_insert) + { + $sql = "SELECT COUNT(*) FROM " . $GLOBALS['ecs']->table('goods') . + " WHERE goods_id = '$_POST[goods_id]' AND is_delete = 0"; + if ($GLOBALS['db']->getOne($sql) <= 0) + { + client_show_message(240); //货号重复 + } + } + /* 检查货号是否重复 */ + if ($_POST['goods_sn']) + { + $sql = "SELECT COUNT(*) FROM " . $GLOBALS['ecs']->table('goods') . + " WHERE goods_sn = '$_POST[goods_sn]' AND is_delete = 0 AND goods_id <> '$_POST[goods_id]'"; + if ($GLOBALS['db']->getOne($sql) > 0) + { + client_show_message(200); //货号重复 + } + } + + /* 处理商品图片 */ + $goods_img = ''; // 初始化商品图片 + $goods_thumb = ''; // 初始化商品缩略图 + $original_img = ''; // 初始化原始图片 + $old_original_img = ''; // 初始化原始图片旧图 + + $allow_file_type = array('jpg', 'jpeg', 'png', 'gif'); + if(!empty($_POST['goods_img']['Data'])) + { + if(!in_array($_POST['goods_img']['Type'], $allow_file_type)) + { + client_show_message(201); + } + if(client_check_image_size($_POST['goods_img']['Data']) === false) + { + client_show_message(202); + } + if ($_POST['goods_id'] > 0) + { + /* 删除原来的图片文件 */ + $sql = "SELECT goods_thumb, goods_img, original_img " . + " FROM " . $GLOBALS['ecs']->table('goods') . + " WHERE goods_id = '$_POST[goods_id]'"; + $row = $GLOBALS['db']->getRow($sql); + if ($row['goods_thumb'] != '' && is_file(ROOT_PATH . '/' . $row['goods_thumb'])) + { + @unlink(ROOT_PATH . '/' . $row['goods_thumb']); + } + if ($row['goods_img'] != '' && is_file(ROOT_PATH . '/' . $row['goods_img'])) + { + @unlink(ROOT_PATH . '/' . $row['goods_img']); + } + if ($row['original_img'] != '' && is_file(ROOT_PATH . '/' . $row['original_img'])) + { + /* 先不处理,以防止程序中途出错停止 */ + //$old_original_img = $row['original_img']; //记录旧图路径 + } + } + + $original_img = upload_image($_POST['goods_img']); // 原始图片 + if ($original_img === false) + { + client_show_message(210); // 写入商品图片出错 + } + $goods_img = $original_img; // 商品图片 + + /* 复制一份相册图片 */ + $img = $original_img; // 相册图片 + $pos = strpos(basename($img), '.'); + $newname = dirname($img) . '/' . random_filename() . substr(basename($img), $pos); + if (!copy(ROOT_PATH . '/' . $img, ROOT_PATH .'/'. $newname)) + { + client_show_message(211); // 复制相册图片时出错 + } + $img = $newname; + + $gallery_img = $img; + $gallery_thumb = $img; + + /* 图片属性 */ + $img_property = ($image->gd_version() > 0)?getimagesize(ROOT_PATH .'/'. $goods_img):array(); + + // 如果系统支持GD,缩放商品图片,且给商品图片和相册图片加水印 + if ($image->gd_version() > 0 && $image->check_img_function($img_property[2])) + { + // 如果设置大小不为0,缩放图片 + if ($GLOBALS['_CFG']['image_width'] != 0 || $GLOBALS['_CFG']['image_height'] != 0) + { + $goods_img = $image->make_thumb(ROOT_PATH .'/'. $goods_img, $GLOBALS['_CFG']['image_width'], $GLOBALS['_CFG']['image_height']); + if ($goods_img === false) + { + client_show_message(212); + } + } + + // 加水印 + if (intval($GLOBALS['_CFG']['watermark_place']) > 0 && !empty($GLOBALS['_CFG']['watermark'])) + { + if ($image->add_watermark(ROOT_PATH . '/' .$goods_img,'',$GLOBALS['_CFG']['watermark'], $GLOBALS['_CFG']['watermark_place'], $GLOBALS['_CFG']['watermark_alpha']) === false) + { + client_show_message(213); + } + + $newname = dirname($img) . '/' . random_filename() . substr(basename($img), $pos); + if (!copy(ROOT_PATH . '/'. $img, ROOT_PATH . '/'. $newname)) + { + client_show_message(214); + } + $gallery_img = $newname; + if ($image->add_watermark(ROOT_PATH .'/'. $gallery_img,'',$GLOBALS['_CFG']['watermark'], $GLOBALS['_CFG']['watermark_place'], $GLOBALS['_CFG']['watermark_alpha']) === false) + { + client_show_message(213); + } + } + + // 相册缩略图 + if ($_CFG['thumb_width'] != 0 || $_CFG['thumb_height'] != 0) + { + $gallery_thumb = $image->make_thumb(ROOT_PATH .'/'. $img, $GLOBALS['_CFG']['thumb_width'], $GLOBALS['_CFG']['thumb_height']); + if ($gallery_thumb === false) + { + client_show_message(215); + } + } + } + } + if(!empty($_POST['goods_thumb']['Data'])) + { + if(!in_array($_POST['goods_thumb']['Type'], $allow_file_type)) + { + client_show_message(203); + } + if(client_check_image_size($_POST['goods_thumb']['Data']) === false) + { + client_show_message(204); + } + $goods_thumb = upload_image($_POST['goods_thumb']); + if ($goods_thumb === false) + { + client_show_message(217); + } + } + else + { + // 未上传,如果自动选择生成,且上传了商品图片,生成所略图 + if (isset($_POST['auto_thumb']) && !empty($original_img)) + { + // 如果设置缩略图大小不为0,生成缩略图 + if ($_CFG['thumb_width'] != 0 || $_CFG['thumb_height'] != 0) + { + $goods_thumb = $image->make_thumb(ROOT_PATH .'/'. $original_img, $GLOBALS['_CFG']['thumb_width'], $GLOBALS['_CFG']['thumb_height']); + if ($goods_thumb === false) + { + client_show_message(218); + } + } + else + { + $goods_thumb = $original_img; + } + } + } + + /* 如果没有输入商品货号则自动生成一个商品货号 */ + if (empty($_POST['goods_sn'])) + { + $max_id = $is_insert ? $GLOBALS['db']->getOne("SELECT MAX(goods_id) + 1 FROM ".$GLOBALS['ecs']->table('goods')) : $_POST['goods_id']; + $goods_sn = generate_goods_sn($max_id); + } + else + { + $goods_sn = $_POST['goods_sn']; + } + + /* 处理商品数据 */ + $is_promote = (isset($_POST['is_promote']) && $_POST['is_promote']) ? 1 : 0; + $shop_price = !empty($_POST['shop_price']) ? $_POST['shop_price'] : 0; + $market_price = !empty($_POST['market_price']) ? $_POST['market_price'] : ($GLOBALS['_CFG']['market_price_rate'] * $shop_price); + $promote_price = !empty($_POST['promote_price']) ? floatval($_POST['promote_price'] ) : 0; + $promote_start_date = ($is_promote && !empty($_POST['promote_start_date'])) ? local_strtotime($_POST['promote_start_date']) : 0; + $promote_end_date = ($is_promote && !empty($_POST['promote_end_date'])) ? local_strtotime($_POST['promote_end_date']) : 0; + + $goods_weight = !empty($_POST['goods_weight']) ? $_POST['goods_weight'] * $_POST['weight_unit'] : 0; + $is_best = (isset($_POST['is_best']) && $_POST['is_best']) ? 1 : 0; + $is_new = (isset($_POST['is_new']) && $_POST['is_new']) ? 1 : 0; + $is_hot = (isset($_POST['is_hot']) && $_POST['is_hot']) ? 1 : 0; + $is_on_sale = (isset($_POST['is_on_sale']) && $_POST['is_on_sale']) ? 1 : 0; + $is_alone_sale = (isset($_POST['is_alone_sale']) && $_POST['is_alone_sale']) ? 1 : 0; + $goods_number = isset($_POST['goods_number']) ? $_POST['goods_number'] : 0; + $warn_number = isset($_POST['warn_number']) ? $_POST['warn_number'] : 0; + $goods_type = isset($_POST['goods_type']) ? $_POST['goods_type'] : 0; + + $goods_name_style = $_POST['goods_name_color'] . '+' . $_POST['goods_name_style']; + $catgory_id = empty($_POST['cat_id']) ? '' : intval($_POST['cat_id']); + $brand_id = empty($_POST['brand_id']) ? '' : intval($_POST['brand_id']); + $new_brand_name = empty($_POST['new_brand_name']) ? '' : trim($_POST['new_brand_name']); + $new_cat_name = empty($_POST['new_cat_name']) ? '' : trim($_POST['new_cat_name']); + + if($catgory_id == '' && $new_cat_name != '') + { + if (cat_exists($new_cat_name, $_POST['parent_cat'])) + { + /* 同级别下不能有重复的分类名称 */ + client_show_message(219); + } + } + + if($brand_id == '' && $new_brand_name != '') + { + if (brand_exists($new_brand_name)) + { + /* 同级别下不能有重复的品牌名称 */ + client_show_message(220); + } + } + + //处理快速添加分类 + if($catgory_id == '' && $new_cat_name != '') + { + $sql = "INSERT INTO " . $GLOBALS['ecs']->table('category') . "(cat_name, parent_id, is_show)" . + "VALUES ( '$new_cat_name', '$_POST[parent_cat]', 1)"; + + $GLOBALS['db']->query($sql); + $catgory_id = $GLOBALS['db']->insert_id(); + } + + //处理快速添加品牌 + if($brand_id == '' && $new_brand_name != '') + { + $sql = "INSERT INTO ".$GLOBALS['ecs']->table('brand')."(brand_name) " . "VALUES ('$new_brand_name')"; + $GLOBALS['db']->query($sql); + + $brand_id = $GLOBALS['db']->insert_id(); + } + + /* 处理商品详细描述 */ + $_POST['goods_desc'] = htmlspecialchars_decode($_POST['goods_desc']); + + /* 入库 */ + if ($is_insert) + { + if ($code == '') + { + $sql = "INSERT INTO " . $GLOBALS['ecs']->table('goods') . " (goods_name, goods_name_style, goods_sn, " . + "cat_id, brand_id, shop_price, market_price, is_promote, promote_price, " . + "promote_start_date, promote_end_date, goods_img, goods_thumb, original_img, keywords, goods_brief, " . + "seller_note, goods_weight, goods_number, warn_number, integral, give_integral, is_best, is_new, is_hot, " . + "is_on_sale, is_alone_sale, goods_desc, add_time, last_update, goods_type)" . + "VALUES ('$_POST[goods_name]', '$goods_name_style', '$goods_sn', '$catgory_id', " . + "'$brand_id', '$shop_price', '$market_price', '$is_promote','$promote_price', ". + "'$promote_start_date', '$promote_end_date', '$goods_img', '$goods_thumb', '$original_img', ". + "'$_POST[keywords]', '$_POST[goods_brief]', '$_POST[seller_note]', '$goods_weight', '$goods_number',". + " '$warn_number', '$_POST[integral]', '" . intval($_POST['give_integral']) . "', '$is_best', '$is_new', '$is_hot', '$is_on_sale', '$is_alone_sale', ". + " '$_POST[goods_desc]', '" . gmtime() . "', '". gmtime() ."', '$goods_type')"; + } + else + { + $sql = "INSERT INTO " . $GLOBALS['ecs']->table('goods') . " (goods_name, goods_name_style, goods_sn, " . + "cat_id, brand_id, shop_price, market_price, is_promote, promote_price, " . + "promote_start_date, promote_end_date, goods_img, goods_thumb, original_img, keywords, goods_brief, " . + "seller_note, goods_weight, goods_number, warn_number, integral, give_integral, is_best, is_new, is_hot, is_real, " . + "is_on_sale, is_alone_sale, goods_desc, add_time, last_update, goods_type, extension_code)" . + "VALUES ('$_POST[goods_name]', '$goods_name_style', '$goods_sn', '$catgory_id', " . + "'$brand_id', '$shop_price', '$market_price', '$is_promote', '$promote_price', ". + "'$promote_start_date', '$promote_end_date', '$goods_img', '$goods_thumb', '$original_img', ". + "'$_POST[keywords]', '$_POST[goods_brief]', '$_POST[seller_note]', '$goods_weight', '$goods_number',". + " '$warn_number', '$_POST[integral]', '" . intval($_POST['give_integral']) . "', '$is_best', '$is_new', '$is_hot', 0, '$is_on_sale', '$is_alone_sale', ". + " '$_POST[goods_desc]', '" . gmtime() . "', '". gmtime() ."', '$goods_type', '$code')"; + } + } + else + { + /* 将上传的新图片图片名改为原图片 */ + if ($goods_img && $row['goods_img']) + { + if (is_file(ROOT_PATH . $row['goods_img'])) + { + @unlink(ROOT_PATH . $row['goods_img']); + } + @rename(ROOT_PATH . $goods_img, ROOT_PATH . $row['goods_img']); + if (is_file(ROOT_PATH . $row['original_img'])) + { + @unlink(ROOT_PATH . $row['original_img']); + } + @rename(ROOT_PATH . $original_img, ROOT_PATH . $row['original_img']); + } + + if ($goods_thumb && $row['goods_thumb']) + { + if (is_file(ROOT_PATH . $row['goods_thumb'])) + { + @unlink(ROOT_PATH . $row['goods_thumb']); + } + @rename(ROOT_PATH . $goods_thumb, ROOT_PATH . $row['goods_thumb']); + } + + $sql = "UPDATE " . $GLOBALS['ecs']->table('goods') . " SET " . + "goods_name = '$_POST[goods_name]', " . + "goods_name_style = '$goods_name_style', " . + "goods_sn = '$goods_sn', " . + "cat_id = '$catgory_id', " . + "brand_id = '$brand_id', " . + "shop_price = '$shop_price', " . + "market_price = '$market_price', " . + "is_promote = '$is_promote', " . + "promote_price = '$promote_price', " . + "promote_start_date = '$promote_start_date', " . + "promote_end_date = '$promote_end_date', "; + + /* 如果以前没上传过图片,需要更新数据库 */ + if ($goods_img && empty($row['goods_img'])) + { + $sql .= "goods_img = '$goods_img', original_img = '$original_img', "; + } + if (!empty($goods_thumb)) + { + $sql .= "goods_thumb = '$goods_thumb', "; + } + if ($code != '') + { + $sql .= "is_real=0, extension_code='$code', "; + } + $sql .= "keywords = '$_POST[keywords]', " . + "goods_brief = '$_POST[goods_brief]', " . + "seller_note = '$_POST[seller_note]', " . + "goods_weight = '$goods_weight'," . + "goods_number = '$goods_number', " . + "warn_number = '$warn_number', " . + "integral = '$_POST[integral]', " . + "give_integral = '". $_POST['give_integral'] ."', " . + "is_best = '$is_best', " . + "is_new = '$is_new', " . + "is_hot = '$is_hot', " . + "is_on_sale = '$is_on_sale', " . + "is_alone_sale = '$is_alone_sale', " . + "goods_desc = '$_POST[goods_desc]', " . + "last_update = '". gmtime() ."', ". + "goods_type = '$goods_type' " . + "WHERE goods_id = '$_POST[goods_id]' LIMIT 1"; + } + $GLOBALS['db']->query($sql); + + /* 商品编号 */ + $goods_id = $is_insert ? $GLOBALS['db']->insert_id() : $_POST['goods_id']; + + /* 记录日志 */ + if ($is_insert) + { + admin_log($_POST['goods_name'], 'add', 'goods'); + } + else + { + admin_log($_POST['goods_name'], 'edit', 'goods'); + } + + /* 处理属性 */ + if (isset($_POST['attr_id_list']) && isset($_POST['attr_value_list'])) + { + // 取得原有的属性值 + $goods_attr_list = array(); + + $keywords_arr = explode(" ", $_POST['keywords']); + + $keywords_arr = array_flip($keywords_arr); + if (isset($keywords_arr[''])) + { + unset($keywords_arr['']); + } + + $sql = "SELECT attr_id, attr_index FROM " . $GLOBALS['ecs']->table('attribute') . " WHERE cat_id = '$goods_type' "; + + $attr_res = $GLOBALS['db']->query($sql); + + $attr_list = array(); + + while ($row = $GLOBALS['db']->fetchRow($attr_res)) + { + $attr_list[$row['attr_id']] = $row['attr_index']; + } + + $sql = "SELECT * FROM " . $GLOBALS['ecs']->table('goods_attr') . " WHERE goods_id = '$goods_id' "; + + $res = $GLOBALS['db']->query($sql); + + while ($row = $GLOBALS['db']->fetchRow($res)) + { + $goods_attr_list[$row['attr_id']][$row['attr_value']] = array('sign' => 'delete', 'goods_attr_id' => $row['goods_attr_id']); + } + + // 循环现有的,根据原有的做相应处理 + foreach ($_POST['attr_id_list'] AS $key => $attr_id) + { + $attr_value = $_POST['attr_value_list'][$key]; + $attr_price = $_POST['attr_price_list'][$key]; + if (!empty($attr_value)) + { + if (isset($goods_attr_list[$attr_id][$attr_value])) + { + // 如果原来有,标记为更新 + $goods_attr_list[$attr_id][$attr_value]['sign'] = 'update'; + $goods_attr_list[$attr_id][$attr_value]['attr_price'] = $attr_price; + } + else + { + // 如果原来没有,标记为新增 + $goods_attr_list[$attr_id][$attr_value]['sign'] = 'insert'; + $goods_attr_list[$attr_id][$attr_value]['attr_price'] = $attr_price; + } + + $val_arr = explode(' ', $attr_value); + + foreach ($val_arr AS $k => $v) + { + if (!isset($keywords_arr[$v]) && $attr_list[$attr_id] == "1") + { + $keywords_arr[$v] = $v; + } + } + } + } + + $keywords = join(' ', array_flip($keywords_arr)); + + $sql = "UPDATE " .$GLOBALS['ecs']->table('goods'). " SET keywords = '$keywords' WHERE goods_id = '$goods_id' LIMIT 1"; + + $GLOBALS['db']->query($sql); + + /* 插入、更新、删除数据 */ + foreach ($goods_attr_list as $attr_id => $attr_value_list) + { + foreach ($attr_value_list as $attr_value => $info) + { + if ($info['sign'] == 'insert') + { + $sql = "INSERT INTO " .$GLOBALS['ecs']->table('goods_attr'). " (attr_id, goods_id, attr_value, attr_price)". + "VALUES ('$attr_id', '$goods_id', '$attr_value', '$info[attr_price]')"; + } + elseif ($info['sign'] == 'update') + { + $sql = "UPDATE " .$GLOBALS['ecs']->table('goods_attr'). " SET attr_price = '$info[attr_price]' WHERE goods_attr_id = '$info[goods_attr_id]' LIMIT 1"; + } + else + { + $sql = "DELETE FROM " .$GLOBALS['ecs']->table('goods_attr'). " WHERE goods_attr_id = '$info[goods_attr_id]' LIMIT 1"; + } + $GLOBALS['db']->query($sql); + } + } + } + + /* 处理会员价格 */ + if (isset($_POST['user_rank']) && isset($_POST['user_price'])) + { + handle_member_price($goods_id, $_POST['user_rank'], $_POST['user_price']); + } + + /* 处理扩展分类 */ + if (isset($_POST['other_cat'])) + { + handle_other_cat($goods_id, array_unique($_POST['other_cat'])); + } + + if ($is_insert) + { + /* 处理关联商品 */ + handle_link_goods($goods_id); + + /* 处理组合商品 */ + handle_group_goods($goods_id); + + /* 处理关联文章 */ + handle_goods_article($goods_id); + } + + /* 如果有图片,把商品图片加入图片相册 */ + if (isset($img)) + { + $sql = "INSERT INTO " . $GLOBALS['ecs']->table('goods_gallery') . " (goods_id, img_url, img_desc, thumb_url, img_original) " . + "VALUES ('$goods_id', '$gallery_img', '', '$gallery_thumb', '$img')"; + $GLOBALS['db']->query($sql); + } + + /* 处理相册图片 + handle_gallery_image($goods_id, $_FILES['img_url'], $_POST['img_desc']); + */ + if(!empty($_POST['img_url'])) + { + foreach ($_POST['img_url'] as $key => $img_url) + { + if(!in_array($img_url['Type'], $allow_file_type)) + { + client_show_message(205); + } + if(client_check_image_size($img_url['Data']) === false) + { + client_show_message(206); + } + $img_original = upload_image($img_url); + if($img_original === false) + { + continue; + } + + // 暂停生成缩略图 + /* + $thumb_url = $image->make_thumb(ROOT_PATH . $img_original, $GLOBALS['_CFG']['thumb_width'], $GLOBALS['_CFG']['thumb_height']); + $thumb_url = is_string($thumb_url) ? $thumb_url : ''; + + $img_url = $img_original; + + // 如果服务器支持GD 则添加水印 + if (gd_version() > 0) + { + $pos = strpos(basename($img_original), '.'); + $newname = dirname($img_original) . '/' . random_filename() . substr(basename($img_original), $pos); + copy(ROOT_PATH . '/' . $img_original, ROOT_PATH . '/' . $newname); + $img_url = $newname; + + $image->add_watermark(ROOT_PATH . $img_url,'',$GLOBALS['_CFG']['watermark'], $GLOBALS['_CFG']['watermark_place'], $GLOBALS['_CFG']['watermark_alpha']); + } + */ + $img_url = $thumb_url = $img_original; + $img_desc = $_POST['img_desc'][$key]; + $sql = "INSERT INTO " . $GLOBALS['ecs']->table('goods_gallery') . " (goods_id, img_url, img_desc, thumb_url, img_original) " . + "VALUES ('$goods_id', '$img_url', '$img_desc', '$thumb_url', '$img_original')"; + $GLOBALS['db']->query($sql); + } + } + + + /* 编辑时处理相册图片描述 */ + if (!$is_insert && isset($_POST['old_img_desc'])) + { + foreach ($_POST['old_img_desc'] AS $img_id => $img_desc) + { + $sql = "UPDATE " . $GLOBALS['ecs']->table('goods_gallery') . " SET img_desc = '$img_desc' WHERE img_id = '$img_id' LIMIT 1"; + $GLOBALS['db']->query($sql); + } + } + + /* 清空缓存 */ + clear_cache_files(); + + /* 提示页面 */ + client_show_message(0, true, '', $goods_id); + } + + /** + * 获取商品数据 + * + * @param array $post POST数据 + */ + function API_GetGoods($post) + { + $pagesize = intval($_POST['PageSize']); + $page = intval($_POST['Page']); + if(empty($pagesize)) + { + $pagesize = 20; // 每页大小 + } + if($page < 0) + { + $page = 0; + } + //$limit = ' LIMIT ' . ($page * $pagesize) . ', ' . ($pagesize+1); + $today = gmtime(); + $is_delete = 0; + $record_count = $GLOBALS['db']->getOne("SELECT count(*) FROM " . $GLOBALS['ecs']->table('goods') . " WHERE is_delete='$is_delete' $where "); + if ($page > floor($record_count / $pagesize)) + { + $page = $record_count / $pagesize; + } + $limit = ' LIMIT ' . ($page * $pagesize) . ', ' . $pagesize; + $sql = "SELECT goods_id, cat_id, goods_name, goods_sn, brand_id, market_price, shop_price, promote_price, is_on_sale, is_alone_sale, is_best, is_new, is_hot, goods_number, goods_weight, integral, goods_brief, REPLACE(goods_desc, CONCAT(char(170), char(178)), '') AS goods_desc, goods_thumb, goods_img, promote_start_date, promote_end_date, " . " (promote_price > 0 AND promote_start_date <= '$today' AND promote_end_date >= '$today') AS is_promote, warn_number, keywords, extension_code, seller_note, give_integral " . " FROM " . $GLOBALS['ecs']->table('goods') . " AS g WHERE is_delete='$is_delete' $where ORDER BY goods_id DESC $limit"; + + $result = array(); + $result['Data'] = $GLOBALS['db']->getAll($sql); + $result['NextPage'] = false; + $result['PrevPage'] = false; + $result['RecordCount'] = $record_count; + if ($page < floor($record_count / $pagesize)) + { + $result['NextPage'] = true; + } + if($page > 0) + { + $result['PrevPage'] = true; + } + + foreach ($result['Data'] as $key => $goods) + { + $result['Data'][$key]['is_on_sale'] = ($goods['is_on_sale'] == 1); + $result['Data'][$key]['is_alone_sale'] = ($goods['is_alone_sale'] == 1); + $result['Data'][$key]['is_best'] = ($goods['is_best'] == 1); + $result['Data'][$key]['is_new'] = ($goods['is_new'] == 1); + $result['Data'][$key]['is_hot'] = ($goods['is_hot'] == 1); + $result['Data'][$key]['is_promote'] = ($goods['is_promote'] == 1); + $result['Data'][$key]['goods_desc'] = htmlspecialchars($goods['goods_desc']); + $result['Data'][$key]['keywords'] = htmlspecialchars($goods['keywords']); + $result['Data'][$key]['promote_start_date'] = local_date('Y-m-d', $goods['promote_start_date']); + $result['Data'][$key]['promote_end_date'] = local_date('Y-m-d', $goods['promote_end_date']); + + $tmp = array(); + if($goods['goods_thumb'] != '') + { + $tmp['Type'] = substr($goods['goods_thumb'], strrpos($goods['goods_thumb'], '.')+1); + $tmp['Data'] = get_goods_image_url($goods['goods_id'], $goods['goods_thumb'], true); + } + else + { + $tmp['Type'] = ''; + $tmp['Data'] = ''; + } + $result['Data'][$key]['goods_thumb'] = $tmp; + if($goods['goods_img'] != '') + { + $tmp['Type'] = substr($goods['goods_img'], strrpos($goods['goods_img'], '.')+1); + $tmp['Data'] = get_goods_image_url($goods['goods_id'], $goods['goods_img'], false); + } + else + { + $tmp['Type'] = ''; + $tmp['Data'] = ''; + } + $result['Data'][$key]['goods_img'] = $tmp; + } + show_json($GLOBALS['json'], $result, true); + } + + /** + * 删除品牌 + * + * @param array $post POST数据 + */ + function API_DeleteBrand($post) + { + require_once(ROOT_PATH . ADMIN_PATH . '/includes/cls_exchange.php'); + admin_privilege('brand_manage'); + $brand_id = intval($_POST['Id']); + $exc = new exchange($GLOBALS['ecs']->table("brand"), $GLOBALS['db'], 'brand_id', 'brand_name'); + $brand = $GLOBALS['db']->getRow("SELECT brand_logo FROM " . $GLOBALS['ecs']->table('brand') . " WHERE brand_id='$brand_id'"); + if (!empty($brand['brand_logo'])) + { + @unlink(ROOT_PATH . '/brandlogo/' . $brand['brand_logo']); + } + $exc->drop($brand_id); + + /* 更新商品的品牌编号 */ + $sql = "UPDATE " .$GLOBALS['ecs']->table('goods'). " SET brand_id=0 WHERE brand_id='$brand_id'"; + $GLOBALS['db']->query($sql); + client_show_message(0, true); + } + + /** + * 删除分类 + * + * @param array $post POST数据 + */ + function API_DeleteCategory($post) + { + /* 加载后台主操作函数 */ + require_once(ROOT_PATH . ADMIN_PATH . '/includes/lib_main.php'); + admin_privilege('cat_manage'); + /* 初始化分类ID并取得分类名称 */ + $cat_id = intval($_POST['Id']); + $cat_name = $GLOBALS['db']->getOne('SELECT cat_name FROM ' .$GLOBALS['ecs']->table('category'). " WHERE cat_id='$cat_id'"); + + /* 当前分类下是否有子分类 */ + $cat_count = $GLOBALS['db']->getOne('SELECT COUNT(*) FROM ' .$GLOBALS['ecs']->table('category'). " WHERE parent_id='$cat_id'"); + + /* 当前分类下是否存在商品 */ + $goods_count = $GLOBALS['db']->getOne('SELECT COUNT(*) FROM ' .$GLOBALS['ecs']->table('goods'). " WHERE cat_id='$cat_id'"); + /* 如果不存在下级子分类或商品,则删除之 */ + if ($cat_count == 0 && $goods_count == 0) + { + /* 删除分类 */ + $sql = 'DELETE FROM ' .$GLOBALS['ecs']->table('category'). " WHERE cat_id = '$cat_id'"; + if ($GLOBALS['db']->query($sql)) + { + $GLOBALS['db']->query("DELETE FROM " . $GLOBALS['ecs']->table('nav') . "WHERE ctype = 'c' AND cid = '" . $cat_id . "' AND type = 'middle'"); + clear_cache_files(); + admin_log($cat_name, 'remove', 'category'); + } + client_show_message(0, true); + } + else + { + client_show_message(400); + } + } + + /** + * 删除商品 + * + * @param array $post POST数据 + */ + function API_DeleteGoods($post) + { + require_once(ROOT_PATH . ADMIN_PATH . '/includes/cls_exchange.php'); + $exc = new exchange($GLOBALS['ecs']->table("goods"), $GLOBALS['db'], 'goods_id', 'goods_name'); + admin_privilege('remove_back'); + + $goods_id = intval($_POST['Id']); + if ($exc->edit("is_delete = 1", $goods_id, '')) + { + client_show_message(0, true); + } + else + { + client_show_message(230); + } + + } + + function API_EditCategory($post) + { + /* 加载后台主操作函数 */ + require_once(ROOT_PATH . ADMIN_PATH . '/includes/lib_main.php'); + + /* 初始化变量 */ + $cat_id = !empty($_POST['cat_id']) ? intval($_POST['cat_id']) : 0; + $cat['parent_id'] = !empty($_POST['parent_id']) ? intval($_POST['parent_id']) : 0; + $cat['sort_order'] = !empty($_POST['sort_order']) ? intval($_POST['sort_order']) : 0; + $cat['keywords'] = !empty($_POST['keywords']) ? trim($_POST['keywords']) : ''; + $cat['cat_desc'] = !empty($_POST['cat_desc']) ? $_POST['cat_desc'] : ''; + $cat['measure_unit'] = !empty($_POST['measure_unit']) ? trim($_POST['measure_unit']) : ''; + $cat['cat_name'] = !empty($_POST['cat_name']) ? trim($_POST['cat_name']) : ''; + $cat['is_show'] = !empty($_POST['is_show']) ? intval($_POST['is_show']) : 0; + $cat['show_in_nav'] = !empty($_POST['show_in_nav']) ? intval($_POST['show_in_nav']): 0; + $cat['style'] = !empty($_POST['style']) ? trim($_POST['style']) : ''; + $cat['grade'] = !empty($_POST['grade']) ? intval($_POST['grade']) : 0; + $cat['filter_attr'] = !empty($_POST['filter_attr']) ? intval($_POST['filter_attr']) : 0; + + /* 判断上级目录是否合法 */ + $children = array_keys(cat_list($cat_id, 0, false)); // 获得当前分类的所有下级分类 + if (in_array($cat['parent_id'], $children)) + { + /* 选定的父类是当前分类或当前分类的下级分类 */ + client_show_message(401); + } + + if($cat['grade'] > 10 || $cat['grade'] < 0) + { + /* 价格区间数超过范围 */ + client_show_message(402); + } + if (cat_exists($cat['cat_name'], $cat['parent_id'], $cat_id)) + { + /* 同级别下不能有重复的分类名称 */ + client_show_message(403); + } + + $dat = $GLOBALS['db']->getRow("SELECT cat_name, show_in_nav FROM ". $GLOBALS['ecs']->table('category') . " WHERE cat_id = '$cat_id'"); + + if ($GLOBALS['db']->autoExecute($GLOBALS['ecs']->table('category'), $cat, 'UPDATE', "cat_id='$cat_id'")) + { + if($cat['cat_name'] != $dat['cat_name']) + { + //如果分类名称发生了改变 + $sql = "UPDATE " . $GLOBALS['ecs']->table('nav') . " SET name = '" . $cat['cat_name'] . "' WHERE ctype = 'c' AND cid = '" . $cat_id . "' AND type = 'middle'"; + $GLOBALS['db']->query($sql); + } + if($cat['show_in_nav'] != $dat['show_in_nav']) + { + //是否显示于导航栏发生了变化 + if($cat['show_in_nav'] == 1) + { + //显示 + $nid = $GLOBALS['db']->getOne("SELECT id FROM ". $GLOBALS['ecs']->table('nav') . " WHERE ctype = 'c' AND cid = '" . $cat_id . "' AND type = 'middle'"); + if(empty($nid)) + { + //不存在 + $vieworder = $GLOBALS['db']->getOne("SELECT max(vieworder) FROM ". $GLOBALS['ecs']->table('nav') . " WHERE type = 'middle'"); + $vieworder += 2; + $uri = build_uri('category', array('cid'=> $cat_id), $cat['cat_name']); + + $sql = "INSERT INTO " . $GLOBALS['ecs']->table('nav') . " (name,ctype,cid,ifshow,vieworder,opennew,url,type) VALUES('" . $cat['cat_name'] . "', 'c', '$cat_id','1','$vieworder','0', '" . $uri . "','middle')"; + } + else + { + $sql = "UPDATE " . $GLOBALS['ecs']->table('nav') . " SET ifshow = 1 WHERE ctype = 'c' AND cid = '" . $cat_id . "' AND type = 'middle'"; + } + $GLOBALS['db']->query($sql); + } + else + { + //去除 + $GLOBALS['db']->query("UPDATE " . $GLOBALS['ecs']->table('nav') . " SET ifshow = 0 WHERE ctype = 'c' AND cid = '" . $cat_id . "' AND type = 'middle'"); + } + } + } + /* 更新分類信息成功 */ + clear_cache_files(); // 清除缓存 + admin_log($_POST['cat_name'], 'edit', 'category'); // 记录管理员操作 + + client_show_message(0, true); + } + + function API_EditBrand($post) + { + /* 加载后台主操作函数 */ + require_once(ROOT_PATH . ADMIN_PATH . '/includes/lib_main.php'); + require_once(ROOT_PATH . ADMIN_PATH . '/includes/cls_exchange.php'); + require_once(ROOT_PATH . 'includes/cls_image.php'); + + /* 检查权限 */ + admin_privilege('brand_manage'); + + $is_show = isset($_POST['is_show']) ? 1 : 0; + $brand_id = !empty($_POST['brand_id']) ? intval($_POST['brand_id']) : 0; + + /*检查品牌名是否重复*/ + $exc = new exchange($GLOBALS['ecs']->table("brand"), $GLOBALS['db'], 'brand_id', 'brand_name'); + $is_only = $exc->is_only('brand_name', $_POST['brand_name'], '', ''); + + if (!$is_only) + { + client_show_message(301); + } + + $param = "brand_name = '$_POST[brand_name]', site_url='$_POST[site_url]', brand_desc='$_POST[brand_desc]', is_show='$is_show', sort_order='$_POST[sort_order]' "; + + /* 处理图片 */ + $img_name = upload_image($_POST['brand_logo'], 'brandlogo'); + if($img_name !== false) + { + $param .= " ,brand_logo = '" . basename($img_name) . "' "; + } + + /* 更新数据 */ + + if ($exc->edit($param, $brand_id, '')) + { + /* 清除缓存 */ + clear_cache_files(); + + admin_log($_POST['brand_name'], 'edit', 'brand'); + client_show_message(0, true); + } + else + { + client_show_message(302); + } + } + + function API_EditGoods($post) + { + $_POST['act'] = 'update'; + API_AddGoods($post); + //client_show_message(0); + } + + /** + * 出错函数 + * + */ + function API_Error() + { + client_show_message(102); + } + + +?> \ No newline at end of file diff --git a/api/client/includes/lib_struct.php b/api/client/includes/lib_struct.php new file mode 100644 index 0000000..bcc4bf4 --- /dev/null +++ b/api/client/includes/lib_struct.php @@ -0,0 +1,65 @@ + false, + 'MessageCode' => 1, + 'MessageString' => 'Nothing', + 'InsertID' => 0 +); + + +/** + * 返回信息语言包 + */ +$_ALANG = array( + /* 系统类 */ + 100 => '登录成功', + 101 => '没有权限', + 102 => '无效调用', + 103 => '登录失败,用户名或者密码错误。', + 104 => '商店不存在', + 105 => '商店已经被关闭', + 106 => '域名未通过绑定审核或备案信息不合法', + 107 => '缺少必要的网店信息', + 108 => '独立网店的服务期限已经终止', + 109 => '独立网店的顶级域名服务期限已经终止', + 110 => '未登录或者登录超时。', + /* 登录类 */ + /* 分类操作 */ + 400 => '存在下级子分类或商品,该分类不能被删除', + 401 => '选定的父类是当前分类或当前分类的下级分类', + 402 => '价格区间数超过范围', + 403 => '同级别下不能有重复的分类名称', + /* 品牌操作 */ + 300 => '删除品牌时出错', + 301 => '品牌名重复', + 302 => '编辑品牌时出错', + /* 商品操作 */ + 200 => '商品货号重复', + 201 => '商品图片类型不正确', + 202 => '商品图片太大', + 203 => '商品图片缩略图类型不正确', + 204 => '商品图片缩略图太大', + 205 => '商品相册图片类型不正确', + 206 => '商品相册图片太大', + 210 => '写入商品图片出错', + 211 => '复制相册图片时出错', + 212 => '生成缩略图时出错', + 213 => '添加图片水印时出错', + 214 => '复制水印图片时出错', + 215 => '生成相册缩略图时出错', + 216 => '复制原图时出错', + 217 => '上传缩略图时出错', + 218 => '自动生成缩略图时出错', + 219 => '同级别下不能有重复的分类名称', + 220 => '同级别下不能有重复的品牌名称', + 221 => '商品数量已经超过限制', + 230 => '把商品放入回收站时发生错误', + 240 => '该商品已经不存在,编辑失败', + 'undefined' => '未定义信息' +); + +?> \ No newline at end of file diff --git a/api/cron.php b/api/cron.php new file mode 100644 index 0000000..79dd79b --- /dev/null +++ b/api/cron.php @@ -0,0 +1,209 @@ + $cron_val) +{ + if (file_exists(ROOT_PATH . 'includes/modules/cron/' . $cron_val['cron_code'] . '.php')) + { + if (!empty($cron_val['allow_ip'])) // 设置了允许ip + { + $allow_ip = explode(',', $cron_val['allow_ip']); + $server_ip = real_server_ip(); + if (!in_array($server_ip, $allow_ip)) + { + continue; + } + } + if (!empty($cron_val['minute'])) // 设置了允许分钟段 + { + $m = explode(',', $cron_val['minute']); + $m_now = intval(local_date('i',$timestamp)); + if (!in_array($m_now, $m)) + { + continue; + } + } + if (!empty($cron_val['alow_files'])) // 设置允许调用文件 + { + $f_info = parse_url($_SERVER['HTTP_REFERER']); + $f_now = basename($f_info['path']); + $f = explode(' ', $cron_val['alow_files']); + if (!in_array($f_now, $f)) + { + continue; + } + } + if (!empty($cron_val['cron_config'])) + { + foreach ($cron_val['cron_config'] AS $k => $v) + { + $cron[$v['name']] = $v['value']; + } + } + include_once(ROOT_PATH . 'includes/modules/cron/' . $cron_val['cron_code'] . '.php'); + } + else + { + $error_log[] = make_error_arr('includes/modules/cron/' . $cron_val['cron_code'] . '.php not found!',__FILE__); + } + + $close = $cron_val['run_once'] ? 0 : 1; + $next_time = get_next_time($cron_val['cron']); + $sql = "UPDATE " . $ecs->table('crons') . + "SET thistime = '$timestamp', nextime = '$next_time', enable = $close " . + "WHERE cron_id = '$cron_val[cron_id]' LIMIT 1"; + + $db->query($sql); +} +write_error_arr($error_log); + +function get_next_time($cron) +{ + $y = local_date('Y', $GLOBALS['timestamp']); + $mo = local_date('n', $GLOBALS['timestamp']); + $d = local_date('j', $GLOBALS['timestamp']); + $w = local_date('w', $GLOBALS['timestamp']); + $h = local_date('G', $GLOBALS['timestamp']); + $sh = $sm = 0; + $sy = $y; + if ($cron['day']) + { + $sd = $cron['day']; + $smo = $mo + 1; + } + else + { + $sd = $d; + $smo = $mo; + if ($cron['week'] != '') + { + $sd += $cron['week'] - $w + 7; + } + } + if ($cron['hour']) + { + $sh = $cron['hour']; + if (empty($cron['day']) && $cron['week']=='') + { + $sd++; + } + } + //$next = gmmktime($sh,$sm,0,$smo,$sd,$sy); + $next = local_strtotime("$sy-$smo-$sd $sh:$sm:0"); + if ($next < $GLOBALS['timestamp']) + { + if ($cron['m']) + { + return $GLOBALS['timestamp'] + 60 - intval(local_date('s', $GLOBALS['timestamp'])); + } + else + { + return $GLOBALS['timestamp']; + } + } + else + { + return $next; + } +} + +function get_cron_info() +{ + $crondb = array(); + + $sql = "SELECT * FROM " . $GLOBALS['ecs']->table('crons') . " WHERE enable = 1 AND nextime < $GLOBALS[timestamp]"; + $query = $GLOBALS['db']->query($sql); + + while ($rt = $GLOBALS['db']->fetch_array($query)) + { + $rt['cron'] = array('day'=>$rt['day'],'week'=>$rt['week'],'m'=>$rt['minute'],'hour'=>$rt['hour']); + $rt['cron_config'] = unserialize($rt['cron_config']); + $rt['minute'] = trim($rt['minute']); + $rt['allow_ip'] = trim($rt['allow_ip']); + $crondb[] = $rt; + } + + return $crondb; +} + +function make_error_arr($msg,$file) +{ + $file = str_replace(ROOT_PATH, '' ,$file); + + return array('info' => $msg, 'file' => $file, 'time' => $GLOBALS['timestamp']); +} + +function write_error_arr($err_arr) +{ + if (!empty($err_arr)) + { + $query = ''; + foreach ($err_arr AS $key => $val) + { + $query .= $query ? ",('$val[info]', '$val[file]', '$val[time]')" : "('$val[info]', '$val[file]', '$val[time]')"; + } + if ($query) + { + $sql = "INSERT INTO " . $GLOBALS['ecs']->table('error_log') . "(info, file, time) VALUES " . $query; + $GLOBALS['db']->query($sql); + } + } +} + +function check_method() +{ + if (PHP_VERSION >= '4.2') + { + $if_cron = PHP_SAPI == 'cli' ? true : false; + } + else + { + $if_cron = php_sapi_name() == 'cgi' ? true : false; + } + if (!empty($GLOBALS['_CFG']['cron_method'])) + { + if (!$if_cron) + { + die('Hacking attempt'); + } + } + else + { + if ($if_cron) + { + die('Hacking attempt'); + } + elseif (!isset($_GET['t']) || $GLOBALS['timestamp'] - intval($_GET['t']) > 60 || empty($_SERVER['HTTP_REFERER'])) + { + exit; + } + } +} + +?> \ No newline at end of file diff --git "a/api/ecshop\346\250\241\346\235\277\347\275\221 - ecshop\346\250\241\346\235\277\345\210\266\344\275\234\344\272\214\346\254\241\345\274\200\345\217\221\347\254\254\344\270\200\347\253\231.url" "b/api/ecshop\346\250\241\346\235\277\347\275\221 - ecshop\346\250\241\346\235\277\345\210\266\344\275\234\344\272\214\346\254\241\345\274\200\345\217\221\347\254\254\344\270\200\347\253\231.url" new file mode 100644 index 0000000..8360d56 --- /dev/null +++ "b/api/ecshop\346\250\241\346\235\277\347\275\221 - ecshop\346\250\241\346\235\277\345\210\266\344\275\234\344\272\214\346\254\241\345\274\200\345\217\221\347\254\254\344\270\200\347\253\231.url" @@ -0,0 +1,9 @@ +[DEFAULT] +BASEURL=http://www.ecshoptemplate.com/ +[{000214A0-0000-0000-C000-000000000046}] +Prop3=19,2 +[InternetShortcut] +URL=http://www.ecshoptemplate.com/ +IDList= +IconFile=http://www.ecshoptemplate.com/favicon.ico +IconIndex=1 diff --git a/api/goods.php b/api/goods.php new file mode 100644 index 0000000..a159024 --- /dev/null +++ b/api/goods.php @@ -0,0 +1,191 @@ +getOne("SELECT `value` FROM " . $ecs->table('shop_config') . " WHERE `code`='hash_code'", true); + +$action = isset($_REQUEST['action'])? $_REQUEST['action']:''; +if (empty($_REQUEST['verify']) || empty($_REQUEST['auth']) || empty($_REQUEST['action'])) +{ + $results = array('result'=>'false', 'data'=>'缺少必要的参数'); + exit($json->encode($results)); +} +if ($_REQUEST['verify'] != md5($hash_code.$_REQUEST['action'].$_REQUEST['auth'])) +{ + $results = array('result'=>'false', 'data'=>'数据来源不合法,请返回'); + exit($json->encode($results)); +} + +parse_str(passport_decrypt($_REQUEST['auth'], $hash_code), $data); + +switch ($action) +{ + case 'get_goods_info': + { + $shop_id = isset($data['shop_id'])? intval($data['shop_id']):0; + $record_number = isset($data['record_number'])? intval($data['record_number']):20; + $page_number = isset($data['page_number'])? intval($data['page_number']):0; + $limit = ' LIMIT ' . ($record_number * $page_number) . ', ' . ($record_number+1); + $sql = "SELECT `goods_id`, `goods_name`, `goods_number`, `shop_price`, `keywords`, `goods_brief`, `goods_thumb`, `goods_img`, `last_update` FROM " . $ecs->table('goods') . " WHERE `is_delete`='0' ORDER BY `goods_id` ASC $limit "; + $results = array('result' => 'false', 'next' => 'false', 'data' => array()); + $query = $db->query($sql); + $record_count = 0; + while ($goods = $db->fetch_array($query)) + { + $goods['goods_thumb'] = (!empty($goods['goods_thumb']))? 'http://' . $_SERVER['SERVER_NAME'] . '/' . $goods['goods_thumb']:''; + $goods['goods_img'] = (!empty($goods['goods_img']))? 'http://' . $_SERVER['SERVER_NAME'] . '/' . $goods['goods_img']:''; + $results['data'][] = $goods; + $record_count++; + } + if ($record_count > 0) + { + $results['result'] = 'true'; + } + if ($record_count > $record_number) + { + array_pop($results['data']); + $results['next'] = 'true'; + } + exit($json->encode($results)); + break; + } + case 'get_shop_info': + { + $results = array('result' => 'true', 'data' => array()); + $sql = "SELECT `value` FROM " . $ecs->table('shop_config') . " WHERE code='shop_name'"; + $shop_name = $db->getOne($sql); + $sql = "SELECT `value` FROM " . $ecs->table('shop_config') . " WHERE code='currency_format'"; + $currency_format = $db->getOne($sql); + $sql = "SELECT r.region_name, sc.value FROM " . $ecs->table('region') . " AS r INNER JOIN " . $ecs->table('shop_config') . " AS sc ON r.`region_id`=sc.`value` WHERE sc.`code`='shop_country' OR sc.`code`='shop_province' OR sc.`code`='shop_city' ORDER BY sc.`id` ASC"; + + $shop_region = $db->getAll($sql); + $results['data'] = array + ( + 'shop_name' => $shop_name, + 'domain' => 'http://' . $_SERVER['SERVER_NAME'] . '/', + 'shop_region' => $shop_region[0]['region_name'] . ' ' . $shop_region[1]['region_name'] . ' ' . $shop_region[2]['region_name'], + 'currency_format' => $currency_format + ); + exit($json->encode($results)); + break; + } + case 'get_shipping': + { + $results = array('result' => 'false', 'data' => array()); + $sql = "SELECT `shipping_id`, `shipping_name`, `insure` FROM " . $ecs->table('shipping'); + $result = $db->getAll($sql); + if (!empty($result)) + { + $results['result'] = 'true'; + $results['data'] = $result; + } + exit($json->encode($results)); + break; + } + case 'get_goods_attribute': + { + $results = array('result' => 'false', 'data' => array()); + $goods_id = isset($data['goods_id'])? intval($data['goods_id']):0; + if (!empty($goods_id)) + { + $sql = "SELECT t2.attr_name, t1.attr_value FROM " . $ecs->table('goods_attr') . " AS t1 LEFT JOIN " . $ecs->table('attribute') . " AS t2 ON t1.attr_id=t2.attr_id WHERE t1.goods_id='$goods_id'"; + $result = $db->getAll($sql); + if (!empty($result)) + { + $results['result'] = 'true'; + $results['data'] = $result; + } + } + else + { + $results = array('result'=>'false', 'data'=>'缺少商品ID,无法获取其属性'); + } + exit($json->encode($results)); + break; + } + default: + { + $results = array('result'=>'false', 'data'=>'缺少动作'); + exit(json_encode($results)); + break; + } +} + +/** + * 解密函数 + * + * @param string $txt + * @param string $key + * @return string + */ +function passport_decrypt($txt, $key) +{ + $txt = passport_key(base64_decode($txt), $key); + $tmp = ''; + for ($i = 0;$i < strlen($txt); $i++) { + $md5 = $txt[$i]; + $tmp .= $txt[++$i] ^ $md5; + } + return $tmp; +} + +/** + * 加密函数 + * + * @param string $txt + * @param string $key + * @return string + */ +function passport_encrypt($txt, $key) +{ + srand((double)microtime() * 1000000); + $encrypt_key = md5(rand(0, 32000)); + $ctr = 0; + $tmp = ''; + for($i = 0; $i < strlen($txt); $i++ ) + { + $ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr; + $tmp .= $encrypt_key[$ctr].($txt[$i] ^ $encrypt_key[$ctr++]); + } + return base64_encode(passport_key($tmp, $key)); +} + +/** + * 编码函数 + * + * @param string $txt + * @param string $key + * @return string + */ +function passport_key($txt, $encrypt_key) +{ + $encrypt_key = md5($encrypt_key); + $ctr = 0; + $tmp = ''; + for($i = 0; $i < strlen($txt); $i++) + { + $ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr; + $tmp .= $txt[$i] ^ $encrypt_key[$ctr++]; + } + return $tmp; +} +?> \ No newline at end of file diff --git a/api/init.php b/api/init.php new file mode 100644 index 0000000..eb45145 --- /dev/null +++ b/api/init.php @@ -0,0 +1,137 @@ += '5.1' && !empty($timezone)) +{ + date_default_timezone_set($timezone); +} + +$php_self = isset($_SERVER['PHP_SELF']) ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME']; +if ('/' == substr($php_self, -1)) +{ + $php_self .= 'index.php'; +} +define('PHP_SELF', $php_self); + +require(ROOT_PATH . 'includes/inc_constant.php'); +require(ROOT_PATH . 'includes/cls_ecshop.php'); +require(ROOT_PATH . 'includes/lib_base.php'); +require(ROOT_PATH . 'includes/lib_common.php'); +require(ROOT_PATH . 'includes/lib_time.php'); + +/* 对用户传入的变量进行转义操作。*/ +if (!get_magic_quotes_gpc()) +{ + if (!empty($_GET)) + { + $_GET = addslashes_deep($_GET); + } + if (!empty($_POST)) + { + $_POST = addslashes_deep($_POST); + } + + $_COOKIE = addslashes_deep($_COOKIE); + $_REQUEST = addslashes_deep($_REQUEST); +} + +/* 创建 ECSHOP 对象 */ +$ecs = new ECS($db_name, $prefix); +$data_dir = $ecs->data_dir(); + +/* 初始化数据库类 */ +require(ROOT_PATH . 'includes/cls_mysql.php'); +$db = new cls_mysql($db_host, $db_user, $db_pass, $db_name); +$db_host = $db_user = $db_pass = $db_name = NULL; + +/* 初始化session */ +require(ROOT_PATH . 'includes/cls_session.php'); +$sess_name = defined("SESS_NAME") ? SESS_NAME : 'ECS_ID'; +$sess = new cls_session($db, $ecs->table('sessions'), $ecs->table('sessions_data'), $sess_name); + +/* 载入系统参数 */ +$_CFG = load_config(); + +/* 初始化用户插件 */ +$user =& init_users(); + +if ((DEBUG_MODE & 1) == 1) +{ + error_reporting(E_ALL); +} +else +{ + error_reporting(E_ALL ^ E_NOTICE); +} +if ((DEBUG_MODE & 4) == 4) +{ + include(ROOT_PATH . 'includes/lib.debug.php'); +} + +/* 判断是否支持 Gzip 模式 */ +if (gzip_enabled()) +{ + ob_start('ob_gzhandler'); +} + +header('Content-type: text/html; charset=' . EC_CHARSET); + +?> \ No newline at end of file diff --git a/api/uc.php b/api/uc.php new file mode 100644 index 0000000..5a0d437 --- /dev/null +++ b/api/uc.php @@ -0,0 +1,583 @@ + 3600) + { + exit('Authracation has expiried'); + } + if(empty($get)) + { + exit('Invalid Request'); + } +} + +$action = $get['action']; +include(ROOT_PATH . 'uc_client/lib/xml.class.php'); +$post = xml_unserialize(file_get_contents('php://input')); + +if(in_array($get['action'], array('test', 'deleteuser', 'renameuser', 'gettag', 'synlogin', 'synlogout', 'updatepw', 'updatebadwords', 'updatehosts', 'updateapps', 'updateclient', 'updatecredit', 'getcreditsettings', 'updatecreditsettings'))) +{ + $uc_note = new uc_note(); + exit($uc_note->$get['action']($get, $post)); +} +else +{ + exit(API_RETURN_FAILED); +} + +$ecs_url = str_replace('/api', '', $ecs->url()); + +class uc_note +{ + var $db = ''; + var $tablepre = ''; + var $appdir = ''; + + function _serialize($arr, $htmlon = 0) + { + if(!function_exists('xml_serialize')) + { + include(ROOT_PATH . 'uc_client/lib/xml.class.php'); + } + return xml_serialize($arr, $htmlon); + } + + function uc_note() + { + $this->appdir = ROOT_PATH; + $this->db = $GLOBALS['db']; + } + + function test($get, $post) + { + return API_RETURN_SUCCEED; + } + + function deleteuser($get, $post) + { + $uids = $get['ids']; + if(!API_DELETEUSER) + { + return API_RETURN_FORBIDDEN; + } + + if (delete_user($uids)) + { + return API_RETURN_SUCCEED; + } + } + + function renameuser($get, $post) + { + $uid = $get['uid']; + $usernameold = $get['oldusername']; + $usernamenew = $get['newusername']; + if(!API_RENAMEUSER) + { + return API_RETURN_FORBIDDEN; + } + $this->db->query("UPDATE " . $GLOBALS['ecs']->table("users") . " SET user_name='$usernamenew' WHERE user_id='$uid'"); + $this->db->query("UPDATE " . $GLOBALS['ecs']->table("affiliate_log") . " SET user_name='$usernamenew' WHERE user_name='$usernameold'"); + $this->db->query("UPDATE " . $GLOBALS['ecs']->table("comment") . " SET user_name='$usernamenew' WHERE user_name='$usernameold'"); + $this->db->query("UPDATE " . $GLOBALS['ecs']->table("feedback") . " SET user_name='$usernamenew' WHERE user_name='$usernameold'"); + clear_cache_files(); + return API_RETURN_SUCCEED; + } + + function gettag($get, $post) + { + $name = $get['id']; + if(!API_GETTAG) + { + return API_RETURN_FORBIDDEN; + } + $tags = fetch_tag($name); + $return = array($name, $tags); + include_once(ROOT_PATH . 'uc_client/client.php'); + return uc_serialize($return, 1); + } + + function synlogin($get, $post) + { + $uid = intval($get['uid']); + $username = $get['username']; + if(!API_SYNLOGIN) + { + return API_RETURN_FORBIDDEN; + } + header('P3P: CP="CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR"'); + set_login($uid, $username); + } + + function synlogout($get, $post) + { + if(!API_SYNLOGOUT) + { + return API_RETURN_FORBIDDEN; + } + + header('P3P: CP="CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR"'); + set_cookie(); + set_session(); + } + + function updatepw($get, $post) + { + if(!API_UPDATEPW) + { + return API_RETURN_FORBIDDEN; + } + $username = $get['username']; + #$password = md5($get['password']); + $newpw = md5(time().rand(100000, 999999)); + $this->db->query("UPDATE " . $GLOBALS['ecs']->table('users') . " SET password='$newpw' WHERE user_name='$username'"); + return API_RETURN_SUCCEED; + } + + function updatebadwords($get, $post) + { + if(!API_UPDATEBADWORDS) + { + return API_RETURN_FORBIDDEN; + } + $cachefile = $this->appdir.'./uc_client/data/cache/badwords.php'; + $fp = fopen($cachefile, 'w'); + $data = array(); + if(is_array($post)) { + foreach($post as $k => $v) { + $data['findpattern'][$k] = $v['findpattern']; + $data['replace'][$k] = $v['replacement']; + } + } + $s = "appdir . './uc_client/data/cache/hosts.php'; + $fp = fopen($cachefile, 'w'); + $s = "appdir . './uc_client/data/cache/apps.php'; + $fp = fopen($cachefile, 'w'); + $s = "appdir . './uc_client/data/cache/settings.php'; + $fp = fopen($cachefile, 'w'); + $s = " 'rank_points', 1 => 'pay_points'); + $sql = "UPDATE " . $GLOBALS['ecs']-> table('users') . " SET {$points[$credit]} = {$points[$credit]} + '$amount' WHERE user_id = $uid"; + $this->db->query($sql); + if ($this->db->affected_rows() <= 0) + { + return API_RETURN_FAILED; + } + $sql = "INSERT INTO " . $GLOBALS['ecs']->table('account_log') . "(user_id, {$points[$credit]}, change_time, change_desc, change_type)" . + " VALUES ('$uid', '$amount', '". gmtime() ."', '" . $cfg['uc_lang']['exchange'] . "', '99')"; + $this->db->query($sql); + return API_RETURN_SUCCEED; + } + + function getcredit($get, $post) + { + if(!API_GETCREDIT) + { + return API_RETURN_FORBIDDEN; + } + + /*$uid = intval($get['uid']); + $credit = intval($get['credit']); + return $credit >= 1 && $credit <= 8 ? $this->db->result_first("SELECT extcredits$credit FROM ".$this->tablepre."members WHERE uid='$uid'") : 0;*/ + } + + function getcreditsettings($get, $post) + { + if(!API_GETCREDITSETTINGS) + { + return API_RETURN_FORBIDDEN; + } + $cfg = unserialize($GLOBALS['_CFG']['integrate_config']); + $credits = $cfg['uc_lang']['credits']; + include_once(ROOT_PATH . 'uc_client/client.php'); + return uc_serialize($credits); + } + + function updatecreditsettings($get, $post) + { + if(!API_UPDATECREDITSETTINGS) + { + return API_RETURN_FORBIDDEN; + } + + $outextcredits = array(); + foreach($get['credit'] as $appid => $credititems) + { + if($appid == UC_APPID) + { + foreach($credititems as $value) + { + $outextcredits[] = array + ( + 'appiddesc' => $value['appiddesc'], + 'creditdesc' => $value['creditdesc'], + 'creditsrc' => $value['creditsrc'], + 'title' => $value['title'], + 'unit' => $value['unit'], + 'ratio' => $value['ratio'] + ); + } + } + } + $this->db->query("UPDATE " . $GLOBALS['ecs']->table("shop_config") . " SET value='".serialize($outextcredits)."' WHERE code='points_rule'"); + return API_RETURN_SUCCEED; + } +} + +/** + * 删除用户接口函数 + * + * @access public + * @param int $uids + * @return void + */ +function delete_user($uids = '') +{ + if (empty($uids)) + { + return; + } + else + { + $uids = stripslashes($uids); + $sql = "DELETE FROM " . $GLOBALS['ecs']->table('users') . " WHERE user_id IN ($uids)"; + $result = $GLOBALS['db']->query($sql); + return true; + } +} + +/** + * 设置用户登陆 + * + * @access public + * @param int $uid + * @return void + */ +function set_login($user_id = '', $user_name = '') +{ + if (empty($user_id)) + { + return ; + } + else + { + $sql = "SELECT user_name, email FROM " . $GLOBALS['ecs']->table('users') . " WHERE user_id='$user_id' LIMIT 1"; + $row = $GLOBALS['db']->getRow($sql); + if ($row) + { + set_cookie($user_id, $row['user_name'], $row['email']); + set_session($user_id, $row['user_name'], $row['email']); + include_once(ROOT_PATH . 'includes/lib_main.php'); + update_user_info(); + } + else + { + include_once(ROOT_PATH . 'uc_client/client.php'); + if($data = uc_get_user($user_name)) + { + list($uid, $uname, $email) = $data; + $sql = "REPLACE INTO " . $GLOBALS['ecs']->table('users') ."(user_id, user_name, email) VALUES('$uid', '$uname', '$email')"; + $GLOBALS['db']->query($sql); + set_login($uid); + } + else + { + return false; + } + } + } +} + +/** + * 设置cookie + * + * @access public + * @param + * @return void + */ +function set_cookie($user_id='', $user_name = '', $email = '') +{ + if (empty($user_id)) + { + /* 摧毁cookie */ + $time = time() - 3600; + setcookie('ECS[user_id]', '', $time); + setcookie('ECS[username]', '', $time); + setcookie('ECS[email]', '', $time); + } + else + { + /* 设置cookie */ + $time = time() + 3600 * 24 * 30; + setcookie("ECS[user_id]", $user_id, $time, $GLOBALS['cookie_path'], $GLOBALS['cookie_domain']); + setcookie("ECS[username]", $user_name, $time, $GLOBALS['cookie_path'], $GLOBALS['cookie_domain']); + setcookie("ECS[email]", $email, $time, $GLOBALS['cookie_path'], $GLOBALS['cookie_domain']); + } +} + +/** + * 设置指定用户SESSION + * + * @access public + * @param + * @return void + */ +function set_session ($user_id = '', $user_name = '', $email = '') +{ + if (empty($user_id)) + { + $GLOBALS['sess']->destroy_session(); + } + else + { + $_SESSION['user_id'] = $user_id; + $_SESSION['user_name'] = $user_name; + $_SESSION['email'] = $email; + } +} + +/** + * 获取EC的TAG数据 + * + * @access public + * @param string $tagname + * @param int $num 获取的数量 默认取最新的100条 + * @return array + */ +function fetch_tag($tagname, $num=100) +{ + $rewrite = intval($GLOBALS['_CFG']['rewrite']) > 0; + $sql = "SELECT t.*, u.user_name, g.goods_name, g.goods_img, g.shop_price FROM " . $GLOBALS['ecs']->table('tag') . " as t, " . $GLOBALS['ecs']->table('users') ." as u, " . + $GLOBALS['ecs']->table('goods') ." as g WHERE tag_words = '$tagname' AND t.user_id = u.user_id AND g.goods_id = t.goods_id ORDER BY t.tag_id DESC LIMIT " . $num; + $arr = $GLOBALS['db']->getAll($sql); + $tag_list = array(); + foreach ($arr as $k=>$v) + { + $tag_list[$k]['goods_name'] = $v['goods_name']; + $tag_list[$k]['uid'] = $v['user_id']; + $tag_list[$k]['username'] = $v['user_name']; + $tag_list[$k]['dateline'] = time(); + $tag_list[$k]['url'] = $GLOBALS['ecs_url'] . 'goods.php?id=' . $v['goods_id']; + $tag_list[$k]['image'] = $GLOBALS['ecs_url'] . $v['goods_img']; + $tag_list[$k]['goods_price'] = $v['shop_price']; + } + + return $tag_list; +} + +/** + * uc自带函数1 + * + * @access public + * @param string $string + * + * @return string $string + */ +function _setcookie($var, $value, $life = 0, $prefix = 1) +{ + global $cookiepre, $cookiedomain, $cookiepath, $timestamp, $_SERVER; + setcookie(($prefix ? $cookiepre : '').$var, $value, + $life ? $timestamp + $life : 0, $cookiepath, + $cookiedomain, $_SERVER['SERVER_PORT'] == 443 ? 1 : 0); +} + +/** + * uc自带函数2 + * + * @access public + * + * @return string $string + */ +function _authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) +{ + $ckey_length = 4; + $key = md5($key ? $key : UC_KEY); + $keya = md5(substr($key, 0, 16)); + $keyb = md5(substr($key, 16, 16)); + $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : ''; + + $cryptkey = $keya.md5($keya.$keyc); + $key_length = strlen($cryptkey); + + $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string; + $string_length = strlen($string); + + $result = ''; + $box = range(0, 255); + + $rndkey = array(); + for($i = 0; $i <= 255; $i++) + { + $rndkey[$i] = ord($cryptkey[$i % $key_length]); + } + + for($j = $i = 0; $i < 256; $i++) + { + $j = ($j + $box[$i] + $rndkey[$i]) % 256; + $tmp = $box[$i]; + $box[$i] = $box[$j]; + $box[$j] = $tmp; + } + + for($a = $j = $i = 0; $i < $string_length; $i++) + { + $a = ($a + 1) % 256; + $j = ($j + $box[$a]) % 256; + $tmp = $box[$a]; + $box[$a] = $box[$j]; + $box[$j] = $tmp; + $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256])); + } + + if($operation == 'DECODE') + { + if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) + { + return substr($result, 26); + } + else + { + return ''; + } + } + else + { + return $keyc.str_replace('=', '', base64_encode($result)); + } +} + +/** + * uc自带函数3 + * + * @access public + * @param string $string + * + * @return string $string + */ +function _stripslashes($string) +{ + if(is_array($string)) + { + foreach($string as $key => $val) + { + $string[$key] = _stripslashes($val); + } + } + else + { + $string = stripslashes($string); + } + return $string; +} + +?> \ No newline at end of file diff --git "a/api/\346\234\200\346\250\241\346\235\277 - \344\270\223\346\263\250\347\275\221\345\272\227\345\225\206\345\237\216\346\250\241\346\235\277\345\210\266\344\275\234\344\270\216\345\256\232\345\210\266\345\274\200\345\217\221.url" "b/api/\346\234\200\346\250\241\346\235\277 - \344\270\223\346\263\250\347\275\221\345\272\227\345\225\206\345\237\216\346\250\241\346\235\277\345\210\266\344\275\234\344\270\216\345\256\232\345\210\266\345\274\200\345\217\221.url" new file mode 100644 index 0000000..f60bd51 --- /dev/null +++ "b/api/\346\234\200\346\250\241\346\235\277 - \344\270\223\346\263\250\347\275\221\345\272\227\345\225\206\345\237\216\346\250\241\346\235\277\345\210\266\344\275\234\344\270\216\345\256\232\345\210\266\345\274\200\345\217\221.url" @@ -0,0 +1,9 @@ +[DEFAULT] +BASEURL=http://www.zuimoban.com/ +[{000214A0-0000-0000-C000-000000000046}] +Prop3=19,2 +[InternetShortcut] +URL=http://www.zuimoban.com/ +IDList= +IconFile=http://www.zuimoban.com/favicon.ico +IconIndex=1 diff --git a/article.php b/article.php new file mode 100644 index 0000000..7a0cc24 --- /dev/null +++ b/article.php @@ -0,0 +1,213 @@ +caching = true; +} + +/*------------------------------------------------------ */ +//-- INPUT +/*------------------------------------------------------ */ + +$_REQUEST['id'] = isset($_REQUEST['id']) ? intval($_REQUEST['id']) : 0; +$article_id = $_REQUEST['id']; +if(isset($_REQUEST['cat_id']) && $_REQUEST['cat_id'] < 0) +{ + $article_id = $db->getOne("SELECT article_id FROM " . $ecs->table('article') . " WHERE cat_id = '".intval($_REQUEST['cat_id'])."' "); +} + +/*------------------------------------------------------ */ +//-- PROCESSOR +/*------------------------------------------------------ */ + +$cache_id = sprintf('%X', crc32($_REQUEST['id'] . '-' . $_CFG['lang'])); + +if (!$smarty->is_cached('article.dwt', $cache_id)) +{ + /* 文章详情 */ + $article = get_article_info($article_id); + + if (empty($article)) + { + ecs_header("Location: ./\n"); + exit; + } + + if (!empty($article['link']) && $article['link'] != 'http://' && $article['link'] != 'https://') + { + ecs_header("location:$article[link]\n"); + exit; + } + + $smarty->assign('article_categories', article_categories_tree($article_id)); //文章分类树 + $smarty->assign('categories', get_categories_tree()); // 分类树 + $smarty->assign('helps', get_shop_help()); // 网店帮助 + $smarty->assign('top_goods', get_top10()); // 销售排行 + $smarty->assign('best_goods', get_recommend_goods('best')); // 推荐商品 + $smarty->assign('new_goods', get_recommend_goods('new')); // 最新商品 + $smarty->assign('hot_goods', get_recommend_goods('hot')); // 热点文章 + $smarty->assign('promotion_goods', get_promote_goods()); // 特价商品 + $smarty->assign('related_goods', article_related_goods($_REQUEST['id'])); // 特价商品 + $smarty->assign('id', $article_id); + $smarty->assign('username', $_SESSION['user_name']); + $smarty->assign('email', $_SESSION['email']); + $smarty->assign('type', '1'); + $smarty->assign('promotion_info', get_promotion_info()); + + /* 验证码相关设置 */ + if ((intval($_CFG['captcha']) & CAPTCHA_COMMENT) && gd_version() > 0) + { + $smarty->assign('enabled_captcha', 1); + $smarty->assign('rand', mt_rand()); + } + + $smarty->assign('article', $article); + $smarty->assign('keywords', htmlspecialchars($article['keywords'])); + $smarty->assign('description', htmlspecialchars($article['description'])); + + $catlist = array(); + foreach(get_article_parent_cats($article['cat_id']) as $k=>$v) + { + $catlist[] = $v['cat_id']; + } + + assign_template('a', $catlist); + + $position = assign_ur_here($article['cat_id'], $article['title']); + $smarty->assign('page_title', $position['title']); // 页面标题 + $smarty->assign('ur_here', $position['ur_here']); // 当前位置 + $smarty->assign('comment_type', 1); + + /* 相关商品 */ + $sql = "SELECT a.goods_id, g.goods_name " . + "FROM " . $ecs->table('goods_article') . " AS a, " . $ecs->table('goods') . " AS g " . + "WHERE a.goods_id = g.goods_id " . + "AND a.article_id = '$_REQUEST[id]' "; + $smarty->assign('goods_list', $db->getAll($sql)); + + /* 上一篇下一篇文章 */ + $next_article = $db->getRow("SELECT article_id, title FROM " .$ecs->table('article'). " WHERE article_id > $article_id AND cat_id=$article[cat_id] AND is_open=1 LIMIT 1"); + if (!empty($next_article)) + { + $next_article['url'] = build_uri('article', array('aid'=>$next_article['article_id']), $next_article['title']); + $smarty->assign('next_article', $next_article); + } + + $prev_aid = $db->getOne("SELECT max(article_id) FROM " . $ecs->table('article') . " WHERE article_id < $article_id AND cat_id=$article[cat_id] AND is_open=1"); + if (!empty($prev_aid)) + { + $prev_article = $db->getRow("SELECT article_id, title FROM " .$ecs->table('article'). " WHERE article_id = $prev_aid"); + $prev_article['url'] = build_uri('article', array('aid'=>$prev_article['article_id']), $prev_article['title']); + $smarty->assign('prev_article', $prev_article); + } + + assign_dynamic('article'); +} +if(isset($article) && $article['cat_id'] > 2) +{ + $smarty->display('article.dwt', $cache_id); +} +else +{ + $smarty->display('article_pro.dwt', $cache_id); +} + +/*------------------------------------------------------ */ +//-- PRIVATE FUNCTION +/*------------------------------------------------------ */ + +/** + * 获得指定的文章的详细信息 + * + * @access private + * @param integer $article_id + * @return array + */ +function get_article_info($article_id) +{ + /* 获得文章的信息 */ + $sql = "SELECT a.*, IFNULL(AVG(r.comment_rank), 0) AS comment_rank ". + "FROM " .$GLOBALS['ecs']->table('article'). " AS a ". + "LEFT JOIN " .$GLOBALS['ecs']->table('comment'). " AS r ON r.id_value = a.article_id AND comment_type = 1 ". + "WHERE a.is_open = 1 AND a.article_id = '$article_id' GROUP BY a.article_id"; + $row = $GLOBALS['db']->getRow($sql); + + if ($row !== false) + { + $row['comment_rank'] = ceil($row['comment_rank']); // 用户评论级别取整 + $row['add_time'] = local_date($GLOBALS['_CFG']['date_format'], $row['add_time']); // 修正添加时间显示 + + /* 作者信息如果为空,则用网站名称替换 */ + if (empty($row['author']) || $row['author'] == '_SHOPHELP') + { + $row['author'] = $GLOBALS['_CFG']['shop_name']; + } + } + + return $row; +} + +/** + * 获得文章关联的商品 + * + * @access public + * @param integer $id + * @return array + */ +function article_related_goods($id) +{ + $sql = 'SELECT g.goods_id, g.goods_name, g.goods_thumb, g.goods_img, g.shop_price AS org_price, ' . + "IFNULL(mp.user_price, g.shop_price * '$_SESSION[discount]') AS shop_price, ". + 'g.market_price, g.promote_price, g.promote_start_date, g.promote_end_date ' . + 'FROM ' . $GLOBALS['ecs']->table('goods_article') . ' ga ' . + 'LEFT JOIN ' . $GLOBALS['ecs']->table('goods') . ' AS g ON g.goods_id = ga.goods_id ' . + "LEFT JOIN " . $GLOBALS['ecs']->table('member_price') . " AS mp ". + "ON mp.goods_id = g.goods_id AND mp.user_rank = '$_SESSION[user_rank]' ". + "WHERE ga.article_id = '$id' AND g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0"; + $res = $GLOBALS['db']->query($sql); + + $arr = array(); + while ($row = $GLOBALS['db']->fetchRow($res)) + { + $arr[$row['goods_id']]['goods_id'] = $row['goods_id']; + $arr[$row['goods_id']]['goods_name'] = $row['goods_name']; + $arr[$row['goods_id']]['short_name'] = $GLOBALS['_CFG']['goods_name_length'] > 0 ? + sub_str($row['goods_name'], $GLOBALS['_CFG']['goods_name_length']) : $row['goods_name']; + $arr[$row['goods_id']]['goods_thumb'] = get_image_path($row['goods_id'], $row['goods_thumb'], true); + $arr[$row['goods_id']]['goods_img'] = get_image_path($row['goods_id'], $row['goods_img']); + $arr[$row['goods_id']]['market_price'] = price_format($row['market_price']); + $arr[$row['goods_id']]['shop_price'] = price_format($row['shop_price']); + $arr[$row['goods_id']]['url'] = build_uri('goods', array('gid' => $row['goods_id']), $row['goods_name']); + + if ($row['promote_price'] > 0) + { + $arr[$row['goods_id']]['promote_price'] = bargain_price($row['promote_price'], $row['promote_start_date'], $row['promote_end_date']); + $arr[$row['goods_id']]['formated_promote_price'] = price_format($arr[$row['goods_id']]['promote_price']); + } + else + { + $arr[$row['goods_id']]['promote_price'] = 0; + } + } + + return $arr; +} + +?> \ No newline at end of file diff --git a/article_cat.php b/article_cat.php new file mode 100644 index 0000000..d9d1fa3 --- /dev/null +++ b/article_cat.php @@ -0,0 +1,134 @@ +caching = true; +} + +/* 清除缓存 */ +clear_cache_files(); + +/*------------------------------------------------------ */ +//-- INPUT +/*------------------------------------------------------ */ + +/* 获得指定的分类ID */ +if (!empty($_GET['id'])) +{ + $cat_id = intval($_GET['id']); +} +elseif (!empty($_GET['category'])) +{ + $cat_id = intval($_GET['category']); +} +else +{ + ecs_header("Location: ./\n"); + + exit; +} + +/* 获得当前页码 */ +$page = !empty($_REQUEST['page']) && intval($_REQUEST['page']) > 0 ? intval($_REQUEST['page']) : 1; + +/*------------------------------------------------------ */ +//-- PROCESSOR +/*------------------------------------------------------ */ + +/* 获得页面的缓存ID */ +$cache_id = sprintf('%X', crc32($cat_id . '-' . $page . '-' . $_CFG['lang'])); + +if (!$smarty->is_cached('article_cat.dwt', $cache_id)) +{ + /* 如果页面没有被缓存则重新获得页面的内容 */ + + assign_template('a', array($cat_id)); + $position = assign_ur_here($cat_id); + $smarty->assign('page_title', $position['title']); // 页面标题 + $smarty->assign('ur_here', $position['ur_here']); // 当前位置 + + $smarty->assign('categories', get_categories_tree(0)); // 分类树 + $smarty->assign('article_categories', article_categories_tree($cat_id)); //文章分类树 + $smarty->assign('helps', get_shop_help()); // 网店帮助 + $smarty->assign('top_goods', get_top10()); // 销售排行 + + $smarty->assign('best_goods', get_recommend_goods('best')); + $smarty->assign('new_goods', get_recommend_goods('new')); + $smarty->assign('hot_goods', get_recommend_goods('hot')); + $smarty->assign('promotion_goods', get_promote_goods()); + $smarty->assign('promotion_info', get_promotion_info()); + + /* Meta */ + $meta = $db->getRow("SELECT keywords, cat_desc FROM " . $ecs->table('article_cat') . " WHERE cat_id = '$cat_id'"); + + if ($meta === false || empty($meta)) + { + /* 如果没有找到任何记录则返回首页 */ + ecs_header("Location: ./\n"); + exit; + } + + $smarty->assign('keywords', htmlspecialchars($meta['keywords'])); + $smarty->assign('description', htmlspecialchars($meta['cat_desc'])); + + /* 获得文章总数 */ + $size = isset($_CFG['article_page_size']) && intval($_CFG['article_page_size']) > 0 ? intval($_CFG['article_page_size']) : 20; + $count = get_article_count($cat_id); + $pages = ($count > 0) ? ceil($count / $size) : 1; + + if ($page > $pages) + { + $page = $pages; + } + $pager['search']['id'] = $cat_id; + $keywords = ''; + $goon_keywords = ''; //继续传递的搜索关键词 + + /* 获得文章列表 */ + if (isset($_REQUEST['keywords'])) + { + $keywords = addslashes(htmlspecialchars(urldecode(trim($_REQUEST['keywords'])))); + $pager['search']['keywords'] = $keywords; + $search_url = substr(strrchr($_POST['cur_url'], '/'), 1); + + $smarty->assign('search_value', stripslashes(stripslashes($keywords))); + $smarty->assign('search_url', $search_url); + $count = get_article_count($cat_id, $keywords); + $pages = ($count > 0) ? ceil($count / $size) : 1; + if ($page > $pages) + { + $page = $pages; + } + + $goon_keywords = urlencode($_REQUEST['keywords']); + } + $smarty->assign('artciles_list', get_cat_articles($cat_id, $page, $size ,$keywords)); + $smarty->assign('cat_id', $cat_id); + /* 分页 */ + assign_pager('article_cat', $cat_id, $count, $size, '', '', $page, $goon_keywords); + assign_dynamic('article_cat'); +} + +$smarty->assign('feed_url', ($_CFG['rewrite'] == 1) ? "feed-typearticle_cat" . $cat_id . ".xml" : 'feed.php?type=article_cat' . $cat_id); // RSS URL + +$smarty->display('article_cat.dwt', $cache_id); + +?> \ No newline at end of file diff --git a/auction.php b/auction.php new file mode 100644 index 0000000..43acd6b --- /dev/null +++ b/auction.php @@ -0,0 +1,498 @@ + 0) + { + /* 取得每页记录数 */ + $size = isset($_CFG['page_size']) && intval($_CFG['page_size']) > 0 ? intval($_CFG['page_size']) : 10; + + /* 计算总页数 */ + $page_count = ceil($count / $size); + + /* 取得当前页 */ + $page = isset($_REQUEST['page']) && intval($_REQUEST['page']) > 0 ? intval($_REQUEST['page']) : 1; + $page = $page > $page_count ? $page_count : $page; + + /* 缓存id:语言 - 每页记录数 - 当前页 */ + $cache_id = $_CFG['lang'] . '-' . $size . '-' . $page; + $cache_id = sprintf('%X', crc32($cache_id)); + } + else + { + /* 缓存id:语言 */ + $cache_id = $_CFG['lang']; + $cache_id = sprintf('%X', crc32($cache_id)); + } + + /* 如果没有缓存,生成缓存 */ + if (!$smarty->is_cached('auction_list.dwt', $cache_id)) + { + if ($count > 0) + { + /* 取得当前页的拍卖活动 */ + $auction_list = auction_list($size, $page); + $smarty->assign('auction_list', $auction_list); + + /* 设置分页链接 */ + $pager = get_pager('auction.php', array('act' => 'list'), $count, $page, $size); + $smarty->assign('pager', $pager); + } + + /* 模板赋值 */ + $smarty->assign('cfg', $_CFG); + assign_template(); + $position = assign_ur_here(); + $smarty->assign('page_title', $position['title']); // 页面标题 + $smarty->assign('ur_here', $position['ur_here']); // 当前位置 + $smarty->assign('categories', get_categories_tree()); // 分类树 + $smarty->assign('helps', get_shop_help()); // 网店帮助 + $smarty->assign('top_goods', get_top10()); // 销售排行 + $smarty->assign('promotion_info', get_promotion_info()); + $smarty->assign('feed_url', ($_CFG['rewrite'] == 1) ? "feed-typeauction.xml" : 'feed.php?type=auction'); // RSS URL + + assign_dynamic('auction_list'); + } + + /* 显示模板 */ + $smarty->display('auction_list.dwt', $cache_id); +} + +/*------------------------------------------------------ */ +//-- 拍卖商品 --> 商品详情 +/*------------------------------------------------------ */ +elseif ($_REQUEST['act'] == 'view') +{ + /* 取得参数:拍卖活动id */ + $id = isset($_REQUEST['id']) ? intval($_REQUEST['id']) : 0; + if ($id <= 0) + { + ecs_header("Location: ./\n"); + exit; + } + + /* 取得拍卖活动信息 */ + $auction = auction_info($id); + if (empty($auction)) + { + ecs_header("Location: ./\n"); + exit; + } + + /* 缓存id:语言,拍卖活动id,状态,如果是进行中,还要最后出价的时间(如果有的话) */ + $cache_id = $_CFG['lang'] . '-' . $id . '-' . $auction['status_no']; + if ($auction['status_no'] == UNDER_WAY) + { + if (isset($auction['last_bid'])) + { + $cache_id = $cache_id . '-' . $auction['last_bid']['bid_time']; + } + } + elseif ($auction['status_no'] == FINISHED && $auction['last_bid']['bid_user'] == $_SESSION['user_id'] + && $auction['order_count'] == 0) + { + $auction['is_winner'] = 1; + $cache_id = $cache_id . '-' . $auction['last_bid']['bid_time'] . '-1'; + } + + $cache_id = sprintf('%X', crc32($cache_id)); + + /* 如果没有缓存,生成缓存 */ + if (!$smarty->is_cached('auction.dwt', $cache_id)) + { + //取货品信息 + if ($auction['product_id'] > 0) + { + $goods_specifications = get_specifications_list($auction['goods_id']); + + $good_products = get_good_products($auction['goods_id'], 'AND product_id = ' . $auction['product_id']); + + $_good_products = explode('|', $good_products[0]['goods_attr']); + $products_info = ''; + foreach ($_good_products as $value) + { + $products_info .= ' ' . $goods_specifications[$value]['attr_name'] . ':' . $goods_specifications[$value]['attr_value']; + } + $smarty->assign('products_info', $products_info); + unset($goods_specifications, $good_products, $_good_products, $products_info); + } + + $auction['gmt_end_time'] = local_strtotime($auction['end_time']); + $smarty->assign('auction', $auction); + + /* 取得拍卖商品信息 */ + $goods_id = $auction['goods_id']; + $goods = goods_info($goods_id); + if (empty($goods)) + { + ecs_header("Location: ./\n"); + exit; + } + $goods['url'] = build_uri('goods', array('gid' => $goods_id), $goods['goods_name']); + $smarty->assign('auction_goods', $goods); + + /* 出价记录 */ + $smarty->assign('auction_log', auction_log($id)); + + //模板赋值 + $smarty->assign('cfg', $_CFG); + assign_template(); + + $position = assign_ur_here(0, $goods['goods_name']); + $smarty->assign('page_title', $position['title']); // 页面标题 + $smarty->assign('ur_here', $position['ur_here']); // 当前位置 + + $smarty->assign('categories', get_categories_tree()); // 分类树 + $smarty->assign('helps', get_shop_help()); // 网店帮助 + $smarty->assign('top_goods', get_top10()); // 销售排行 + $smarty->assign('promotion_info', get_promotion_info()); + + assign_dynamic('auction'); + } + + //更新商品点击次数 + $sql = 'UPDATE ' . $ecs->table('goods') . ' SET click_count = click_count + 1 '. + "WHERE goods_id = '" . $auction['goods_id'] . "'"; + $db->query($sql); + + $smarty->assign('now_time', gmtime()); // 当前系统时间 + $smarty->display('auction.dwt', $cache_id); +} + +/*------------------------------------------------------ */ +//-- 拍卖商品 --> 出价 +/*------------------------------------------------------ */ +elseif ($_REQUEST['act'] == 'bid') +{ + include_once(ROOT_PATH . 'includes/lib_order.php'); + + /* 取得参数:拍卖活动id */ + $id = isset($_POST['id']) ? intval($_POST['id']) : 0; + if ($id <= 0) + { + ecs_header("Location: ./\n"); + exit; + } + + /* 取得拍卖活动信息 */ + $auction = auction_info($id); + if (empty($auction)) + { + ecs_header("Location: ./\n"); + exit; + } + + /* 活动是否正在进行 */ + if ($auction['status_no'] != UNDER_WAY) + { + show_message($_LANG['au_not_under_way'], '', '', 'error'); + } + + /* 是否登录 */ + $user_id = $_SESSION['user_id']; + if ($user_id <= 0) + { + show_message($_LANG['au_bid_after_login']); + } + $user = user_info($user_id); + + /* 取得出价 */ + $bid_price = isset($_POST['price']) ? round(floatval($_POST['price']), 2) : 0; + if ($bid_price <= 0) + { + show_message($_LANG['au_bid_price_error'], '', '', 'error'); + } + + /* 如果有一口价且出价大于等于一口价,则按一口价算 */ + $is_ok = false; // 出价是否ok + if ($auction['end_price'] > 0) + { + if ($bid_price >= $auction['end_price']) + { + $bid_price = $auction['end_price']; + $is_ok = true; + } + } + + /* 出价是否有效:区分第一次和非第一次 */ + if (!$is_ok) + { + if ($auction['bid_user_count'] == 0) + { + /* 第一次要大于等于起拍价 */ + $min_price = $auction['start_price']; + } + else + { + /* 非第一次出价要大于等于最高价加上加价幅度,但不能超过一口价 */ + $min_price = $auction['last_bid']['bid_price'] + $auction['amplitude']; + if ($auction['end_price'] > 0) + { + $min_price = min($min_price, $auction['end_price']); + } + } + + if ($bid_price < $min_price) + { + show_message(sprintf($_LANG['au_your_lowest_price'], price_format($min_price, false)), '', '', 'error'); + } + } + + /* 检查联系两次拍卖人是否相同 */ + if ($auction['last_bid']['bid_user'] == $user_id && $bid_price != $auction['end_price']) + { + show_message($_LANG['au_bid_repeat_user'], '', '', 'error'); + } + + /* 是否需要保证金 */ + if ($auction['deposit'] > 0) + { + /* 可用资金够吗 */ + if ($user['user_money'] < $auction['deposit']) + { + show_message($_LANG['au_user_money_short'], '', '', 'error'); + } + + /* 如果不是第一个出价,解冻上一个用户的保证金 */ + if ($auction['bid_user_count'] > 0) + { + log_account_change($auction['last_bid']['bid_user'], $auction['deposit'], (-1) * $auction['deposit'], + 0, 0, sprintf($_LANG['au_unfreeze_deposit'], $auction['act_name'])); + } + + /* 冻结当前用户的保证金 */ + log_account_change($user_id, (-1) * $auction['deposit'], $auction['deposit'], + 0, 0, sprintf($_LANG['au_freeze_deposit'], $auction['act_name'])); + } + + /* 插入出价记录 */ + $auction_log = array( + 'act_id' => $id, + 'bid_user' => $user_id, + 'bid_price' => $bid_price, + 'bid_time' => gmtime() + ); + $db->autoExecute($ecs->table('auction_log'), $auction_log, 'INSERT'); + + /* 出价是否等于一口价 */ + if ($bid_price == $auction['end_price']) + { + /* 结束拍卖活动 */ + $sql = "UPDATE " . $ecs->table('goods_activity') . " SET is_finished = 1 WHERE act_id = '$id' LIMIT 1"; + $db->query($sql); + } + + /* 跳转到活动详情页 */ + ecs_header("Location: auction.php?act=view&id=$id\n"); + exit; +} + +/*------------------------------------------------------ */ +//-- 拍卖商品 --> 购买 +/*------------------------------------------------------ */ +elseif ($_REQUEST['act'] == 'buy') +{ + /* 查询:取得参数:拍卖活动id */ + $id = isset($_POST['id']) ? intval($_POST['id']) : 0; + if ($id <= 0) + { + ecs_header("Location: ./\n"); + exit; + } + + /* 查询:取得拍卖活动信息 */ + $auction = auction_info($id); + if (empty($auction)) + { + ecs_header("Location: ./\n"); + exit; + } + + /* 查询:活动是否已结束 */ + if ($auction['status_no'] != FINISHED) + { + show_message($_LANG['au_not_finished'], '', '', 'error'); + } + + /* 查询:有人出价吗 */ + if ($auction['bid_user_count'] <= 0) + { + show_message($_LANG['au_no_bid'], '', '', 'error'); + } + + /* 查询:是否已经有订单 */ + if ($auction['order_count'] > 0) + { + show_message($_LANG['au_order_placed']); + } + + /* 查询:是否登录 */ + $user_id = $_SESSION['user_id']; + if ($user_id <= 0) + { + show_message($_LANG['au_buy_after_login']); + } + + /* 查询:最后出价的是该用户吗 */ + if ($auction['last_bid']['bid_user'] != $user_id) + { + show_message($_LANG['au_final_bid_not_you'], '', '', 'error'); + } + + /* 查询:取得商品信息 */ + $goods = goods_info($auction['goods_id']); + + /* 查询:处理规格属性 */ + $goods_attr = ''; + $goods_attr_id = ''; + if ($auction['product_id'] > 0) + { + $product_info = get_good_products($auction['goods_id'], 'AND product_id = ' . $auction['product_id']); + + $goods_attr_id = str_replace('|', ',', $product_info[0]['goods_attr']); + + $attr_list = array(); + $sql = "SELECT a.attr_name, g.attr_value " . + "FROM " . $ecs->table('goods_attr') . " AS g, " . + $ecs->table('attribute') . " AS a " . + "WHERE g.attr_id = a.attr_id " . + "AND g.goods_attr_id " . db_create_in($goods_attr_id); + $res = $db->query($sql); + while ($row = $db->fetchRow($res)) + { + $attr_list[] = $row['attr_name'] . ': ' . $row['attr_value']; + } + $goods_attr = join(chr(13) . chr(10), $attr_list); + } + else + { + $auction['product_id'] = 0; + } + + /* 清空购物车中所有拍卖商品 */ + include_once(ROOT_PATH . 'includes/lib_order.php'); + clear_cart(CART_AUCTION_GOODS); + + /* 加入购物车 */ + $cart = array( + 'user_id' => $user_id, + 'session_id' => SESS_ID, + 'goods_id' => $auction['goods_id'], + 'goods_sn' => addslashes($goods['goods_sn']), + 'goods_name' => addslashes($goods['goods_name']), + 'market_price' => $goods['market_price'], + 'goods_price' => $auction['last_bid']['bid_price'], + 'goods_number' => 1, + 'goods_attr' => $goods_attr, + 'goods_attr_id' => $goods_attr_id, + 'is_real' => $goods['is_real'], + 'extension_code' => addslashes($goods['extension_code']), + 'parent_id' => 0, + 'rec_type' => CART_AUCTION_GOODS, + 'is_gift' => 0 + ); + $db->autoExecute($ecs->table('cart'), $cart, 'INSERT'); + + /* 记录购物流程类型:团购 */ + $_SESSION['flow_type'] = CART_AUCTION_GOODS; + $_SESSION['extension_code'] = 'auction'; + $_SESSION['extension_id'] = $id; + + /* 进入收货人页面 */ + ecs_header("Location: ./flow.php?step=consignee\n"); + exit; +} + +/** + * 取得拍卖活动数量 + * @return int + */ +function auction_count() +{ + $now = gmtime(); + $sql = "SELECT COUNT(*) " . + "FROM " . $GLOBALS['ecs']->table('goods_activity') . + "WHERE act_type = '" . GAT_AUCTION . "' " . + "AND start_time <= '$now' AND end_time >= '$now' AND is_finished < 2"; + + return $GLOBALS['db']->getOne($sql); +} + +/** + * 取得某页的拍卖活动 + * @param int $size 每页记录数 + * @param int $page 当前页 + * @return array + */ +function auction_list($size, $page) +{ + $auction_list = array(); + $auction_list['finished'] = $auction_list['finished'] = array(); + + $now = gmtime(); + $sql = "SELECT a.*, IFNULL(g.goods_thumb, '') AS goods_thumb " . + "FROM " . $GLOBALS['ecs']->table('goods_activity') . " AS a " . + "LEFT JOIN " . $GLOBALS['ecs']->table('goods') . " AS g ON a.goods_id = g.goods_id " . + "WHERE a.act_type = '" . GAT_AUCTION . "' " . + "AND a.start_time <= '$now' AND a.end_time >= '$now' AND a.is_finished < 2 ORDER BY a.act_id DESC"; + $res = $GLOBALS['db']->selectLimit($sql, $size, ($page - 1) * $size); + while ($row = $GLOBALS['db']->fetchRow($res)) + { + $ext_info = unserialize($row['ext_info']); + $auction = array_merge($row, $ext_info); + $auction['status_no'] = auction_status($auction); + + $auction['start_time'] = local_date($GLOBALS['_CFG']['time_format'], $auction['start_time']); + $auction['end_time'] = local_date($GLOBALS['_CFG']['time_format'], $auction['end_time']); + $auction['formated_start_price'] = price_format($auction['start_price']); + $auction['formated_end_price'] = price_format($auction['end_price']); + $auction['formated_deposit'] = price_format($auction['deposit']); + $auction['goods_thumb'] = get_image_path($row['goods_id'], $row['goods_thumb'], true); + $auction['url'] = build_uri('auction', array('auid'=>$auction['act_id'])); + + if($auction['status_no'] < 2) + { + $auction_list['under_way'][] = $auction; + } + else + { + $auction_list['finished'][] = $auction; + } + } + + $auction_list = @array_merge($auction_list['under_way'], $auction_list['finished']); + + return $auction_list; +} + +?> \ No newline at end of file diff --git a/brand.php b/brand.php new file mode 100644 index 0000000..72feebd --- /dev/null +++ b/brand.php @@ -0,0 +1,355 @@ +caching = true; +} + +/*------------------------------------------------------ */ +//-- INPUT +/*------------------------------------------------------ */ + +/* 获得请求的分类 ID */ +if (!empty($_REQUEST['id'])) +{ + $brand_id = intval($_REQUEST['id']); +} +if (!empty($_REQUEST['brand'])) +{ + $brand_id = intval($_REQUEST['brand']); +} +if (empty($brand_id)) +{ + /* 缓存编号 */ + $cache_id = sprintf('%X', crc32($_CFG['lang'])); + if (!$smarty->is_cached('brand_list.dwt', $cache_id)) + { + assign_template(); + $position = assign_ur_here('', $_LANG['all_brand']); + $smarty->assign('page_title', $position['title']); // 页面标题 + $smarty->assign('ur_here', $position['ur_here']); // 当前位置 + + $smarty->assign('categories', get_categories_tree()); // 分类树 + $smarty->assign('helps', get_shop_help()); // 网店帮助 + $smarty->assign('top_goods', get_top10()); // 销售排行 + + $smarty->assign('brand_list', get_brands()); + } + $smarty->display('brand_list.dwt', $cache_id); + exit(); +} + +/* 初始化分页信息 */ +$page = !empty($_REQUEST['page']) && intval($_REQUEST['page']) > 0 ? intval($_REQUEST['page']) : 1; +$size = !empty($_CFG['page_size']) && intval($_CFG['page_size']) > 0 ? intval($_CFG['page_size']) : 10; +$cate = !empty($_REQUEST['cat']) && intval($_REQUEST['cat']) > 0 ? intval($_REQUEST['cat']) : 0; + +/* 排序、显示方式以及类型 */ +$default_display_type = $_CFG['show_order_type'] == '0' ? 'list' : ($_CFG['show_order_type'] == '1' ? 'grid' : 'text'); +$default_sort_order_method = $_CFG['sort_order_method'] == '0' ? 'DESC' : 'ASC'; +$default_sort_order_type = $_CFG['sort_order_type'] == '0' ? 'goods_id' : ($_CFG['sort_order_type'] == '1' ? 'shop_price' : 'last_update'); + +$sort = (isset($_REQUEST['sort']) && in_array(trim(strtolower($_REQUEST['sort'])), array('goods_id', 'shop_price', 'last_update'))) ? trim($_REQUEST['sort']) : $default_sort_order_type; +$order = (isset($_REQUEST['order']) && in_array(trim(strtoupper($_REQUEST['order'])), array('ASC', 'DESC'))) ? trim($_REQUEST['order']) : $default_sort_order_method; +$display = (isset($_REQUEST['display']) && in_array(trim(strtolower($_REQUEST['display'])), array('list', 'grid', 'text'))) ? trim($_REQUEST['display']) : (isset($_COOKIE['ECS']['display']) ? $_COOKIE['ECS']['display'] : $default_display_type); +$display = in_array($display, array('list', 'grid', 'text')) ? $display : 'text'; +setcookie('ECS[display]', $display, gmtime() + 86400 * 7); + +/*------------------------------------------------------ */ +//-- PROCESSOR +/*------------------------------------------------------ */ + +/* 页面的缓存ID */ +$cache_id = sprintf('%X', crc32($brand_id . '-' . $display . '-' . $sort . '-' . $order . '-' . $page . '-' . $size . '-' . $_SESSION['user_rank'] . '-' . $_CFG['lang'] . '-' . $cate)); + +if (!$smarty->is_cached('brand.dwt', $cache_id)) +{ + $brand_info = get_brand_info($brand_id); + + if (empty($brand_info)) + { + ecs_header("Location: ./\n"); + exit; + } + + $smarty->assign('data_dir', DATA_DIR); + $smarty->assign('keywords', htmlspecialchars($brand_info['brand_desc'])); + $smarty->assign('description', htmlspecialchars($brand_info['brand_desc'])); + + /* 赋值固定内容 */ + assign_template(); + $position = assign_ur_here($cate, $brand_info['brand_name']); + $smarty->assign('page_title', $position['title']); // 页面标题 + $smarty->assign('ur_here', $position['ur_here']); // 当前位置 + $smarty->assign('brand_id', $brand_id); + $smarty->assign('category', $cate); + + $smarty->assign('categories', get_categories_tree()); // 分类树 + $smarty->assign('helps', get_shop_help()); // 网店帮助 + $smarty->assign('top_goods', get_top10()); // 销售排行 + $smarty->assign('show_marketprice', $_CFG['show_marketprice']); + $smarty->assign('brand_cat_list', brand_related_cat($brand_id)); // 相关分类 + $smarty->assign('feed_url', ($_CFG['rewrite'] == 1) ? "feed-b$brand_id.xml" : 'feed.php?brand=' . $brand_id); + + /* 调查 */ + $vote = get_vote(); + if (!empty($vote)) + { + $smarty->assign('vote_id', $vote['id']); + $smarty->assign('vote', $vote['content']); + } + + $smarty->assign('best_goods', brand_recommend_goods('best', $brand_id, $cate)); + $smarty->assign('promotion_goods', brand_recommend_goods('promote', $brand_id, $cate)); + $smarty->assign('brand', $brand_info); + $smarty->assign('promotion_info', get_promotion_info()); + + $count = goods_count_by_brand($brand_id, $cate); + + $goodslist = brand_get_goods($brand_id, $cate, $size, $page, $sort, $order); + + if($display == 'grid') + { + if(count($goodslist) % 2 != 0) + { + $goodslist[] = array(); + } + } + $smarty->assign('goods_list', $goodslist); + $smarty->assign('script_name', 'brand'); + + assign_pager('brand', $cate, $count, $size, $sort, $order, $page, '', $brand_id, 0, 0, $display); // 分页 + assign_dynamic('brand'); // 动态内容 +} + +$smarty->display('brand.dwt', $cache_id); + +/*------------------------------------------------------ */ +//-- PRIVATE FUNCTION +/*------------------------------------------------------ */ + +/** + * 获得指定品牌的详细信息 + * + * @access private + * @param integer $id + * @return void + */ +function get_brand_info($id) +{ + $sql = 'SELECT * FROM ' . $GLOBALS['ecs']->table('brand') . " WHERE brand_id = '$id'"; + + return $GLOBALS['db']->getRow($sql); +} + +/** + * 获得指定品牌下的推荐和促销商品 + * + * @access private + * @param string $type + * @param integer $brand + * @return array + */ +function brand_recommend_goods($type, $brand, $cat = 0) +{ + static $result = NULL; + + $time = gmtime(); + + if ($result === NULL) + { + if ($cat > 0) + { + $cat_where = "AND " . get_children($cat); + } + else + { + $cat_where = ''; + } + + $sql = 'SELECT g.goods_id, g.goods_name, g.market_price, g.shop_price AS org_price, g.promote_price, ' . + "IFNULL(mp.user_price, g.shop_price * '$_SESSION[discount]') AS shop_price, ". + 'promote_start_date, promote_end_date, g.goods_brief, g.goods_thumb, goods_img, ' . + 'b.brand_name, g.is_best, g.is_new, g.is_hot, g.is_promote ' . + 'FROM ' . $GLOBALS['ecs']->table('goods') . ' AS g ' . + 'LEFT JOIN ' . $GLOBALS['ecs']->table('brand') . ' AS b ON b.brand_id = g.brand_id ' . + 'LEFT JOIN ' . $GLOBALS['ecs']->table('member_price') . ' AS mp '. + "ON mp.goods_id = g.goods_id AND mp.user_rank = '$_SESSION[user_rank]' ". + "WHERE g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0 AND g.brand_id = '$brand' AND " . + "(g.is_best = 1 OR (g.is_promote = 1 AND promote_start_date <= '$time' AND ". + "promote_end_date >= '$time')) $cat_where" . + 'ORDER BY g.sort_order, g.last_update DESC'; + $result = $GLOBALS['db']->getAll($sql); + } + + /* 取得每一项的数量限制 */ + $num = 0; + $type2lib = array('best'=>'recommend_best', 'new'=>'recommend_new', 'hot'=>'recommend_hot', 'promote'=>'recommend_promotion'); + $num = get_library_number($type2lib[$type]); + + $idx = 0; + $goods = array(); + foreach ($result AS $row) + { + if ($idx >= $num) + { + break; + } + + if (($type == 'best' && $row['is_best'] == 1) || + ($type == 'promote' && $row['is_promote'] == 1 && + $row['promote_start_date'] <= $time && $row['promote_end_date'] >= $time)) + { + if ($row['promote_price'] > 0) + { + $promote_price = bargain_price($row['promote_price'], $row['promote_start_date'], $row['promote_end_date']); + $goods[$idx]['promote_price'] = $promote_price > 0 ? price_format($promote_price) : ''; + } + else + { + $goods[$idx]['promote_price'] = ''; + } + + $goods[$idx]['id'] = $row['goods_id']; + $goods[$idx]['name'] = $row['goods_name']; + $goods[$idx]['brief'] = $row['goods_brief']; + $goods[$idx]['brand_name'] = $row['brand_name']; + $goods[$idx]['short_style_name'] = $GLOBALS['_CFG']['goods_name_length'] > 0 ? + sub_str($row['goods_name'], $GLOBALS['_CFG']['goods_name_length']) : $row['goods_name']; + $goods[$idx]['market_price'] = price_format($row['market_price']); + $goods[$idx]['shop_price'] = price_format($row['shop_price']); + $goods[$idx]['thumb'] = get_image_path($row['goods_id'], $row['goods_thumb'], true); + $goods[$idx]['goods_img'] = get_image_path($row['goods_id'], $row['goods_img']); + $goods[$idx]['url'] = build_uri('goods', array('gid' => $row['goods_id']), $row['goods_name']); + + $idx++; + } + } + + return $goods; +} + +/** + * 获得指定的品牌下的商品总数 + * + * @access private + * @param integer $brand_id + * @param integer $cate + * @return integer + */ +function goods_count_by_brand($brand_id, $cate = 0) +{ + $sql = 'SELECT COUNT(*) FROM ' .$GLOBALS['ecs']->table('goods'). ' AS g '. + "WHERE brand_id = '$brand_id' AND g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0"; + + if ($cate > 0) + { + $sql .= " AND " . get_children($cate); + } + + return $GLOBALS['db']->getOne($sql); +} + +/** + * 获得品牌下的商品 + * + * @access private + * @param integer $brand_id + * @return array + */ +function brand_get_goods($brand_id, $cate, $size, $page, $sort, $order) +{ + $cate_where = ($cate > 0) ? 'AND ' . get_children($cate) : ''; + + /* 获得商品列表 */ + $sql = 'SELECT g.goods_id, g.goods_name, g.market_price, g.shop_price AS org_price, ' . + "IFNULL(mp.user_price, g.shop_price * '$_SESSION[discount]') AS shop_price, g.promote_price, " . + 'g.promote_start_date, g.promote_end_date, g.goods_brief, g.goods_thumb , g.goods_img ' . + 'FROM ' . $GLOBALS['ecs']->table('goods') . ' AS g ' . + 'LEFT JOIN ' . $GLOBALS['ecs']->table('member_price') . ' AS mp ' . + "ON mp.goods_id = g.goods_id AND mp.user_rank = '$_SESSION[user_rank]' " . + "WHERE g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0 AND g.brand_id = '$brand_id' $cate_where". + "ORDER BY $sort $order"; + + $res = $GLOBALS['db']->selectLimit($sql, $size, ($page - 1) * $size); + + $arr = array(); + while ($row = $GLOBALS['db']->fetchRow($res)) + { + if ($row['promote_price'] > 0) + { + $promote_price = bargain_price($row['promote_price'], $row['promote_start_date'], $row['promote_end_date']); + } + else + { + $promote_price = 0; + } + + $arr[$row['goods_id']]['goods_id'] = $row['goods_id']; + if($GLOBALS['display'] == 'grid') + { + $arr[$row['goods_id']]['goods_name'] = $GLOBALS['_CFG']['goods_name_length'] > 0 ? sub_str($row['goods_name'], $GLOBALS['_CFG']['goods_name_length']) : $row['goods_name']; + } + else + { + $arr[$row['goods_id']]['goods_name'] = $row['goods_name']; + } + $arr[$row['goods_id']]['market_price'] = price_format($row['market_price']); + $arr[$row['goods_id']]['shop_price'] = price_format($row['shop_price']); + $arr[$row['goods_id']]['promote_price'] = ($promote_price > 0) ? price_format($promote_price) : ''; + $arr[$row['goods_id']]['goods_brief'] = $row['goods_brief']; + $arr[$row['goods_id']]['goods_thumb'] = get_image_path($row['goods_id'], $row['goods_thumb'], true); + $arr[$row['goods_id']]['goods_img'] = get_image_path($row['goods_id'], $row['goods_img']); + $arr[$row['goods_id']]['url'] = build_uri('goods', array('gid' => $row['goods_id']), $row['goods_name']); + } + + return $arr; +} + +/** + * 获得与指定品牌相关的分类 + * + * @access public + * @param integer $brand + * @return array + */ +function brand_related_cat($brand) +{ + $arr[] = array('cat_id' => 0, + 'cat_name' => $GLOBALS['_LANG']['all_category'], + 'url' => build_uri('brand', array('bid' => $brand), $GLOBALS['_LANG']['all_category'])); + + $sql = "SELECT c.cat_id, c.cat_name, COUNT(g.goods_id) AS goods_count FROM ". + $GLOBALS['ecs']->table('category'). " AS c, ". + $GLOBALS['ecs']->table('goods') . " AS g " . + "WHERE g.brand_id = '$brand' AND c.cat_id = g.cat_id ". + "GROUP BY g.cat_id"; + $res = $GLOBALS['db']->query($sql); + + while ($row = $GLOBALS['db']->fetchRow($res)) + { + $row['url'] = build_uri('brand', array('cid' => $row['cat_id'], 'bid' => $brand), $row['cat_name']); + $arr[] = $row; + } + + return $arr; +} + +?> \ No newline at end of file diff --git a/captcha.php b/captcha.php new file mode 100644 index 0000000..9019624 --- /dev/null +++ b/captcha.php @@ -0,0 +1,30 @@ +session_word = 'captcha_login'; +} +$img->generate_image(); + +?> \ No newline at end of file diff --git a/catalog.php b/catalog.php new file mode 100644 index 0000000..bee5a7f --- /dev/null +++ b/catalog.php @@ -0,0 +1,77 @@ +caching = true; +} + +if (!$smarty->is_cached('catalog.dwt')) +{ + /* 取出所有分类 */ + $cat_list = cat_list(0, 0, false); + + foreach ($cat_list AS $key=>$val) + { + if ($val['is_show'] == 0) + { + unset($cat_list[$key]); + } + } + + + assign_template(); + assign_dynamic('catalog'); + $position = assign_ur_here(0, $_LANG['catalog']); + $smarty->assign('page_title', $position['title']); // 页面标题 + $smarty->assign('ur_here', $position['ur_here']); // 当前位置 + $smarty->assign('categories', get_categories_tree()); // 分类树 + + $smarty->assign('helps', get_shop_help()); // 网店帮助 + $smarty->assign('cat_list', $cat_list); // 分类列表 + $smarty->assign('brand_list', get_brands()); // 所以品牌赋值 + $smarty->assign('promotion_info', get_promotion_info()); +} + +$smarty->display('catalog.dwt'); + +/** + * 计算指定分类的商品数量 + * + * @access public + * @param integer $cat_id + * + * @return void + */ +function calculate_goods_num($cat_list, $cat_id) +{ + $goods_num = 0; + + foreach ($cat_list AS $cat) + { + if ($cat['parent_id'] == $cat_id && !empty($cat['goods_num'])) + { + $goods_num += $cat['goods_num']; + } + } + + return $goods_num; +} + +?> \ No newline at end of file diff --git a/category.php b/category.php new file mode 100644 index 0000000..d8b5ef1 --- /dev/null +++ b/category.php @@ -0,0 +1,600 @@ +caching = true; +} + +/*------------------------------------------------------ */ +//-- INPUT +/*------------------------------------------------------ */ + +/* 获得请求的分类 ID */ +if (isset($_REQUEST['id'])) +{ + $cat_id = intval($_REQUEST['id']); +} +elseif (isset($_REQUEST['category'])) +{ + $cat_id = intval($_REQUEST['category']); +} +else +{ + /* 如果分类ID为0,则返回首页 */ + ecs_header("Location: ./\n"); + + exit; +} + + +/* 初始化分页信息 */ +$page = isset($_REQUEST['page']) && intval($_REQUEST['page']) > 0 ? intval($_REQUEST['page']) : 1; +$size = isset($_CFG['page_size']) && intval($_CFG['page_size']) > 0 ? intval($_CFG['page_size']) : 10; +$brand = isset($_REQUEST['brand']) && intval($_REQUEST['brand']) > 0 ? intval($_REQUEST['brand']) : 0; +$price_max = isset($_REQUEST['price_max']) && intval($_REQUEST['price_max']) > 0 ? intval($_REQUEST['price_max']) : 0; +$price_min = isset($_REQUEST['price_min']) && intval($_REQUEST['price_min']) > 0 ? intval($_REQUEST['price_min']) : 0; +$filter_attr_str = isset($_REQUEST['filter_attr']) ? htmlspecialchars(trim($_REQUEST['filter_attr'])) : '0'; + +$filter_attr_str = trim(urldecode($filter_attr_str)); +$filter_attr_str = preg_match('/^[\d\.]+$/',$filter_attr_str) ? $filter_attr_str : ''; +$filter_attr = empty($filter_attr_str) ? '' : explode('.', $filter_attr_str); + + +/* 排序、显示方式以及类型 */ +$default_display_type = $_CFG['show_order_type'] == '0' ? 'list' : ($_CFG['show_order_type'] == '1' ? 'grid' : 'text'); +$default_sort_order_method = $_CFG['sort_order_method'] == '0' ? 'DESC' : 'ASC'; +$default_sort_order_type = $_CFG['sort_order_type'] == '0' ? 'goods_id' : ($_CFG['sort_order_type'] == '1' ? 'shop_price' : 'last_update'); + +$sort = (isset($_REQUEST['sort']) && in_array(trim(strtolower($_REQUEST['sort'])), array('goods_id', 'shop_price', 'last_update'))) ? trim($_REQUEST['sort']) : $default_sort_order_type; +$order = (isset($_REQUEST['order']) && in_array(trim(strtoupper($_REQUEST['order'])), array('ASC', 'DESC'))) ? trim($_REQUEST['order']) : $default_sort_order_method; +$display = (isset($_REQUEST['display']) && in_array(trim(strtolower($_REQUEST['display'])), array('list', 'grid', 'text'))) ? trim($_REQUEST['display']) : (isset($_COOKIE['ECS']['display']) ? $_COOKIE['ECS']['display'] : $default_display_type); +$display = in_array($display, array('list', 'grid', 'text')) ? $display : 'text'; +setcookie('ECS[display]', $display, gmtime() + 86400 * 7); +/*------------------------------------------------------ */ +//-- PROCESSOR +/*------------------------------------------------------ */ + +/* 页面的缓存ID */ +$cache_id = sprintf('%X', crc32($cat_id . '-' . $display . '-' . $sort .'-' . $order .'-' . $page . '-' . $size . '-' . $_SESSION['user_rank'] . '-' . + $_CFG['lang'] .'-'. $brand. '-' . $price_max . '-' .$price_min . '-' . $filter_attr_str)); + +if (!$smarty->is_cached('category.dwt', $cache_id)) +{ + /* 如果页面没有被缓存则重新获取页面的内容 */ + + $children = get_children($cat_id); + + $cat = get_cat_info($cat_id); // 获得分类的相关信息 + + if (!empty($cat)) + { + $smarty->assign('keywords', htmlspecialchars($cat['keywords'])); + $smarty->assign('description', htmlspecialchars($cat['cat_desc'])); + $smarty->assign('cat_style', htmlspecialchars($cat['style'])); + } + else + { + /* 如果分类不存在则返回首页 */ + ecs_header("Location: ./\n"); + + exit; + } + + /* 赋值固定内容 */ + if ($brand > 0) + { + $sql = "SELECT brand_name FROM " .$GLOBALS['ecs']->table('brand'). " WHERE brand_id = '$brand'"; + $brand_name = $db->getOne($sql); + } + else + { + $brand_name = ''; + } + + /* 获取价格分级 */ + if ($cat['grade'] == 0 && $cat['parent_id'] != 0) + { + $cat['grade'] = get_parent_grade($cat_id); //如果当前分类级别为空,取最近的上级分类 + } + + if ($cat['grade'] > 1) + { + /* 需要价格分级 */ + + /* + 算法思路: + 1、当分级大于1时,进行价格分级 + 2、取出该类下商品价格的最大值、最小值 + 3、根据商品价格的最大值来计算商品价格的分级数量级: + 价格范围(不含最大值) 分级数量级 + 0-0.1 0.001 + 0.1-1 0.01 + 1-10 0.1 + 10-100 1 + 100-1000 10 + 1000-10000 100 + 4、计算价格跨度: + 取整((最大值-最小值) / (价格分级数) / 数量级) * 数量级 + 5、根据价格跨度计算价格范围区间 + 6、查询数据库 + + 可能存在问题: + 1、 + 由于价格跨度是由最大值、最小值计算出来的 + 然后再通过价格跨度来确定显示时的价格范围区间 + 所以可能会存在价格分级数量不正确的问题 + 该问题没有证明 + 2、 + 当价格=最大值时,分级会多出来,已被证明存在 + */ + + $sql = "SELECT min(g.shop_price) AS min, max(g.shop_price) as max ". + " FROM " . $ecs->table('goods'). " AS g ". + " WHERE ($children OR " . get_extension_goods($children) . ') AND g.is_delete = 0 AND g.is_on_sale = 1 AND g.is_alone_sale = 1 '; + //获得当前分类下商品价格的最大值、最小值 + + $row = $db->getRow($sql); + + // 取得价格分级最小单位级数,比如,千元商品最小以100为级数 + $price_grade = 0.0001; + for($i=-2; $i<= log10($row['max']); $i++) + { + $price_grade *= 10; + } + + //跨度 + $dx = ceil(($row['max'] - $row['min']) / ($cat['grade']) / $price_grade) * $price_grade; + if($dx == 0) + { + $dx = $price_grade; + } + + for($i = 1; $row['min'] > $dx * $i; $i ++); + + for($j = 1; $row['min'] > $dx * ($i-1) + $price_grade * $j; $j++); + $row['min'] = $dx * ($i-1) + $price_grade * ($j - 1); + + for(; $row['max'] >= $dx * $i; $i ++); + $row['max'] = $dx * ($i) + $price_grade * ($j - 1); + + $sql = "SELECT (FLOOR((g.shop_price - $row[min]) / $dx)) AS sn, COUNT(*) AS goods_num ". + " FROM " . $ecs->table('goods') . " AS g ". + " WHERE ($children OR " . get_extension_goods($children) . ') AND g.is_delete = 0 AND g.is_on_sale = 1 AND g.is_alone_sale = 1 '. + " GROUP BY sn "; + + $price_grade = $db->getAll($sql); + + foreach ($price_grade as $key=>$val) + { + $temp_key = $key + 1; + $price_grade[$temp_key]['goods_num'] = $val['goods_num']; + $price_grade[$temp_key]['start'] = $row['min'] + round($dx * $val['sn']); + $price_grade[$temp_key]['end'] = $row['min'] + round($dx * ($val['sn'] + 1)); + $price_grade[$temp_key]['price_range'] = $price_grade[$temp_key]['start'] . ' - ' . $price_grade[$temp_key]['end']; + $price_grade[$temp_key]['formated_start'] = price_format($price_grade[$temp_key]['start']); + $price_grade[$temp_key]['formated_end'] = price_format($price_grade[$temp_key]['end']); + $price_grade[$temp_key]['url'] = build_uri('category', array('cid'=>$cat_id, 'bid'=>$brand, 'price_min'=>$price_grade[$temp_key]['start'], 'price_max'=> $price_grade[$temp_key]['end'], 'filter_attr'=>$filter_attr_str), $cat['cat_name']); + + /* 判断价格区间是否被选中 */ + if (isset($_REQUEST['price_min']) && $price_grade[$temp_key]['start'] == $price_min && $price_grade[$temp_key]['end'] == $price_max) + { + $price_grade[$temp_key]['selected'] = 1; + } + else + { + $price_grade[$temp_key]['selected'] = 0; + } + } + + $price_grade[0]['start'] = 0; + $price_grade[0]['end'] = 0; + $price_grade[0]['price_range'] = $_LANG['all_attribute']; + $price_grade[0]['url'] = build_uri('category', array('cid'=>$cat_id, 'bid'=>$brand, 'price_min'=>0, 'price_max'=> 0, 'filter_attr'=>$filter_attr_str), $cat['cat_name']); + $price_grade[0]['selected'] = empty($price_max) ? 1 : 0; + + $smarty->assign('price_grade', $price_grade); + + } + + + /* 品牌筛选 */ + + $sql = "SELECT b.brand_id, b.brand_name, COUNT(*) AS goods_num ". + "FROM " . $GLOBALS['ecs']->table('brand') . "AS b, ". + $GLOBALS['ecs']->table('goods') . " AS g LEFT JOIN ". $GLOBALS['ecs']->table('goods_cat') . " AS gc ON g.goods_id = gc.goods_id " . + "WHERE g.brand_id = b.brand_id AND ($children OR " . 'gc.cat_id ' . db_create_in(array_unique(array_merge(array($cat_id), array_keys(cat_list($cat_id, 0, false))))) . ") AND b.is_show = 1 " . + " AND g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0 ". + "GROUP BY b.brand_id HAVING goods_num > 0 ORDER BY b.sort_order, b.brand_id ASC"; + + $brands = $GLOBALS['db']->getAll($sql); + + foreach ($brands AS $key => $val) + { + $temp_key = $key + 1; + $brands[$temp_key]['brand_name'] = $val['brand_name']; + $brands[$temp_key]['url'] = build_uri('category', array('cid' => $cat_id, 'bid' => $val['brand_id'], 'price_min'=>$price_min, 'price_max'=> $price_max, 'filter_attr'=>$filter_attr_str), $cat['cat_name']); + + /* 判断品牌是否被选中 */ + if ($brand == $brands[$key]['brand_id']) + { + $brands[$temp_key]['selected'] = 1; + } + else + { + $brands[$temp_key]['selected'] = 0; + } + } + + $brands[0]['brand_name'] = $_LANG['all_attribute']; + $brands[0]['url'] = build_uri('category', array('cid' => $cat_id, 'bid' => 0, 'price_min'=>$price_min, 'price_max'=> $price_max, 'filter_attr'=>$filter_attr_str), $cat['cat_name']); + $brands[0]['selected'] = empty($brand) ? 1 : 0; + + $smarty->assign('brands', $brands); + + + /* 属性筛选 */ + $ext = ''; //商品查询条件扩展 + if ($cat['filter_attr'] > 0) + { + $cat_filter_attr = explode(',', $cat['filter_attr']); //提取出此分类的筛选属性 + $all_attr_list = array(); + + foreach ($cat_filter_attr AS $key => $value) + { + $sql = "SELECT a.attr_name FROM " . $ecs->table('attribute') . " AS a, " . $ecs->table('goods_attr') . " AS ga, " . $ecs->table('goods') . " AS g WHERE ($children OR " . get_extension_goods($children) . ") AND a.attr_id = ga.attr_id AND g.goods_id = ga.goods_id AND g.is_delete = 0 AND g.is_on_sale = 1 AND g.is_alone_sale = 1 AND a.attr_id='$value'"; + if($temp_name = $db->getOne($sql)) + { + $all_attr_list[$key]['filter_attr_name'] = $temp_name; + + $sql = "SELECT a.attr_id, MIN(a.goods_attr_id ) AS goods_id, a.attr_value AS attr_value FROM " . $ecs->table('goods_attr') . " AS a, " . $ecs->table('goods') . + " AS g" . + " WHERE ($children OR " . get_extension_goods($children) . ') AND g.goods_id = a.goods_id AND g.is_delete = 0 AND g.is_on_sale = 1 AND g.is_alone_sale = 1 '. + " AND a.attr_id='$value' ". + " GROUP BY a.attr_value"; + + $attr_list = $db->getAll($sql); + + $temp_arrt_url_arr = array(); + + for ($i = 0; $i < count($cat_filter_attr); $i++) //获取当前url中已选择属性的值,并保留在数组中 + { + $temp_arrt_url_arr[$i] = !empty($filter_attr[$i]) ? $filter_attr[$i] : 0; + } + + $temp_arrt_url_arr[$key] = 0; //“全部”的信息生成 + $temp_arrt_url = implode('.', $temp_arrt_url_arr); + $all_attr_list[$key]['attr_list'][0]['attr_value'] = $_LANG['all_attribute']; + $all_attr_list[$key]['attr_list'][0]['url'] = build_uri('category', array('cid'=>$cat_id, 'bid'=>$brand, 'price_min'=>$price_min, 'price_max'=>$price_max, 'filter_attr'=>$temp_arrt_url), $cat['cat_name']); + $all_attr_list[$key]['attr_list'][0]['selected'] = empty($filter_attr[$key]) ? 1 : 0; + + foreach ($attr_list as $k => $v) + { + $temp_key = $k + 1; + $temp_arrt_url_arr[$key] = $v['goods_id']; //为url中代表当前筛选属性的位置变量赋值,并生成以‘.’分隔的筛选属性字符串 + $temp_arrt_url = implode('.', $temp_arrt_url_arr); + + $all_attr_list[$key]['attr_list'][$temp_key]['attr_value'] = $v['attr_value']; + $all_attr_list[$key]['attr_list'][$temp_key]['url'] = build_uri('category', array('cid'=>$cat_id, 'bid'=>$brand, 'price_min'=>$price_min, 'price_max'=>$price_max, 'filter_attr'=>$temp_arrt_url), $cat['cat_name']); + + if (!empty($filter_attr[$key]) AND $filter_attr[$key] == $v['goods_id']) + { + $all_attr_list[$key]['attr_list'][$temp_key]['selected'] = 1; + } + else + { + $all_attr_list[$key]['attr_list'][$temp_key]['selected'] = 0; + } + } + } + + } + + $smarty->assign('filter_attr_list', $all_attr_list); + /* 扩展商品查询条件 */ + if (!empty($filter_attr)) + { + $ext_sql = "SELECT DISTINCT(b.goods_id) FROM " . $ecs->table('goods_attr') . " AS a, " . $ecs->table('goods_attr') . " AS b " . "WHERE "; + $ext_group_goods = array(); + + foreach ($filter_attr AS $k => $v) // 查出符合所有筛选属性条件的商品id */ + { + if (is_numeric($v) && $v !=0 &&isset($cat_filter_attr[$k])) + { + $sql = $ext_sql . "b.attr_value = a.attr_value AND b.attr_id = " . $cat_filter_attr[$k] ." AND a.goods_attr_id = " . $v; + $ext_group_goods = $db->getColCached($sql); + $ext .= ' AND ' . db_create_in($ext_group_goods, 'g.goods_id'); + } + } + } + } + + assign_template('c', array($cat_id)); + + $position = assign_ur_here($cat_id, $brand_name); + $smarty->assign('page_title', $position['title']); // 页面标题 + $smarty->assign('ur_here', $position['ur_here']); // 当前位置 + + $smarty->assign('categories', get_categories_tree()); // 分类树 + $smarty->assign('helps', get_shop_help()); // 网店帮助 + $smarty->assign('top_goods', get_top10()); // 销售排行 + $smarty->assign('show_marketprice', $_CFG['show_marketprice']); + $smarty->assign('category', $cat_id); + $smarty->assign('brand_id', $brand); + $smarty->assign('price_max', $price_max); + $smarty->assign('price_min', $price_min); + $smarty->assign('filter_attr', $filter_attr_str); + $smarty->assign('feed_url', ($_CFG['rewrite'] == 1) ? "feed-c$cat_id.xml" : 'feed.php?cat=' . $cat_id); // RSS URL + + if ($brand > 0) + { + $arr['all'] = array('brand_id' => 0, + 'brand_name' => $GLOBALS['_LANG']['all_goods'], + 'brand_logo' => '', + 'goods_num' => '', + 'url' => build_uri('category', array('cid'=>$cat_id), $cat['cat_name']) + ); + } + else + { + $arr = array(); + } + + $brand_list = array_merge($arr, get_brands($cat_id, 'category')); + + $smarty->assign('data_dir', DATA_DIR); + $smarty->assign('brand_list', $brand_list); + $smarty->assign('promotion_info', get_promotion_info()); + + + /* 调查 */ + $vote = get_vote(); + if (!empty($vote)) + { + $smarty->assign('vote_id', $vote['id']); + $smarty->assign('vote', $vote['content']); + } + + $smarty->assign('best_goods', get_category_recommend_goods('best', $children, $brand, $price_min, $price_max, $ext)); + $smarty->assign('promotion_goods', get_category_recommend_goods('promote', $children, $brand, $price_min, $price_max, $ext)); + $smarty->assign('hot_goods', get_category_recommend_goods('hot', $children, $brand, $price_min, $price_max, $ext)); + + $count = get_cagtegory_goods_count($children, $brand, $price_min, $price_max, $ext); + $max_page = ($count> 0) ? ceil($count / $size) : 1; + if ($page > $max_page) + { + $page = $max_page; + } + $goodslist = category_get_goods($children, $brand, $price_min, $price_max, $ext, $size, $page, $sort, $order); + if($display == 'grid') + { + if(count($goodslist) % 2 != 0) + { + $goodslist[] = array(); + } + } + $smarty->assign('goods_list', $goodslist); + $smarty->assign('category', $cat_id); + $smarty->assign('script_name', 'category'); + + assign_pager('category', $cat_id, $count, $size, $sort, $order, $page, '', $brand, $price_min, $price_max, $display, $filter_attr_str); // 分页 + assign_dynamic('category'); // 动态内容 +} + +$smarty->display('category.dwt', $cache_id); + +/*------------------------------------------------------ */ +//-- PRIVATE FUNCTION +/*------------------------------------------------------ */ + +/** + * 获得分类的信息 + * + * @param integer $cat_id + * + * @return void + */ +function get_cat_info($cat_id) +{ + return $GLOBALS['db']->getRow('SELECT cat_name, keywords, cat_desc, style, grade, filter_attr, parent_id FROM ' . $GLOBALS['ecs']->table('category') . + " WHERE cat_id = '$cat_id'"); +} + +/** + * 获得分类下的商品 + * + * @access public + * @param string $children + * @return array + */ +function category_get_goods($children, $brand, $min, $max, $ext, $size, $page, $sort, $order) +{ + $display = $GLOBALS['display']; + $where = "g.is_on_sale = 1 AND g.is_alone_sale = 1 AND ". + "g.is_delete = 0 AND ($children OR " . get_extension_goods($children) . ')'; + + if ($brand > 0) + { + $where .= "AND g.brand_id=$brand "; + } + + if ($min > 0) + { + $where .= " AND g.shop_price >= $min "; + } + + if ($max > 0) + { + $where .= " AND g.shop_price <= $max "; + } + + /* 获得商品列表 */ + $sql = 'SELECT g.goods_id, g.goods_name, g.goods_name_style, g.market_price, g.is_new, g.is_best, g.is_hot, g.shop_price AS org_price, ' . + "IFNULL(mp.user_price, g.shop_price * '$_SESSION[discount]') AS shop_price, g.promote_price, g.goods_type, " . + 'g.promote_start_date, g.promote_end_date, g.goods_brief, g.goods_thumb , g.goods_img ' . + 'FROM ' . $GLOBALS['ecs']->table('goods') . ' AS g ' . + 'LEFT JOIN ' . $GLOBALS['ecs']->table('member_price') . ' AS mp ' . + "ON mp.goods_id = g.goods_id AND mp.user_rank = '$_SESSION[user_rank]' " . + "WHERE $where $ext ORDER BY $sort $order"; + $res = $GLOBALS['db']->selectLimit($sql, $size, ($page - 1) * $size); + + $arr = array(); + while ($row = $GLOBALS['db']->fetchRow($res)) + { + if ($row['promote_price'] > 0) + { + $promote_price = bargain_price($row['promote_price'], $row['promote_start_date'], $row['promote_end_date']); + } + else + { + $promote_price = 0; + } + + /* 处理商品水印图片 */ + $watermark_img = ''; + + if ($promote_price != 0) + { + $watermark_img = "watermark_promote_small"; + } + elseif ($row['is_new'] != 0) + { + $watermark_img = "watermark_new_small"; + } + elseif ($row['is_best'] != 0) + { + $watermark_img = "watermark_best_small"; + } + elseif ($row['is_hot'] != 0) + { + $watermark_img = 'watermark_hot_small'; + } + + if ($watermark_img != '') + { + $arr[$row['goods_id']]['watermark_img'] = $watermark_img; + } + + $arr[$row['goods_id']]['goods_id'] = $row['goods_id']; + if($display == 'grid') + { + $arr[$row['goods_id']]['goods_name'] = $GLOBALS['_CFG']['goods_name_length'] > 0 ? sub_str($row['goods_name'], $GLOBALS['_CFG']['goods_name_length']) : $row['goods_name']; + } + else + { + $arr[$row['goods_id']]['goods_name'] = $row['goods_name']; + } + $arr[$row['goods_id']]['name'] = $row['goods_name']; + $arr[$row['goods_id']]['goods_brief'] = $row['goods_brief']; + $arr[$row['goods_id']]['goods_style_name'] = add_style($row['goods_name'],$row['goods_name_style']); + $arr[$row['goods_id']]['market_price'] = price_format($row['market_price']); + $arr[$row['goods_id']]['shop_price'] = price_format($row['shop_price']); + $arr[$row['goods_id']]['type'] = $row['goods_type']; + $arr[$row['goods_id']]['promote_price'] = ($promote_price > 0) ? price_format($promote_price) : ''; + $arr[$row['goods_id']]['goods_thumb'] = get_image_path($row['goods_id'], $row['goods_thumb'], true); + $arr[$row['goods_id']]['goods_img'] = get_image_path($row['goods_id'], $row['goods_img']); + $arr[$row['goods_id']]['url'] = build_uri('goods', array('gid'=>$row['goods_id']), $row['goods_name']); + } + + return $arr; +} + +/** + * 获得分类下的商品总数 + * + * @access public + * @param string $cat_id + * @return integer + */ +function get_cagtegory_goods_count($children, $brand = 0, $min = 0, $max = 0, $ext='') +{ + $where = "g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0 AND ($children OR " . get_extension_goods($children) . ')'; + + if ($brand > 0) + { + $where .= " AND g.brand_id = $brand "; + } + + if ($min > 0) + { + $where .= " AND g.shop_price >= $min "; + } + + if ($max > 0) + { + $where .= " AND g.shop_price <= $max "; + } + + /* 返回商品总数 */ + return $GLOBALS['db']->getOne('SELECT COUNT(*) FROM ' . $GLOBALS['ecs']->table('goods') . " AS g WHERE $where $ext"); +} + +/** + * 取得最近的上级分类的grade值 + * + * @access public + * @param int $cat_id //当前的cat_id + * + * @return int + */ +function get_parent_grade($cat_id) +{ + static $res = NULL; + + if ($res === NULL) + { + $data = read_static_cache('cat_parent_grade'); + if ($data === false) + { + $sql = "SELECT parent_id, cat_id, grade ". + " FROM " . $GLOBALS['ecs']->table('category'); + $res = $GLOBALS['db']->getAll($sql); + write_static_cache('cat_parent_grade', $res); + } + else + { + $res = $data; + } + } + + if (!$res) + { + return 0; + } + + $parent_arr = array(); + $grade_arr = array(); + + foreach ($res as $val) + { + $parent_arr[$val['cat_id']] = $val['parent_id']; + $grade_arr[$val['cat_id']] = $val['grade']; + } + + while ($parent_arr[$cat_id] >0 && $grade_arr[$cat_id] == 0) + { + $cat_id = $parent_arr[$cat_id]; + } + + return $grade_arr[$cat_id]; + +} + + +?> diff --git a/cert/index.htm b/cert/index.htm new file mode 100644 index 0000000..0519ecb --- /dev/null +++ b/cert/index.htm @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/certi.php b/certi.php new file mode 100644 index 0000000..8dcfb87 --- /dev/null +++ b/certi.php @@ -0,0 +1,44 @@ +table('sessions') . " WHERE sesskey = '" . $session_id . "' "; + $sesskey = $db->getOne($sql); + if ($sesskey != '') + { + exit('{"res":"succ","msg":"","info":""}'); + } + else + { + exit('{"res":"fail","msg":"error:000002","info":""}'); + } +} +else +{ + exit('{"res":"fail","msg":"error:000001","info":""}'); +} + +?> \ No newline at end of file diff --git a/chinabank_receive.php b/chinabank_receive.php new file mode 100644 index 0000000..b2d4b27 --- /dev/null +++ b/chinabank_receive.php @@ -0,0 +1,70 @@ +getOne("SELECT pay_config FROM " . $ecs->table('payment') . " WHERE pay_code = 'chinabank' AND enabled = 1"); +if (!empty($payment)) +{ + $payment = unserialize($payment); + foreach($payment as $k=>$v) + { + if ($v['name'] == 'chinabank_key') + { + $key = $v['value']; + } + } +} +else +{ + die('error'); +} + +$v_oid =trim($_POST['v_oid']); +$v_pmode =trim($_POST['v_pmode']); +$v_pstatus =trim($_POST['v_pstatus']); +$v_pstring =trim($_POST['v_pstring']); +$v_amount =trim($_POST['v_amount']); +$v_moneytype =trim($_POST['v_moneytype']); +$remark1 =trim($_POST['remark1' ]); +$remark2 =trim($_POST['remark2' ]); +$v_md5str =trim($_POST['v_md5str' ]); + +$md5string = strtoupper(md5($v_oid.$v_pstatus.$v_amount.$v_moneytype.$key)); +if ($v_md5str == $md5string) +{ + if($v_pstatus == '20') + { + if ($remark1 == 'voucher') + { + $v_oid = get_order_id_by_sn($v_oid, "true"); + } + else + { + $v_oid = get_order_id_by_sn($v_oid); + } + order_paid($v_oid); + } + echo 'ok'; +}else{ + echo 'error'; +} +?> \ No newline at end of file diff --git a/comment.php b/comment.php new file mode 100644 index 0000000..9675d14 --- /dev/null +++ b/comment.php @@ -0,0 +1,305 @@ + 0, 'message' => '', 'content' => ''); + +if (empty($_REQUEST['act'])) +{ + /* + * act 参数为空 + * 默认为添加评论内容 + */ + $cmt = $json->decode($_REQUEST['cmt']); + $cmt->page = 1; + $cmt->id = !empty($cmt->id) ? intval($cmt->id) : 0; + $cmt->type = !empty($cmt->type) ? intval($cmt->type) : 0; + + if (empty($cmt) || !isset($cmt->type) || !isset($cmt->id)) + { + $result['error'] = 1; + $result['message'] = $_LANG['invalid_comments']; + } + elseif (!is_email($cmt->email)) + { + $result['error'] = 1; + $result['message'] = $_LANG['error_email']; + } + else + { + if ((intval($_CFG['captcha']) & CAPTCHA_COMMENT) && gd_version() > 0) + { + /* 检查验证码 */ + include_once('includes/cls_captcha.php'); + + $validator = new captcha(); + if (!$validator->check_word($cmt->captcha)) + { + $result['error'] = 1; + $result['message'] = $_LANG['invalid_captcha']; + } + else + { + $factor = intval($_CFG['comment_factor']); + if ($cmt->type == 0 && $factor > 0) + { + /* 只有商品才检查评论条件 */ + switch ($factor) + { + case COMMENT_LOGIN : + if ($_SESSION['user_id'] == 0) + { + $result['error'] = 1; + $result['message'] = $_LANG['comment_login']; + } + break; + + case COMMENT_CUSTOM : + if ($_SESSION['user_id'] > 0) + { + $sql = "SELECT o.order_id FROM " . $ecs->table('order_info') . " AS o ". + " WHERE user_id = '" . $_SESSION['user_id'] . "'". + " AND (o.order_status = '" . OS_CONFIRMED . "' or o.order_status = '" . OS_SPLITED . "') ". + " AND (o.pay_status = '" . PS_PAYED . "' OR o.pay_status = '" . PS_PAYING . "') ". + " AND (o.shipping_status = '" . SS_SHIPPED . "' OR o.shipping_status = '" . SS_RECEIVED . "') ". + " LIMIT 1"; + + + $tmp = $db->getOne($sql); + if (empty($tmp)) + { + $result['error'] = 1; + $result['message'] = $_LANG['comment_custom']; + } + } + else + { + $result['error'] = 1; + $result['message'] = $_LANG['comment_custom']; + } + break; + case COMMENT_BOUGHT : + if ($_SESSION['user_id'] > 0) + { + $sql = "SELECT o.order_id". + " FROM " . $ecs->table('order_info'). " AS o, ". + $ecs->table('order_goods') . " AS og ". + " WHERE o.order_id = og.order_id". + " AND o.user_id = '" . $_SESSION['user_id'] . "'". + " AND og.goods_id = '" . $cmt->id . "'". + " AND (o.order_status = '" . OS_CONFIRMED . "' or o.order_status = '" . OS_SPLITED . "') ". + " AND (o.pay_status = '" . PS_PAYED . "' OR o.pay_status = '" . PS_PAYING . "') ". + " AND (o.shipping_status = '" . SS_SHIPPED . "' OR o.shipping_status = '" . SS_RECEIVED . "') ". + " LIMIT 1"; + $tmp = $db->getOne($sql); + if (empty($tmp)) + { + $result['error'] = 1; + $result['message'] = $_LANG['comment_brought']; + } + } + else + { + $result['error'] = 1; + $result['message'] = $_LANG['comment_brought']; + } + } + } + + /* 无错误就保存留言 */ + if (empty($result['error'])) + { + add_comment($cmt); + } + } + } + else + { + /* 没有验证码时,用时间来限制机器人发帖或恶意发评论 */ + if (!isset($_SESSION['send_time'])) + { + $_SESSION['send_time'] = 0; + } + + $cur_time = gmtime(); + if (($cur_time - $_SESSION['send_time']) < 30) // 小于30秒禁止发评论 + { + $result['error'] = 1; + $result['message'] = $_LANG['cmt_spam_warning']; + } + else + { + $factor = intval($_CFG['comment_factor']); + if ($cmt->type == 0 && $factor > 0) + { + /* 只有商品才检查评论条件 */ + switch ($factor) + { + case COMMENT_LOGIN : + if ($_SESSION['user_id'] == 0) + { + $result['error'] = 1; + $result['message'] = $_LANG['comment_login']; + } + break; + + case COMMENT_CUSTOM : + if ($_SESSION['user_id'] > 0) + { + $sql = "SELECT o.order_id FROM " . $ecs->table('order_info') . " AS o ". + " WHERE user_id = '" . $_SESSION['user_id'] . "'". + " AND (o.order_status = '" . OS_CONFIRMED . "' or o.order_status = '" . OS_SPLITED . "') ". + " AND (o.pay_status = '" . PS_PAYED . "' OR o.pay_status = '" . PS_PAYING . "') ". + " AND (o.shipping_status = '" . SS_SHIPPED . "' OR o.shipping_status = '" . SS_RECEIVED . "') ". + " LIMIT 1"; + + + $tmp = $db->getOne($sql); + if (empty($tmp)) + { + $result['error'] = 1; + $result['message'] = $_LANG['comment_custom']; + } + } + else + { + $result['error'] = 1; + $result['message'] = $_LANG['comment_custom']; + } + break; + + case COMMENT_BOUGHT : + if ($_SESSION['user_id'] > 0) + { + $sql = "SELECT o.order_id". + " FROM " . $ecs->table('order_info'). " AS o, ". + $ecs->table('order_goods') . " AS og ". + " WHERE o.order_id = og.order_id". + " AND o.user_id = '" . $_SESSION['user_id'] . "'". + " AND og.goods_id = '" . $cmt->id . "'". + " AND (o.order_status = '" . OS_CONFIRMED . "' or o.order_status = '" . OS_SPLITED . "') ". + " AND (o.pay_status = '" . PS_PAYED . "' OR o.pay_status = '" . PS_PAYING . "') ". + " AND (o.shipping_status = '" . SS_SHIPPED . "' OR o.shipping_status = '" . SS_RECEIVED . "') ". + " LIMIT 1"; + $tmp = $db->getOne($sql); + if (empty($tmp)) + { + $result['error'] = 1; + $result['message'] = $_LANG['comment_brought']; + } + } + else + { + $result['error'] = 1; + $result['message'] = $_LANG['comment_brought']; + } + } + } + /* 无错误就保存留言 */ + if (empty($result['error'])) + { + add_comment($cmt); + $_SESSION['send_time'] = $cur_time; + } + } + } + } +} +else +{ + /* + * act 参数不为空 + * 默认为评论内容列表 + * 根据 _GET 创建一个静态对象 + */ + $cmt = new stdClass(); + $cmt->id = !empty($_GET['id']) ? intval($_GET['id']) : 0; + $cmt->type = !empty($_GET['type']) ? intval($_GET['type']) : 0; + $cmt->page = isset($_GET['page']) && intval($_GET['page']) > 0 ? intval($_GET['page']) : 1; +} + +if ($result['error'] == 0) +{ + $comments = assign_comment($cmt->id, $cmt->type, $cmt->page); + + $smarty->assign('comment_type', $cmt->type); + $smarty->assign('id', $cmt->id); + $smarty->assign('username', $_SESSION['user_name']); + $smarty->assign('email', $_SESSION['email']); + $smarty->assign('comments', $comments['comments']); + $smarty->assign('pager', $comments['pager']); + + /* 验证码相关设置 */ + if ((intval($_CFG['captcha']) & CAPTCHA_COMMENT) && gd_version() > 0) + { + $smarty->assign('enabled_captcha', 1); + $smarty->assign('rand', mt_rand()); + } + + $result['message'] = $_CFG['comment_check'] ? $_LANG['cmt_submit_wait'] : $_LANG['cmt_submit_done']; + $result['content'] = $smarty->fetch("library/comments_list.lbi"); +} + +echo $json->encode($result); + +/*------------------------------------------------------ */ +//-- PRIVATE FUNCTION +/*------------------------------------------------------ */ + +/** + * 添加评论内容 + * + * @access public + * @param object $cmt + * @return void + */ +function add_comment($cmt) +{ + /* 评论是否需要审核 */ + $status = 1 - $GLOBALS['_CFG']['comment_check']; + + $user_id = empty($_SESSION['user_id']) ? 0 : $_SESSION['user_id']; + $email = empty($cmt->email) ? $_SESSION['email'] : trim($cmt->email); + $user_name = empty($cmt->username) ? $_SESSION['user_name'] : trim($cmt->username); + $email = htmlspecialchars($email); + $user_name = htmlspecialchars($user_name); + + /* 保存评论内容 */ + $sql = "INSERT INTO " .$GLOBALS['ecs']->table('comment') . + "(comment_type, id_value, email, user_name, content, comment_rank, add_time, ip_address, status, parent_id, user_id) VALUES " . + "('" .$cmt->type. "', '" .$cmt->id. "', '$email', '$user_name', '" .$cmt->content."', '".$cmt->rank."', ".gmtime().", '".real_ip()."', '$status', '0', '$user_id')"; + + $result = $GLOBALS['db']->query($sql); + clear_cache_files('comments_list.lbi'); + /*if ($status > 0) + { + add_feed($GLOBALS['db']->insert_id(), COMMENT_GOODS); + }*/ + return $result; +} + +?> \ No newline at end of file diff --git a/compare.php b/compare.php new file mode 100644 index 0000000..539a78d --- /dev/null +++ b/compare.php @@ -0,0 +1,125 @@ + 1) +{ + $where = db_create_in($_REQUEST['goods'], 'id_value'); + $sql = "SELECT id_value , AVG(comment_rank) AS cmt_rank, COUNT(*) AS cmt_count" . + " FROM " .$ecs->table('comment') . + " WHERE $where AND comment_type = 0". + ' GROUP BY id_value '; + $query = $db->query($sql); + $cmt = array(); + while ($row = $db->fetch_array($query)) + { + $cmt[$row['id_value']] = $row; + } + + $where = db_create_in($_REQUEST['goods'], 'g.goods_id'); + $sql = "SELECT g.goods_id, g.goods_type, g.goods_name, g.shop_price, g.goods_weight, g.goods_thumb, g.goods_brief, ". + "a.attr_name, v.attr_value, a.attr_id, b.brand_name, ". + "IFNULL(mp.user_price, g.shop_price * '$_SESSION[discount]') AS rank_price " . + "FROM " .$ecs->table('goods'). " AS g ". + "LEFT JOIN " . $ecs->table('goods_attr'). " AS v ON v.goods_id = g.goods_id ". + "LEFT JOIN " . $ecs->table('attribute') . " AS a ON a.attr_id = v.attr_id " . + "LEFT JOIN " . $ecs->table('brand') . " AS b ON g.brand_id = b.brand_id " . + "LEFT JOIN " . $ecs->table('member_price') . " AS mp ". + "ON mp.goods_id = g.goods_id AND mp.user_rank = '$_SESSION[user_rank]' ". + "WHERE g.is_delete = 0 AND $where ". + "ORDER BY a.attr_id"; + $res = $db->query($sql); + $arr = array(); + $ids = $_REQUEST['goods']; + $attr_name = array(); + $type_id = 0; + while ($row = $db->fetchRow($res)) + { + $goods_id = $row['goods_id']; + $type_id = $row['goods_type']; + $arr[$goods_id]['goods_id'] = $goods_id; + $arr[$goods_id]['url'] = build_uri('goods', array('gid' => $goods_id), $row['goods_name']); + $arr[$goods_id]['goods_name'] = $row['goods_name']; + $arr[$goods_id]['shop_price'] = price_format($row['shop_price']); + $arr[$goods_id]['rank_price'] = price_format($row['rank_price']); + $arr[$goods_id]['goods_weight'] = (intval($row['goods_weight']) > 0) ? + ceil($row['goods_weight']) . $_LANG['kilogram'] : ceil($row['goods_weight'] * 1000) . $_LANG['gram']; + $arr[$goods_id]['goods_thumb'] = get_image_path($row['goods_id'], $row['goods_thumb'], true); + $arr[$goods_id]['goods_brief'] = $row['goods_brief']; + $arr[$goods_id]['brand_name'] = $row['brand_name']; + + $arr[$goods_id]['properties'][$row['attr_id']]['name'] = $row['attr_name']; + if (!empty($arr[$goods_id]['properties'][$row['attr_id']]['value'])) + { + $arr[$goods_id]['properties'][$row['attr_id']]['value'] .= ',' . $row['attr_value']; + } + else + { + $arr[$goods_id]['properties'][$row['attr_id']]['value'] = $row['attr_value']; + } + + if (!isset($arr[$goods_id]['comment_rank'])) + { + $arr[$goods_id]['comment_rank'] = isset($cmt[$goods_id]) ? ceil($cmt[$goods_id]['cmt_rank']) : 0; + $arr[$goods_id]['comment_number'] = isset($cmt[$goods_id]) ? $cmt[$goods_id]['cmt_count'] : 0; + $arr[$goods_id]['comment_number'] = sprintf($_LANG['comment_num'], $arr[$goods_id]['comment_number']); + } + + $tmp = $ids; + $key = array_search($goods_id, $tmp); + + if ($key !== null && $key !== false) + { + unset($tmp[$key]); + } + + $arr[$goods_id]['ids'] = !empty($tmp) ? "goods[]=" . implode('&goods[]=', $tmp) : ''; + } + + $sql = "SELECT attr_id,attr_name FROM " . $ecs->table('attribute') . " WHERE cat_id='$type_id' ORDER BY attr_id"; + + $attribute = array(); + + $query = $db->query($sql); + while ($rt = $db->fetch_array($query)) + { + $attribute[$rt['attr_id']] = $rt['attr_name']; + } + + $smarty->assign('attribute', $attribute); + $smarty->assign('goods_list', $arr); +} +else +{ + show_message($_LANG['compare_no_goods']); + exit; +} + +assign_template(); +$position = assign_ur_here(0, $_LANG['goods_compare']); +$smarty->assign('page_title', $position['title']); // 页面标题 +$smarty->assign('ur_here', $position['ur_here']); // 当前位置 + +$smarty->assign('categories', get_categories_tree()); // 分类树 +$smarty->assign('helps', get_shop_help()); // 网店帮助 + +assign_dynamic('compare'); + +$smarty->display('compare.dwt'); + +?> \ No newline at end of file diff --git a/cycle_image.php b/cycle_image.php new file mode 100644 index 0000000..b54d9de --- /dev/null +++ b/cycle_image.php @@ -0,0 +1,36 @@ +'; +} +?> \ No newline at end of file diff --git a/delete_cart_goods.php b/delete_cart_goods.php new file mode 100644 index 0000000..e5fd814 --- /dev/null +++ b/delete_cart_goods.php @@ -0,0 +1,74 @@ + 0, 'message' => '', 'content' => '', 'goods_id' => ''); +$json = new JSON; +if($_POST['id']) +{ +$sql = 'DELETE FROM '.$GLOBALS['ecs']->table('cart')." WHERE rec_id=".$_POST['id']; +$GLOBALS['db']->query($sql); +} +$sql = 'SELECT c.*,g.goods_name,g.goods_thumb,g.goods_id,c.goods_number,c.goods_price' . + ' FROM ' . $GLOBALS['ecs']->table('cart') ." AS c ". + " LEFT JOIN ".$GLOBALS['ecs']->table('goods')." AS g ON g.goods_id=c.goods_id ". + " WHERE session_id = '" . SESS_ID . "' AND rec_type = '" . CART_GENERAL_GOODS . "'"; +$row = $GLOBALS['db']->GetAll($sql); +$arr = array(); +foreach($row AS $k=>$v) +{ + $arr[$k]['goods_thumb'] =get_image_path($v['goods_id'], $v['goods_thumb'], true); + $arr[$k]['short_name'] = $GLOBALS['_CFG']['goods_name_length'] > 0 ? + sub_str($v['goods_name'], $GLOBALS['_CFG']['goods_name_length']) : $v['goods_name']; + $arr[$k]['url'] = build_uri('goods', array('gid' => $v['goods_id']), $v['goods_name']); + $arr[$k]['goods_number'] = $v['goods_number']; + $arr[$k]['goods_name'] = $v['goods_name']; + $arr[$k]['goods_price'] = price_format($v['goods_price']); + $arr[$k]['goods_amount_price'] = price_format($v['goods_price']*$v['goods_number']); + $arr[$k]['rec_id'] = $v['rec_id']; +} +$sql = 'SELECT SUM(goods_number) AS number, SUM(goods_price * goods_number) AS amount' . + ' FROM ' . $GLOBALS['ecs']->table('cart') . + " WHERE session_id = '" . SESS_ID . "' AND rec_type = '" . CART_GENERAL_GOODS . "'"; +$row = $GLOBALS['db']->GetRow($sql); + +if ($row) +{ + $number = intval($row['number']); + $amount = floatval($row['amount']); +} +else +{ + $number = 0; + $amount = 0; +} + +$GLOBALS['smarty']->assign('str',sprintf($GLOBALS['_LANG']['cart_info'], $number, price_format($amount, false))); +$GLOBALS['smarty']->assign('cart_list_number',$number); +$GLOBALS['smarty']->assign('cart_list_amount',price_format($amount)); +$GLOBALS['smarty']->assign('goods',$arr); +$GLOBALS['smarty']->assign('order',$order); +$GLOBALS['smarty']->assign('order_amount',$amount); + + +$result['content'] = $GLOBALS['smarty']->fetch('library/cart_info.lbi'); + +die($json->encode($result)); +?> \ No newline at end of file diff --git "a/ecshop\346\250\241\346\235\277\347\275\221 - ecshop\346\250\241\346\235\277\345\210\266\344\275\234\344\272\214\346\254\241\345\274\200\345\217\221\347\254\254\344\270\200\347\253\231.url" "b/ecshop\346\250\241\346\235\277\347\275\221 - ecshop\346\250\241\346\235\277\345\210\266\344\275\234\344\272\214\346\254\241\345\274\200\345\217\221\347\254\254\344\270\200\347\253\231.url" new file mode 100644 index 0000000..8360d56 --- /dev/null +++ "b/ecshop\346\250\241\346\235\277\347\275\221 - ecshop\346\250\241\346\235\277\345\210\266\344\275\234\344\272\214\346\254\241\345\274\200\345\217\221\347\254\254\344\270\200\347\253\231.url" @@ -0,0 +1,9 @@ +[DEFAULT] +BASEURL=http://www.ecshoptemplate.com/ +[{000214A0-0000-0000-C000-000000000046}] +Prop3=19,2 +[InternetShortcut] +URL=http://www.ecshoptemplate.com/ +IDList= +IconFile=http://www.ecshoptemplate.com/favicon.ico +IconIndex=1 diff --git a/exchange.php b/exchange.php new file mode 100644 index 0000000..2bc7dd0 --- /dev/null +++ b/exchange.php @@ -0,0 +1,600 @@ +caching = true; +} + +/*------------------------------------------------------ */ +//-- act 操作项的初始化 +/*------------------------------------------------------ */ +if (empty($_REQUEST['act'])) +{ + $_REQUEST['act'] = 'list'; +} + +/*------------------------------------------------------ */ +//-- PROCESSOR +/*------------------------------------------------------ */ + +/*------------------------------------------------------ */ +//-- 积分兑换商品列表 +/*------------------------------------------------------ */ +if ($_REQUEST['act'] == 'list') +{ + /* 初始化分页信息 */ + $page = isset($_REQUEST['page']) && intval($_REQUEST['page']) > 0 ? intval($_REQUEST['page']) : 1; + $size = isset($_CFG['page_size']) && intval($_CFG['page_size']) > 0 ? intval($_CFG['page_size']) : 10; + $cat_id = isset($_REQUEST['cat_id']) && intval($_REQUEST['cat_id']) > 0 ? intval($_REQUEST['cat_id']) : 0; + $integral_max = isset($_REQUEST['integral_max']) && intval($_REQUEST['integral_max']) > 0 ? intval($_REQUEST['integral_max']) : 0; + $integral_min = isset($_REQUEST['integral_min']) && intval($_REQUEST['integral_min']) > 0 ? intval($_REQUEST['integral_min']) : 0; + + /* 排序、显示方式以及类型 */ + $default_display_type = $_CFG['show_order_type'] == '0' ? 'list' : ($_CFG['show_order_type'] == '1' ? 'grid' : 'text'); + $default_sort_order_method = $_CFG['sort_order_method'] == '0' ? 'DESC' : 'ASC'; + $default_sort_order_type = $_CFG['sort_order_type'] == '0' ? 'goods_id' : ($_CFG['sort_order_type'] == '1' ? 'exchange_integral' : 'last_update'); + + $sort = (isset($_REQUEST['sort']) && in_array(trim(strtolower($_REQUEST['sort'])), array('goods_id', 'exchange_integral', 'last_update'))) ? trim($_REQUEST['sort']) : $default_sort_order_type; + $order = (isset($_REQUEST['order']) && in_array(trim(strtoupper($_REQUEST['order'])), array('ASC', 'DESC'))) ? trim($_REQUEST['order']) : $default_sort_order_method; + $display = (isset($_REQUEST['display']) && in_array(trim(strtolower($_REQUEST['display'])), array('list', 'grid', 'text'))) ? trim($_REQUEST['display']) : (isset($_COOKIE['ECS']['display']) ? $_COOKIE['ECS']['display'] : $default_display_type); + $display = in_array($display, array('list', 'grid', 'text')) ? $display : 'text'; + setcookie('ECS[display]', $display, gmtime() + 86400 * 7); + + /* 页面的缓存ID */ + $cache_id = sprintf('%X', crc32($cat_id . '-' . $display . '-' . $sort .'-' . $order .'-' . $page . '-' . $size . '-' . $_SESSION['user_rank'] . '-' . + $_CFG['lang'] . '-' . $integral_max . '-' .$integral_min)); + + if (!$smarty->is_cached('exchange.dwt', $cache_id)) + { + /* 如果页面没有被缓存则重新获取页面的内容 */ + + $children = get_children($cat_id); + + $cat = get_cat_info($cat_id); // 获得分类的相关信息 + + if (!empty($cat)) + { + $smarty->assign('keywords', htmlspecialchars($cat['keywords'])); + $smarty->assign('description', htmlspecialchars($cat['cat_desc'])); + } + + assign_template(); + + $position = assign_ur_here('exchange'); + $smarty->assign('page_title', $position['title']); // 页面标题 + $smarty->assign('ur_here', $position['ur_here']); // 当前位置 + + $smarty->assign('categories', get_categories_tree()); // 分类树 + $smarty->assign('helps', get_shop_help()); // 网店帮助 + $smarty->assign('top_goods', get_top10()); // 销售排行 + $smarty->assign('promotion_info', get_promotion_info()); // 促销活动信息 + + /* 调查 */ + $vote = get_vote(); + if (!empty($vote)) + { + $smarty->assign('vote_id', $vote['id']); + $smarty->assign('vote', $vote['content']); + } + + $ext = ''; //商品查询条件扩展 + + //$smarty->assign('best_goods', get_exchange_recommend_goods('best', $children, $integral_min, $integral_max)); + //$smarty->assign('new_goods', get_exchange_recommend_goods('new', $children, $integral_min, $integral_max)); + $smarty->assign('hot_goods', get_exchange_recommend_goods('hot', $children, $integral_min, $integral_max)); + + + $count = get_exchange_goods_count($children, $integral_min, $integral_max); + $max_page = ($count> 0) ? ceil($count / $size) : 1; + if ($page > $max_page) + { + $page = $max_page; + } + $goodslist = exchange_get_goods($children, $integral_min, $integral_max, $ext, $size, $page, $sort, $order); + if($display == 'grid') + { + if(count($goodslist) % 2 != 0) + { + $goodslist[] = array(); + } + } + $smarty->assign('goods_list', $goodslist); + $smarty->assign('category', $cat_id); + $smarty->assign('integral_max', $integral_max); + $smarty->assign('integral_min', $integral_min); + + + assign_pager('exchange', $cat_id, $count, $size, $sort, $order, $page, '', '', $integral_min, $integral_max, $display); // 分页 + assign_dynamic('exchange_list'); // 动态内容 + } + + $smarty->assign('feed_url', ($_CFG['rewrite'] == 1) ? "feed-typeexchange.xml" : 'feed.php?type=exchange'); // RSS URL + $smarty->display('exchange_list.dwt', $cache_id); +} + +/*------------------------------------------------------ */ +//-- 积分兑换商品详情 +/*------------------------------------------------------ */ +elseif ($_REQUEST['act'] == 'view') +{ + $goods_id = isset($_REQUEST['id']) ? intval($_REQUEST['id']) : 0; + + $cache_id = $goods_id . '-' . $_SESSION['user_rank'] . '-' . $_CFG['lang'] . '-exchange'; + $cache_id = sprintf('%X', crc32($cache_id)); + + if (!$smarty->is_cached('exchange_goods.dwt', $cache_id)) + { + $smarty->assign('image_width', $_CFG['image_width']); + $smarty->assign('image_height', $_CFG['image_height']); + $smarty->assign('helps', get_shop_help()); // 网店帮助 + $smarty->assign('id', $goods_id); + $smarty->assign('type', 0); + $smarty->assign('cfg', $_CFG); + + /* 获得商品的信息 */ + $goods = get_exchange_goods_info($goods_id); + + if ($goods === false) + { + /* 如果没有找到任何记录则跳回到首页 */ + ecs_header("Location: ./\n"); + exit; + } + else + { + if ($goods['brand_id'] > 0) + { + $goods['goods_brand_url'] = build_uri('brand', array('bid'=>$goods['brand_id']), $goods['goods_brand']); + } + + $goods['goods_style_name'] = add_style($goods['goods_name'], $goods['goods_name_style']); + + $smarty->assign('goods', $goods); + $smarty->assign('goods_id', $goods['goods_id']); + $smarty->assign('categories', get_categories_tree()); // 分类树 + + /* meta */ + $smarty->assign('keywords', htmlspecialchars($goods['keywords'])); + $smarty->assign('description', htmlspecialchars($goods['goods_brief'])); + + assign_template(); + + /* 上一个商品下一个商品 */ + $sql = "SELECT eg.goods_id FROM " .$ecs->table('exchange_goods'). " AS eg," . $GLOBALS['ecs']->table('goods') . " AS g WHERE eg.goods_id = g.goods_id AND eg.goods_id > " . $goods['goods_id'] . " AND eg.is_exchange = 1 AND g.is_delete = 0 LIMIT 1"; + $prev_gid = $db->getOne($sql); + if (!empty($prev_gid)) + { + $prev_good['url'] = build_uri('exchange_goods', array('gid' => $prev_gid), $goods['goods_name']); + $smarty->assign('prev_good', $prev_good);//上一个商品 + } + + $sql = "SELECT max(eg.goods_id) FROM " . $ecs->table('exchange_goods') . " AS eg," . $GLOBALS['ecs']->table('goods') . " AS g WHERE eg.goods_id = g.goods_id AND eg.goods_id < ".$goods['goods_id'] . " AND eg.is_exchange = 1 AND g.is_delete = 0"; + $next_gid = $db->getOne($sql); + if (!empty($next_gid)) + { + $next_good['url'] = build_uri('exchange_goods', array('gid' => $next_gid), $goods['goods_name']); + $smarty->assign('next_good', $next_good);//下一个商品 + } + + /* current position */ + $position = assign_ur_here('exchange', $goods['goods_name']); + $smarty->assign('page_title', $position['title']); // 页面标题 + $smarty->assign('ur_here', $position['ur_here']); // 当前位置 + + $properties = get_goods_properties($goods_id); // 获得商品的规格和属性 + $smarty->assign('properties', $properties['pro']); // 商品属性 + $smarty->assign('specification', $properties['spe']); // 商品规格 + + $smarty->assign('pictures', get_goods_gallery($goods_id)); // 商品相册 + + assign_dynamic('exchange_goods'); + } + } + + $smarty->display('exchange_goods.dwt', $cache_id); +} + +/*------------------------------------------------------ */ +//-- 兑换 +/*------------------------------------------------------ */ + +elseif ($_REQUEST['act'] == 'buy') +{ + /* 查询:判断是否登录 */ + if (!isset($back_act) && isset($GLOBALS['_SERVER']['HTTP_REFERER'])) + { + $back_act = strpos($GLOBALS['_SERVER']['HTTP_REFERER'], 'exchange') ? $GLOBALS['_SERVER']['HTTP_REFERER'] : './index.php'; + } + + /* 查询:判断是否登录 */ + if ($_SESSION['user_id'] <= 0) + { + show_message($_LANG['eg_error_login'], array($_LANG['back_up_page']), array($back_act), 'error'); + } + + /* 查询:取得参数:商品id */ + $goods_id = isset($_POST['goods_id']) ? intval($_POST['goods_id']) : 0; + if ($goods_id <= 0) + { + ecs_header("Location: ./\n"); + exit; + } + + /* 查询:取得兑换商品信息 */ + $goods = get_exchange_goods_info($goods_id); + if (empty($goods)) + { + ecs_header("Location: ./\n"); + exit; + } + /* 查询:检查兑换商品是否有库存 */ + if($goods['goods_number'] == 0 && $_CFG['use_storage'] == 1) + { + show_message($_LANG['eg_error_number'], array($_LANG['back_up_page']), array($back_act), 'error'); + } + /* 查询:检查兑换商品是否是取消 */ + if ($goods['is_exchange'] == 0) + { + show_message($_LANG['eg_error_status'], array($_LANG['back_up_page']), array($back_act), 'error'); + } + + $user_info = get_user_info($_SESSION['user_id']); + $user_points = $user_info['pay_points']; // 用户的积分总数 + if ($goods['exchange_integral'] > $user_points) + { + show_message($_LANG['eg_error_integral'], array($_LANG['back_up_page']), array($back_act), 'error'); + } + + /* 查询:取得规格 */ + $specs = ''; + foreach ($_POST as $key => $value) + { + if (strpos($key, 'spec_') !== false) + { + $specs .= ',' . intval($value); + } + } + $specs = trim($specs, ','); + + /* 查询:如果商品有规格则取规格商品信息 配件除外 */ + if (!empty($specs)) + { + $_specs = explode(',', $specs); + + $product_info = get_products_info($goods_id, $_specs); + } + if (empty($product_info)) + { + $product_info = array('product_number' => '', 'product_id' => 0); + } + + //查询:商品存在规格 是货品 检查该货品库存 + if((!empty($specs)) && ($product_info['product_number'] == 0) && ($_CFG['use_storage'] == 1)) + { + show_message($_LANG['eg_error_number'], array($_LANG['back_up_page']), array($back_act), 'error'); + } + + /* 查询:查询规格名称和值,不考虑价格 */ + $attr_list = array(); + $sql = "SELECT a.attr_name, g.attr_value " . + "FROM " . $ecs->table('goods_attr') . " AS g, " . + $ecs->table('attribute') . " AS a " . + "WHERE g.attr_id = a.attr_id " . + "AND g.goods_attr_id " . db_create_in($specs); + $res = $db->query($sql); + while ($row = $db->fetchRow($res)) + { + $attr_list[] = $row['attr_name'] . ': ' . $row['attr_value']; + } + $goods_attr = join(chr(13) . chr(10), $attr_list); + + /* 更新:清空购物车中所有团购商品 */ + include_once(ROOT_PATH . 'includes/lib_order.php'); + clear_cart(CART_EXCHANGE_GOODS); + + /* 更新:加入购物车 */ + $number = 1; + $cart = array( + 'user_id' => $_SESSION['user_id'], + 'session_id' => SESS_ID, + 'goods_id' => $goods['goods_id'], + 'product_id' => $product_info['product_id'], + 'goods_sn' => addslashes($goods['goods_sn']), + 'goods_name' => addslashes($goods['goods_name']), + 'market_price' => $goods['market_price'], + 'goods_price' => 0,//$goods['exchange_integral'] + 'goods_number' => $number, + 'goods_attr' => addslashes($goods_attr), + 'goods_attr_id' => $specs, + 'is_real' => $goods['is_real'], + 'extension_code' => addslashes($goods['extension_code']), + 'parent_id' => 0, + 'rec_type' => CART_EXCHANGE_GOODS, + 'is_gift' => 0 + ); + $db->autoExecute($ecs->table('cart'), $cart, 'INSERT'); + + /* 记录购物流程类型:团购 */ + $_SESSION['flow_type'] = CART_EXCHANGE_GOODS; + $_SESSION['extension_code'] = 'exchange_goods'; + $_SESSION['extension_id'] = $goods_id; + + /* 进入收货人页面 */ + ecs_header("Location: ./flow.php?step=consignee\n"); + exit; +} + +/*------------------------------------------------------ */ +//-- PRIVATE FUNCTION +/*------------------------------------------------------ */ + +/** + * 获得分类的信息 + * + * @param integer $cat_id + * + * @return void + */ +function get_cat_info($cat_id) +{ + return $GLOBALS['db']->getRow('SELECT keywords, cat_desc, style, grade, filter_attr, parent_id FROM ' . $GLOBALS['ecs']->table('category') . + " WHERE cat_id = '$cat_id'"); +} + +/** + * 获得分类下的商品 + * + * @access public + * @param string $children + * @return array + */ +function exchange_get_goods($children, $min, $max, $ext, $size, $page, $sort, $order) +{ + $display = $GLOBALS['display']; + $where = "eg.is_exchange = 1 AND g.is_delete = 0 AND ". + "($children OR " . get_extension_goods($children) . ')'; + + if ($min > 0) + { + $where .= " AND eg.exchange_integral >= $min "; + } + + if ($max > 0) + { + $where .= " AND eg.exchange_integral <= $max "; + } + + /* 获得商品列表 */ + $sql = 'SELECT g.goods_id, g.goods_name, g.goods_name_style, eg.exchange_integral, ' . + 'g.goods_type, g.goods_brief, g.goods_thumb , g.goods_img, eg.is_hot ' . + 'FROM ' . $GLOBALS['ecs']->table('exchange_goods') . ' AS eg, ' .$GLOBALS['ecs']->table('goods') . ' AS g ' . + "WHERE eg.goods_id = g.goods_id AND $where $ext ORDER BY $sort $order"; + $res = $GLOBALS['db']->selectLimit($sql, $size, ($page - 1) * $size); + + $arr = array(); + while ($row = $GLOBALS['db']->fetchRow($res)) + { + /* 处理商品水印图片 */ + $watermark_img = ''; + +// if ($row['is_new'] != 0) +// { +// $watermark_img = "watermark_new_small"; +// } +// elseif ($row['is_best'] != 0) +// { +// $watermark_img = "watermark_best_small"; +// } +// else + if ($row['is_hot'] != 0) + { + $watermark_img = 'watermark_hot_small'; + } + + if ($watermark_img != '') + { + $arr[$row['goods_id']]['watermark_img'] = $watermark_img; + } + + $arr[$row['goods_id']]['goods_id'] = $row['goods_id']; + if($display == 'grid') + { + $arr[$row['goods_id']]['goods_name'] = $GLOBALS['_CFG']['goods_name_length'] > 0 ? sub_str($row['goods_name'], $GLOBALS['_CFG']['goods_name_length']) : $row['goods_name']; + } + else + { + $arr[$row['goods_id']]['goods_name'] = $row['goods_name']; + } + $arr[$row['goods_id']]['name'] = $row['goods_name']; + $arr[$row['goods_id']]['goods_brief'] = $row['goods_brief']; + $arr[$row['goods_id']]['goods_style_name'] = add_style($row['goods_name'],$row['goods_name_style']); + $arr[$row['goods_id']]['exchange_integral'] = $row['exchange_integral']; + $arr[$row['goods_id']]['type'] = $row['goods_type']; + $arr[$row['goods_id']]['goods_thumb'] = get_image_path($row['goods_id'], $row['goods_thumb'], true); + $arr[$row['goods_id']]['goods_img'] = get_image_path($row['goods_id'], $row['goods_img']); + $arr[$row['goods_id']]['url'] = build_uri('exchange_goods', array('gid'=>$row['goods_id']), $row['goods_name']); + } + + return $arr; +} + +/** + * 获得分类下的商品总数 + * + * @access public + * @param string $cat_id + * @return integer + */ +function get_exchange_goods_count($children, $min = 0, $max = 0, $ext='') +{ + $where = "eg.is_exchange = 1 AND g.is_delete = 0 AND ($children OR " . get_extension_goods($children) . ')'; + + + if ($min > 0) + { + $where .= " AND eg.exchange_integral >= $min "; + } + + if ($max > 0) + { + $where .= " AND eg.exchange_integral <= $max "; + } + + $sql = 'SELECT COUNT(*) FROM ' . $GLOBALS['ecs']->table('exchange_goods') . ' AS eg, ' . + $GLOBALS['ecs']->table('goods') . " AS g WHERE eg.goods_id = g.goods_id AND $where $ext"; + + /* 返回商品总数 */ + return $GLOBALS['db']->getOne($sql); +} + +/** + * 获得指定分类下的推荐商品 + * + * @access public + * @param string $type 推荐类型,可以是 best, new, hot, promote + * @param string $cats 分类的ID + * @param integer $min 商品积分下限 + * @param integer $max 商品积分上限 + * @param string $ext 商品扩展查询 + * @return array + */ +function get_exchange_recommend_goods($type = '', $cats = '', $min =0, $max = 0, $ext='') +{ + $price_where = ($min > 0) ? " AND g.shop_price >= $min " : ''; + $price_where .= ($max > 0) ? " AND g.shop_price <= $max " : ''; + + $sql = 'SELECT g.goods_id, g.goods_name, g.goods_name_style, eg.exchange_integral, ' . + 'g.goods_brief, g.goods_thumb, goods_img, b.brand_name ' . + 'FROM ' . $GLOBALS['ecs']->table('exchange_goods') . ' AS eg ' . + 'LEFT JOIN ' . $GLOBALS['ecs']->table('goods') . ' AS g ON g.goods_id = eg.goods_id ' . + 'LEFT JOIN ' . $GLOBALS['ecs']->table('brand') . ' AS b ON b.brand_id = g.brand_id ' . + 'WHERE eg.is_exchange = 1 AND g.is_delete = 0 ' . $price_where . $ext; + $num = 0; + $type2lib = array('best'=>'exchange_best', 'new'=>'exchange_new', 'hot'=>'exchange_hot'); + $num = get_library_number($type2lib[$type], 'exchange_list'); + + switch ($type) + { + case 'best': + $sql .= ' AND eg.is_best = 1'; + break; + case 'new': + $sql .= ' AND eg.is_new = 1'; + break; + case 'hot': + $sql .= ' AND eg.is_hot = 1'; + break; + } + + if (!empty($cats)) + { + $sql .= " AND (" . $cats . " OR " . get_extension_goods($cats) .")"; + } + $order_type = $GLOBALS['_CFG']['recommend_order']; + $sql .= ($order_type == 0) ? ' ORDER BY g.sort_order, g.last_update DESC' : ' ORDER BY RAND()'; + $res = $GLOBALS['db']->selectLimit($sql, $num); + + $idx = 0; + $goods = array(); + while ($row = $GLOBALS['db']->fetchRow($res)) + { + $goods[$idx]['id'] = $row['goods_id']; + $goods[$idx]['name'] = $row['goods_name']; + $goods[$idx]['brief'] = $row['goods_brief']; + $goods[$idx]['brand_name'] = $row['brand_name']; + $goods[$idx]['short_name'] = $GLOBALS['_CFG']['goods_name_length'] > 0 ? + sub_str($row['goods_name'], $GLOBALS['_CFG']['goods_name_length']) : $row['goods_name']; + $goods[$idx]['exchange_integral'] = $row['exchange_integral']; + $goods[$idx]['thumb'] = get_image_path($row['goods_id'], $row['goods_thumb'], true); + $goods[$idx]['goods_img'] = get_image_path($row['goods_id'], $row['goods_img']); + $goods[$idx]['url'] = build_uri('exchange_goods', array('gid' => $row['goods_id']), $row['goods_name']); + + $goods[$idx]['short_style_name'] = add_style($goods[$idx]['short_name'], $row['goods_name_style']); + $idx++; + } + + return $goods; +} + +/** + * 获得积分兑换商品的详细信息 + * + * @access public + * @param integer $goods_id + * @return void + */ +function get_exchange_goods_info($goods_id) +{ + $time = gmtime(); + $sql = 'SELECT g.*, c.measure_unit, b.brand_id, b.brand_name AS goods_brand, eg.exchange_integral, eg.is_exchange ' . + 'FROM ' . $GLOBALS['ecs']->table('goods') . ' AS g ' . + 'LEFT JOIN ' . $GLOBALS['ecs']->table('exchange_goods') . ' AS eg ON g.goods_id = eg.goods_id ' . + 'LEFT JOIN ' . $GLOBALS['ecs']->table('category') . ' AS c ON g.cat_id = c.cat_id ' . + 'LEFT JOIN ' . $GLOBALS['ecs']->table('brand') . ' AS b ON g.brand_id = b.brand_id ' . + "WHERE g.goods_id = '$goods_id' AND g.is_delete = 0 " . + 'GROUP BY g.goods_id'; + + $row = $GLOBALS['db']->getRow($sql); + + if ($row !== false) + { + /* 处理商品水印图片 */ + $watermark_img = ''; + + if ($row['is_new'] != 0) + { + $watermark_img = "watermark_new"; + } + elseif ($row['is_best'] != 0) + { + $watermark_img = "watermark_best"; + } + elseif ($row['is_hot'] != 0) + { + $watermark_img = 'watermark_hot'; + } + + if ($watermark_img != '') + { + $row['watermark_img'] = $watermark_img; + } + + /* 修正重量显示 */ + $row['goods_weight'] = (intval($row['goods_weight']) > 0) ? + $row['goods_weight'] . $GLOBALS['_LANG']['kilogram'] : + ($row['goods_weight'] * 1000) . $GLOBALS['_LANG']['gram']; + + /* 修正上架时间显示 */ + $row['add_time'] = local_date($GLOBALS['_CFG']['date_format'], $row['add_time']); + + /* 修正商品图片 */ + $row['goods_img'] = get_image_path($goods_id, $row['goods_img']); + $row['goods_thumb'] = get_image_path($goods_id, $row['goods_thumb'], true); + + return $row; + } + else + { + return false; + } +} + + +?> diff --git a/favicon.ico b/favicon.ico new file mode 100644 index 0000000..a0d2fff Binary files /dev/null and b/favicon.ico differ diff --git a/feed.php b/feed.php new file mode 100644 index 0000000..27640ef --- /dev/null +++ b/feed.php @@ -0,0 +1,264 @@ +url(); + +$rss = new RSSBuilder(EC_CHARSET, $uri, htmlspecialchars($_CFG['shop_name']), htmlspecialchars($_CFG['shop_desc']), $uri . 'animated_favicon.gif'); +$rss->addDCdata('', 'http://www.ecshop.com', date('r')); + +if (isset($_REQUEST['type'])) +{ + if($_REQUEST['type'] == 'group_buy') + { + $now = gmtime(); + $sql = 'SELECT act_id, act_name, act_desc, start_time ' . + "FROM " . $GLOBALS['ecs']->table('goods_activity') . + "WHERE act_type = '" . GAT_GROUP_BUY . "' " . + "AND start_time <= '$now' AND is_finished < 3 ORDER BY start_time DESC"; + $res = $db->query($sql); + + if ($res !== false) + { + while ($row = $db->fetchRow($res)) + { + $item_url = build_uri('group_buy', array('gbid' => $row['act_id']), $row['act_name']); + $separator = (strpos($item_url, '?') === false)? '?' : '&'; + $about = $uri . $item_url; + $title = htmlspecialchars($row['act_name']); + $link = $uri . $item_url . $separator . 'from=rss'; + $desc = htmlspecialchars($row['act_desc']); + $subject = $_LANG['group_buy']; + $date = local_date('r', $row['start_time']); + + $rss->addItem($about, $title, $link, $desc, $subject, $date); + } + + $rss->outputRSS($ver); + } + } + elseif($_REQUEST['type'] == 'snatch') + { + $now = gmtime(); + $sql = 'SELECT act_id, act_name, act_desc, start_time ' . + "FROM " . $GLOBALS['ecs']->table('goods_activity') . + "WHERE act_type = '" . GAT_SNATCH . "' " . + "AND start_time <= '$now' AND is_finished < 3 ORDER BY start_time DESC"; + $res = $db->query($sql); + + if ($res !== false) + { + while ($row = $db->fetchRow($res)) + { + $item_url = build_uri('snatch', array('sid' => $row['act_id']), $row['act_name']); + $separator = (strpos($item_url, '?') === false)? '?' : '&'; + $about = $uri . $item_url; + $title = htmlspecialchars($row['act_name']); + $link = $uri . $item_url . $separator . 'from=rss'; + $desc = htmlspecialchars($row['act_desc']); + $subject = $_LANG['snatch']; + $date = local_date('r', $row['start_time']); + + $rss->addItem($about, $title, $link, $desc, $subject, $date); + } + + $rss->outputRSS($ver); + } + } + elseif($_REQUEST['type'] == 'auction') + { + $now = gmtime(); + $sql = 'SELECT act_id, act_name, act_desc, start_time ' . + "FROM " . $GLOBALS['ecs']->table('goods_activity') . + "WHERE act_type = '" . GAT_AUCTION . "' " . + "AND start_time <= '$now' AND is_finished < 3 ORDER BY start_time DESC"; + $res = $db->query($sql); + + if ($res !== false) + { + while ($row = $db->fetchRow($res)) + { + $item_url = build_uri('auction', array('auid' => $row['act_id']), $row['act_name']); + $separator = (strpos($item_url, '?') === false)? '?' : '&'; + $about = $uri . $item_url; + $title = htmlspecialchars($row['act_name']); + $link = $uri . $item_url . $separator . 'from=rss'; + $desc = htmlspecialchars($row['act_desc']); + $subject = $_LANG['auction']; + $date = local_date('r', $row['start_time']); + + $rss->addItem($about, $title, $link, $desc, $subject, $date); + } + + $rss->outputRSS($ver); + } + } + elseif($_REQUEST['type'] == 'exchange') + { + $sql = 'SELECT g.goods_id, g.goods_name, g.goods_brief, g.last_update ' . + "FROM " . $GLOBALS['ecs']->table('exchange_goods') . " AS eg, " . + $GLOBALS['ecs']->table('goods') . " AS g " . + "WHERE eg.goods_id = g.goods_id"; + $res = $db->query($sql); + + if ($res !== false) + { + while ($row = $db->fetchRow($res)) + { + $item_url = build_uri('exchange_goods', array('gid' => $row['goods_id']), $row['goods_name']); + $separator = (strpos($item_url, '?') === false)? '?' : '&'; + $about = $uri . $item_url; + $title = htmlspecialchars($row['goods_name']); + $link = $uri . $item_url . $separator . 'from=rss'; + $desc = htmlspecialchars($row['goods_brief']); + $subject = $_LANG['exchange']; + $date = local_date('r', $row['last_update']); + + $rss->addItem($about, $title, $link, $desc, $subject, $date); + } + + $rss->outputRSS($ver); + } + } + elseif($_REQUEST['type'] == 'activity') + { + $now = gmtime(); + $sql = 'SELECT act_id, act_name, start_time ' . + "FROM " . $GLOBALS['ecs']->table('favourable_activity') . + " WHERE start_time <= '$now' AND end_time >= '$now'"; + $res = $db->query($sql); + + if ($res !== false) + { + while ($row = $db->fetchRow($res)) + { + $item_url = 'activity.php'; + $separator = (strpos($item_url, '?') === false)? '?' : '&'; + $about = $uri . $item_url; + $title = htmlspecialchars($row['act_name']); + $link = $uri . $item_url . $separator . 'from=rss'; + $desc = ''; + $subject = $_LANG['favourable']; + $date = local_date('r', $row['start_time']); + + $rss->addItem($about, $title, $link, $desc, $subject, $date); + } + + $rss->outputRSS($ver); + } + } + elseif($_REQUEST['type'] == 'package') + { + $now = gmtime(); + $sql = 'SELECT act_id, act_name, act_desc, start_time ' . + "FROM " . $GLOBALS['ecs']->table('goods_activity') . + "WHERE act_type = '" . GAT_PACKAGE . "' " . + "AND start_time <= '$now' AND is_finished < 3 ORDER BY start_time DESC"; + $res = $db->query($sql); + + if ($res !== false) + { + while ($row = $db->fetchRow($res)) + { + $item_url = 'package.php'; + $separator = (strpos($item_url, '?') === false)? '?' : '&'; + $about = $uri . $item_url; + $title = htmlspecialchars($row['act_name']); + $link = $uri . $item_url . $separator . 'from=rss'; + $desc = htmlspecialchars($row['act_desc']); + $subject = $_LANG['remark_package']; + $date = local_date('r', $row['start_time']); + + $rss->addItem($about, $title, $link, $desc, $subject, $date); + } + + $rss->outputRSS($ver); + } + } + elseif(substr($_REQUEST['type'], 0, 11) == 'article_cat') + { + $sql = 'SELECT article_id, title, author, add_time' . + ' FROM ' .$GLOBALS['ecs']->table('article') . + ' WHERE is_open = 1 AND ' . get_article_children(substr($_REQUEST['type'], 11)) . + ' ORDER BY add_time DESC LIMIT ' . $_CFG['article_page_size']; + $res = $db->query($sql); + + if ($res !== false) + { + while ($row = $db->fetchRow($res)) + { + $item_url = build_uri('article', array('aid' => $row['article_id']), $row['title']); + $separator = (strpos($item_url, '?') === false)? '?' : '&'; + $about = $uri . $item_url; + $title = htmlspecialchars($row['title']); + $link = $uri . $item_url . $separator . 'from=rss'; + $desc = ''; + $subject = htmlspecialchars($row['author']); + $date = local_date('r', $row['add_time']); + + $rss->addItem($about, $title, $link, $desc, $subject, $date); + } + + $rss->outputRSS($ver); + } + } +} +else +{ + $in_cat = $cat > 0 ? ' AND ' . get_children($cat) : ''; + + $sql = 'SELECT c.cat_name, g.goods_id, g.goods_name, g.goods_brief, g.last_update ' . + 'FROM ' . $ecs->table('category') . ' AS c, ' . $ecs->table('goods') . ' AS g ' . + 'WHERE c.cat_id = g.cat_id AND g.is_delete = 0 AND g.is_alone_sale = 1 ' . $brd . $cat . + 'ORDER BY g.last_update DESC'; + $res = $db->query($sql); + + if ($res !== false) + { + while ($row = $db->fetchRow($res)) + { + $item_url = build_uri('goods', array('gid' => $row['goods_id']), $row['goods_name']); + $separator = (strpos($item_url, '?') === false)? '?' : '&'; + $about = $uri . $item_url; + $title = htmlspecialchars($row['goods_name']); + $link = $uri . $item_url . $separator . 'from=rss'; + $desc = htmlspecialchars($row['goods_brief']); + $subject = htmlspecialchars($row['cat_name']); + $date = local_date('r', $row['last_update']); + + $rss->addItem($about, $title, $link, $desc, $subject, $date); + } + + $rss->outputRSS($ver); + } +} + +?> \ No newline at end of file diff --git a/flow.php b/flow.php new file mode 100644 index 0000000..cb66b43 --- /dev/null +++ b/flow.php @@ -0,0 +1,2743 @@ +assign('page_title', $position['title']); // 页面标题 +$smarty->assign('ur_here', $position['ur_here']); // 当前位置 + +$smarty->assign('categories', get_categories_tree()); // 分类树 +$smarty->assign('helps', get_shop_help()); // 网店帮助 +$smarty->assign('lang', $_LANG); +$smarty->assign('show_marketprice', $_CFG['show_marketprice']); +$smarty->assign('data_dir', DATA_DIR); // 数据目录 + +/*------------------------------------------------------ */ +//-- 添加商品到购物车 +/*------------------------------------------------------ */ +if ($_REQUEST['step'] == 'add_to_cart') +{ + include_once('includes/cls_json.php'); + $_POST['goods'] = json_str_iconv($_POST['goods']); + + if (!empty($_REQUEST['goods_id']) && empty($_POST['goods'])) + { + if (!is_numeric($_REQUEST['goods_id']) || intval($_REQUEST['goods_id']) <= 0) + { + ecs_header("Location:./\n"); + } + $goods_id = intval($_REQUEST['goods_id']); + exit; + } + + $result = array('error' => 0, 'message' => '', 'content' => '', 'goods_id' => ''); + $json = new JSON; + + if (empty($_POST['goods'])) + { + $result['error'] = 1; + die($json->encode($result)); + } + + $goods = $json->decode($_POST['goods']); + + /* 检查:如果商品有规格,而post的数据没有规格,把商品的规格属性通过JSON传到前台 */ + if (empty($goods->spec) AND empty($goods->quick)) + { + $sql = "SELECT a.attr_id, a.attr_name, a.attr_type, ". + "g.goods_attr_id, g.attr_value, g.attr_price " . + 'FROM ' . $GLOBALS['ecs']->table('goods_attr') . ' AS g ' . + 'LEFT JOIN ' . $GLOBALS['ecs']->table('attribute') . ' AS a ON a.attr_id = g.attr_id ' . + "WHERE a.attr_type != 0 AND g.goods_id = '" . $goods->goods_id . "' " . + 'ORDER BY a.sort_order, g.attr_price, g.goods_attr_id'; + + $res = $GLOBALS['db']->getAll($sql); + + if (!empty($res)) + { + $spe_arr = array(); + foreach ($res AS $row) + { + $spe_arr[$row['attr_id']]['attr_type'] = $row['attr_type']; + $spe_arr[$row['attr_id']]['name'] = $row['attr_name']; + $spe_arr[$row['attr_id']]['attr_id'] = $row['attr_id']; + $spe_arr[$row['attr_id']]['values'][] = array( + 'label' => $row['attr_value'], + 'price' => $row['attr_price'], + 'format_price' => price_format($row['attr_price'], false), + 'id' => $row['goods_attr_id']); + } + $i = 0; + $spe_array = array(); + foreach ($spe_arr AS $row) + { + $spe_array[]=$row; + } + $result['error'] = ERR_NEED_SELECT_ATTR; + $result['goods_id'] = $goods->goods_id; + $result['parent'] = $goods->parent; + $result['message'] = $spe_array; + + die($json->encode($result)); + } + } + + /* 更新:如果是一步购物,先清空购物车 */ + if ($_CFG['one_step_buy'] == '1') + { + clear_cart(); + } + + /* 检查:商品数量是否合法 */ + if (!is_numeric($goods->number) || intval($goods->number) <= 0) + { + $result['error'] = 1; + $result['message'] = $_LANG['invalid_number']; + } + /* 更新:购物车 */ + else + { + // 更新:添加到购物车 + if (addto_cart($goods->goods_id, $goods->number, $goods->spec, $goods->parent)) + { + if ($_CFG['cart_confirm'] > 2) + { + $result['message'] = ''; + } + else + { + $result['message'] = $_CFG['cart_confirm'] == 1 ? $_LANG['addto_cart_success_1'] : $_LANG['addto_cart_success_2']; + } + + $result['content'] = insert_cart_info(); + $result['one_step_buy'] = $_CFG['one_step_buy']; + } + else + { + $result['message'] = $err->last_message(); + $result['error'] = $err->error_no; + $result['goods_id'] = stripslashes($goods->goods_id); + if (is_array($goods->spec)) + { + $result['product_spec'] = implode(',', $goods->spec); + } + else + { + $result['product_spec'] = $goods->spec; + } + } + } + + $result['confirm_type'] = !empty($_CFG['cart_confirm']) ? $_CFG['cart_confirm'] : 2; + die($json->encode($result)); +} +elseif ($_REQUEST['step'] == 'link_buy') +{ + $goods_id = intval($_GET['goods_id']); + + if (!cart_goods_exists($goods_id,array())) + { + addto_cart($goods_id); + } + ecs_header("Location:./flow.php\n"); + exit; +} +elseif ($_REQUEST['step'] == 'login') +{ + include_once('languages/'. $_CFG['lang']. '/user.php'); + + /* + * 用户登录注册 + */ + if ($_SERVER['REQUEST_METHOD'] == 'GET') + { + $smarty->assign('anonymous_buy', $_CFG['anonymous_buy']); + + /* 检查是否有赠品,如果有提示登录后重新选择赠品 */ + $sql = "SELECT COUNT(*) FROM " . $ecs->table('cart') . + " WHERE session_id = '" . SESS_ID . "' AND is_gift > 0"; + if ($db->getOne($sql) > 0) + { + $smarty->assign('need_rechoose_gift', 1); + } + + /* 检查是否需要注册码 */ + $captcha = intval($_CFG['captcha']); + if (($captcha & CAPTCHA_LOGIN) && (!($captcha & CAPTCHA_LOGIN_FAIL) || (($captcha & CAPTCHA_LOGIN_FAIL) && $_SESSION['login_fail'] > 2)) && gd_version() > 0) + { + $smarty->assign('enabled_login_captcha', 1); + $smarty->assign('rand', mt_rand()); + } + if ($captcha & CAPTCHA_REGISTER) + { + $smarty->assign('enabled_register_captcha', 1); + $smarty->assign('rand', mt_rand()); + } + } + else + { + include_once('includes/lib_passport.php'); + if (!empty($_POST['act']) && $_POST['act'] == 'signin') + { + $captcha = intval($_CFG['captcha']); + if (($captcha & CAPTCHA_LOGIN) && (!($captcha & CAPTCHA_LOGIN_FAIL) || (($captcha & CAPTCHA_LOGIN_FAIL) && $_SESSION['login_fail'] > 2)) && gd_version() > 0) + { + if (empty($_POST['captcha'])) + { + show_message($_LANG['invalid_captcha']); + } + + /* 检查验证码 */ + include_once('includes/cls_captcha.php'); + + $validator = new captcha(); + $validator->session_word = 'captcha_login'; + if (!$validator->check_word($_POST['captcha'])) + { + show_message($_LANG['invalid_captcha']); + } + } + + if ($user->login($_POST['username'], $_POST['password'],isset($_POST['remember']))) + { + update_user_info(); //更新用户信息 + recalculate_price(); // 重新计算购物车中的商品价格 + + /* 检查购物车中是否有商品 没有商品则跳转到首页 */ + $sql = "SELECT COUNT(*) FROM " . $ecs->table('cart') . " WHERE session_id = '" . SESS_ID . "' "; + if ($db->getOne($sql) > 0) + { + ecs_header("Location: flow.php?step=checkout\n"); + } + else + { + ecs_header("Location:index.php\n"); + } + + exit; + } + else + { + $_SESSION['login_fail']++; + show_message($_LANG['signin_failed'], '', 'flow.php?step=login'); + } + } + elseif (!empty($_POST['act']) && $_POST['act'] == 'signup') + { + if ((intval($_CFG['captcha']) & CAPTCHA_REGISTER) && gd_version() > 0) + { + if (empty($_POST['captcha'])) + { + show_message($_LANG['invalid_captcha']); + } + + /* 检查验证码 */ + include_once('includes/cls_captcha.php'); + + $validator = new captcha(); + if (!$validator->check_word($_POST['captcha'])) + { + show_message($_LANG['invalid_captcha']); + } + } + + if (register(trim($_POST['username']), trim($_POST['password']), trim($_POST['email']))) + { + /* 用户注册成功 */ + ecs_header("Location: flow.php?step=consignee\n"); + exit; + } + else + { + $err->show(); + } + } + else + { + // TODO: 非法访问的处理 + } + } +} +elseif ($_REQUEST['step'] == 'consignee') +{ + /*------------------------------------------------------ */ + //-- 收货人信息 + /*------------------------------------------------------ */ + include_once('includes/lib_transaction.php'); + + if ($_SERVER['REQUEST_METHOD'] == 'GET') + { + /* 取得购物类型 */ + $flow_type = isset($_SESSION['flow_type']) ? intval($_SESSION['flow_type']) : CART_GENERAL_GOODS; + + /* + * 收货人信息填写界面 + */ + + if (isset($_REQUEST['direct_shopping'])) + { + $_SESSION['direct_shopping'] = 1; + } + + /* 取得国家列表、商店所在国家、商店所在国家的省列表 */ + $smarty->assign('country_list', get_regions()); + $smarty->assign('shop_country', $_CFG['shop_country']); + $smarty->assign('shop_province_list', get_regions(1, $_CFG['shop_country'])); + + /* 获得用户所有的收货人信息 */ + if ($_SESSION['user_id'] > 0) + { + $consignee_list = get_consignee_list($_SESSION['user_id']); + + if (count($consignee_list) < 5) + { + /* 如果用户收货人信息的总数小于 5 则增加一个新的收货人信息 */ + $consignee_list[] = array('country' => $_CFG['shop_country'], 'email' => isset($_SESSION['email']) ? $_SESSION['email'] : ''); + } + } + else + { + if (isset($_SESSION['flow_consignee'])){ + $consignee_list = array($_SESSION['flow_consignee']); + } + else + { + $consignee_list[] = array('country' => $_CFG['shop_country']); + } + } + $smarty->assign('name_of_region', array($_CFG['name_of_region_1'], $_CFG['name_of_region_2'], $_CFG['name_of_region_3'], $_CFG['name_of_region_4'])); + $smarty->assign('consignee_list', $consignee_list); + + /* 取得每个收货地址的省市区列表 */ + $province_list = array(); + $city_list = array(); + $district_list = array(); + foreach ($consignee_list as $region_id => $consignee) + { + $consignee['country'] = isset($consignee['country']) ? intval($consignee['country']) : 0; + $consignee['province'] = isset($consignee['province']) ? intval($consignee['province']) : 0; + $consignee['city'] = isset($consignee['city']) ? intval($consignee['city']) : 0; + + $province_list[$region_id] = get_regions(1, $consignee['country']); + $city_list[$region_id] = get_regions(2, $consignee['province']); + $district_list[$region_id] = get_regions(3, $consignee['city']); + } + $smarty->assign('province_list', $province_list); + $smarty->assign('city_list', $city_list); + $smarty->assign('district_list', $district_list); + + /* 返回收货人页面代码 */ + $smarty->assign('real_goods_count', exist_real_goods(0, $flow_type) ? 1 : 0); + } + else + { + /* + * 保存收货人信息 + */ + $consignee = array( + 'address_id' => empty($_POST['address_id']) ? 0 : intval($_POST['address_id']), + 'consignee' => empty($_POST['consignee']) ? '' : trim($_POST['consignee']), + 'country' => empty($_POST['country']) ? '' : $_POST['country'], + 'province' => empty($_POST['province']) ? '' : $_POST['province'], + 'city' => empty($_POST['city']) ? '' : $_POST['city'], + 'district' => empty($_POST['district']) ? '' : $_POST['district'], + 'email' => empty($_POST['email']) ? '' : $_POST['email'], + 'address' => empty($_POST['address']) ? '' : $_POST['address'], + 'zipcode' => empty($_POST['zipcode']) ? '' : make_semiangle(trim($_POST['zipcode'])), + 'tel' => empty($_POST['tel']) ? '' : make_semiangle(trim($_POST['tel'])), + 'mobile' => empty($_POST['mobile']) ? '' : make_semiangle(trim($_POST['mobile'])), + 'sign_building' => empty($_POST['sign_building']) ? '' : $_POST['sign_building'], + 'best_time' => empty($_POST['best_time']) ? '' : $_POST['best_time'], + ); + + if ($_SESSION['user_id'] > 0) + { + include_once(ROOT_PATH . 'includes/lib_transaction.php'); + + /* 如果用户已经登录,则保存收货人信息 */ + $consignee['user_id'] = $_SESSION['user_id']; + + save_consignee($consignee, true); + } + + /* 保存到session */ + $_SESSION['flow_consignee'] = stripslashes_deep($consignee); + + ecs_header("Location: flow.php?step=checkout\n"); + exit; + } +} +elseif ($_REQUEST['step'] == 'drop_consignee') +{ + /*------------------------------------------------------ */ + //-- 删除收货人信息 + /*------------------------------------------------------ */ + include_once('includes/lib_transaction.php'); + + $consignee_id = intval($_GET['id']); + + if (drop_consignee($consignee_id)) + { + ecs_header("Location: flow.php?step=consignee\n"); + exit; + } + else + { + show_message($_LANG['not_fount_consignee']); + } +} +elseif ($_REQUEST['step'] == 'checkout') +{ + /*------------------------------------------------------ */ + //-- 订单确认 + /*------------------------------------------------------ */ + + /* 取得购物类型 */ + $flow_type = isset($_SESSION['flow_type']) ? intval($_SESSION['flow_type']) : CART_GENERAL_GOODS; + + /* 团购标志 */ + if ($flow_type == CART_GROUP_BUY_GOODS) + { + $smarty->assign('is_group_buy', 1); + } + /* 积分兑换商品 */ + elseif ($flow_type == CART_EXCHANGE_GOODS) + { + $smarty->assign('is_exchange_goods', 1); + } + else + { + //正常购物流程 清空其他购物流程情况 + $_SESSION['flow_order']['extension_code'] = ''; + } + + /* 检查购物车中是否有商品 */ + $sql = "SELECT COUNT(*) FROM " . $ecs->table('cart') . + " WHERE session_id = '" . SESS_ID . "' " . + "AND parent_id = 0 AND is_gift = 0 AND rec_type = '$flow_type'"; + + if ($db->getOne($sql) == 0) + { + show_message($_LANG['no_goods_in_cart'], '', '', 'warning'); + } + + /* + * 检查用户是否已经登录 + * 如果用户已经登录了则检查是否有默认的收货地址 + * 如果没有登录则跳转到登录和注册页面 + */ + if (empty($_SESSION['direct_shopping']) && $_SESSION['user_id'] == 0) + { + /* 用户没有登录且没有选定匿名购物,转向到登录页面 */ + ecs_header("Location: flow.php?step=login\n"); + exit; + } + + $consignee = get_consignee($_SESSION['user_id']); + + /* 检查收货人信息是否完整 */ + if (!check_consignee_info($consignee, $flow_type)) + { + /* 如果不完整则转向到收货人信息填写界面 */ + ecs_header("Location: flow.php?step=consignee\n"); + exit; + } + + $_SESSION['flow_consignee'] = $consignee; + $smarty->assign('consignee', $consignee); + + /* 对商品信息赋值 */ + $cart_goods = cart_goods($flow_type); // 取得商品列表,计算合计 + $smarty->assign('goods_list', $cart_goods); + + /* 对是否允许修改购物车赋值 */ + if ($flow_type != CART_GENERAL_GOODS || $_CFG['one_step_buy'] == '1') + { + $smarty->assign('allow_edit_cart', 0); + } + else + { + $smarty->assign('allow_edit_cart', 1); + } + + /* + * 取得购物流程设置 + */ + $smarty->assign('config', $_CFG); + /* + * 取得订单信息 + */ + $order = flow_order_info(); + $smarty->assign('order', $order); + + /* 计算折扣 */ + if ($flow_type != CART_EXCHANGE_GOODS && $flow_type != CART_GROUP_BUY_GOODS) + { + $discount = compute_discount(); + $smarty->assign('discount', $discount['discount']); + $favour_name = empty($discount['name']) ? '' : join(',', $discount['name']); + $smarty->assign('your_discount', sprintf($_LANG['your_discount'], $favour_name, price_format($discount['discount']))); + } + + /* + * 计算订单的费用 + */ + $total = order_fee($order, $cart_goods, $consignee); + + $smarty->assign('total', $total); + $smarty->assign('shopping_money', sprintf($_LANG['shopping_money'], $total['formated_goods_price'])); + $smarty->assign('market_price_desc', sprintf($_LANG['than_market_price'], $total['formated_market_price'], $total['formated_saving'], $total['save_rate'])); + + /* 取得配送列表 */ + $region = array($consignee['country'], $consignee['province'], $consignee['city'], $consignee['district']); + $shipping_list = available_shipping_list($region); + $cart_weight_price = cart_weight_price($flow_type); + $insure_disabled = true; + $cod_disabled = true; + + // 查看购物车中是否全为免运费商品,若是则把运费赋为零 + $sql = 'SELECT count(*) FROM ' . $ecs->table('cart') . " WHERE `session_id` = '" . SESS_ID. "' AND `extension_code` != 'package_buy' AND `is_shipping` = 0"; + $shipping_count = $db->getOne($sql); + + foreach ($shipping_list AS $key => $val) + { + $shipping_cfg = unserialize_config($val['configure']); + $shipping_fee = ($shipping_count == 0 AND $cart_weight_price['free_shipping'] == 1) ? 0 : shipping_fee($val['shipping_code'], unserialize($val['configure']), + $cart_weight_price['weight'], $cart_weight_price['amount'], $cart_weight_price['number']); + + $shipping_list[$key]['format_shipping_fee'] = price_format($shipping_fee, false); + $shipping_list[$key]['shipping_fee'] = $shipping_fee; + $shipping_list[$key]['free_money'] = price_format($shipping_cfg['free_money'], false); + $shipping_list[$key]['insure_formated'] = strpos($val['insure'], '%') === false ? + price_format($val['insure'], false) : $val['insure']; + + /* 当前的配送方式是否支持保价 */ + if ($val['shipping_id'] == $order['shipping_id']) + { + $insure_disabled = ($val['insure'] == 0); + $cod_disabled = ($val['support_cod'] == 0); + } + } + + $smarty->assign('shipping_list', $shipping_list); + $smarty->assign('insure_disabled', $insure_disabled); + $smarty->assign('cod_disabled', $cod_disabled); + + /* 取得支付列表 */ + if ($order['shipping_id'] == 0) + { + $cod = true; + $cod_fee = 0; + } + else + { + $shipping = shipping_info($order['shipping_id']); + $cod = $shipping['support_cod']; + + if ($cod) + { + /* 如果是团购,且保证金大于0,不能使用货到付款 */ + if ($flow_type == CART_GROUP_BUY_GOODS) + { + $group_buy_id = $_SESSION['extension_id']; + if ($group_buy_id <= 0) + { + show_message('error group_buy_id'); + } + $group_buy = group_buy_info($group_buy_id); + if (empty($group_buy)) + { + show_message('group buy not exists: ' . $group_buy_id); + } + + if ($group_buy['deposit'] > 0) + { + $cod = false; + $cod_fee = 0; + + /* 赋值保证金 */ + $smarty->assign('gb_deposit', $group_buy['deposit']); + } + } + + if ($cod) + { + $shipping_area_info = shipping_area_info($order['shipping_id'], $region); + $cod_fee = $shipping_area_info['pay_fee']; + } + } + else + { + $cod_fee = 0; + } + } + + // 给货到付款的手续费加,以便改变配送的时候动态显示 + $payment_list = available_payment_list(1, $cod_fee); + if(isset($payment_list)) + { + foreach ($payment_list as $key => $payment) + { + if ($payment['is_cod'] == '1') + { + $payment_list[$key]['format_pay_fee'] = '' . $payment['format_pay_fee'] . ''; + } + /* 如果有易宝神州行支付 如果订单金额大于300 则不显示 */ + if ($payment['pay_code'] == 'yeepayszx' && $total['amount'] > 300) + { + unset($payment_list[$key]); + } + /* 如果有余额支付 */ + if ($payment['pay_code'] == 'balance') + { + /* 如果未登录,不显示 */ + if ($_SESSION['user_id'] == 0) + { + unset($payment_list[$key]); + } + else + { + if ($_SESSION['flow_order']['pay_id'] == $payment['pay_id']) + { + $smarty->assign('disable_surplus', 1); + } + } + } + } + } + $smarty->assign('payment_list', $payment_list); + + /* 取得包装与贺卡 */ + if ($total['real_goods_count'] > 0) + { + /* 只有有实体商品,才要判断包装和贺卡 */ + if (!isset($_CFG['use_package']) || $_CFG['use_package'] == '1') + { + /* 如果使用包装,取得包装列表及用户选择的包装 */ + $smarty->assign('pack_list', pack_list()); + } + + /* 如果使用贺卡,取得贺卡列表及用户选择的贺卡 */ + if (!isset($_CFG['use_card']) || $_CFG['use_card'] == '1') + { + $smarty->assign('card_list', card_list()); + } + } + + $user_info = user_info($_SESSION['user_id']); + + /* 如果使用余额,取得用户余额 */ + if ((!isset($_CFG['use_surplus']) || $_CFG['use_surplus'] == '1') + && $_SESSION['user_id'] > 0 + && $user_info['user_money'] > 0) + { + // 能使用余额 + $smarty->assign('allow_use_surplus', 1); + $smarty->assign('your_surplus', $user_info['user_money']); + } + + /* 如果使用积分,取得用户可用积分及本订单最多可以使用的积分 */ + if ((!isset($_CFG['use_integral']) || $_CFG['use_integral'] == '1') + && $_SESSION['user_id'] > 0 + && $user_info['pay_points'] > 0 + && ($flow_type != CART_GROUP_BUY_GOODS && $flow_type != CART_EXCHANGE_GOODS)) + { + // 能使用积分 + $smarty->assign('allow_use_integral', 1); + $smarty->assign('order_max_integral', flow_available_points()); // 可用积分 + $smarty->assign('your_integral', $user_info['pay_points']); // 用户积分 + } + + /* 如果使用红包,取得用户可以使用的红包及用户选择的红包 */ + if ((!isset($_CFG['use_bonus']) || $_CFG['use_bonus'] == '1') + && ($flow_type != CART_GROUP_BUY_GOODS && $flow_type != CART_EXCHANGE_GOODS)) + { + // 取得用户可用红包 + $user_bonus = user_bonus($_SESSION['user_id'], $total['goods_price']); + if (!empty($user_bonus)) + { + foreach ($user_bonus AS $key => $val) + { + $user_bonus[$key]['bonus_money_formated'] = price_format($val['type_money'], false); + } + $smarty->assign('bonus_list', $user_bonus); + } + + // 能使用红包 + $smarty->assign('allow_use_bonus', 1); + } + + /* 如果使用缺货处理,取得缺货处理列表 */ + if (!isset($_CFG['use_how_oos']) || $_CFG['use_how_oos'] == '1') + { + if (is_array($GLOBALS['_LANG']['oos']) && !empty($GLOBALS['_LANG']['oos'])) + { + $smarty->assign('how_oos_list', $GLOBALS['_LANG']['oos']); + } + } + + /* 如果能开发票,取得发票内容列表 */ + if ((!isset($_CFG['can_invoice']) || $_CFG['can_invoice'] == '1') + && isset($_CFG['invoice_content']) + && trim($_CFG['invoice_content']) != '' && $flow_type != CART_EXCHANGE_GOODS) + { + $inv_content_list = explode("\n", str_replace("\r", '', $_CFG['invoice_content'])); + $smarty->assign('inv_content_list', $inv_content_list); + + $inv_type_list = array(); + foreach ($_CFG['invoice_type']['type'] as $key => $type) + { + if (!empty($type)) + { + $inv_type_list[$type] = $type . ' [' . floatval($_CFG['invoice_type']['rate'][$key]) . '%]'; + } + } + $smarty->assign('inv_type_list', $inv_type_list); + } + + /* 保存 session */ + $_SESSION['flow_order'] = $order; +} +elseif ($_REQUEST['step'] == 'select_shipping') +{ + /*------------------------------------------------------ */ + //-- 改变配送方式 + /*------------------------------------------------------ */ + include_once('includes/cls_json.php'); + $json = new JSON; + $result = array('error' => '', 'content' => '', 'need_insure' => 0); + + /* 取得购物类型 */ + $flow_type = isset($_SESSION['flow_type']) ? intval($_SESSION['flow_type']) : CART_GENERAL_GOODS; + + /* 获得收货人信息 */ + $consignee = get_consignee($_SESSION['user_id']); + + /* 对商品信息赋值 */ + $cart_goods = cart_goods($flow_type); // 取得商品列表,计算合计 + + if (empty($cart_goods) || !check_consignee_info($consignee, $flow_type)) + { + $result['error'] = $_LANG['no_goods_in_cart']; + } + else + { + /* 取得购物流程设置 */ + $smarty->assign('config', $_CFG); + + /* 取得订单信息 */ + $order = flow_order_info(); + + $order['shipping_id'] = intval($_REQUEST['shipping']); + $regions = array($consignee['country'], $consignee['province'], $consignee['city'], $consignee['district']); + $shipping_info = shipping_area_info($order['shipping_id'], $regions); + + /* 计算订单的费用 */ + $total = order_fee($order, $cart_goods, $consignee); + $smarty->assign('total', $total); + + /* 取得可以得到的积分和红包 */ + $smarty->assign('total_integral', cart_amount(false, $flow_type) - $total['bonus'] - $total['integral_money']); + $smarty->assign('total_bonus', price_format(get_total_bonus(), false)); + + /* 团购标志 */ + if ($flow_type == CART_GROUP_BUY_GOODS) + { + $smarty->assign('is_group_buy', 1); + } + + $result['cod_fee'] = $shipping_info['pay_fee']; + if (strpos($result['cod_fee'], '%') === false) + { + $result['cod_fee'] = price_format($result['cod_fee'], false); + } + $result['need_insure'] = ($shipping_info['insure'] > 0 && !empty($order['need_insure'])) ? 1 : 0; + $result['content'] = $smarty->fetch('library/order_total.lbi'); + } + + echo $json->encode($result); + exit; +} +elseif ($_REQUEST['step'] == 'select_insure') +{ + /*------------------------------------------------------ */ + //-- 选定/取消配送的保价 + /*------------------------------------------------------ */ + + include_once('includes/cls_json.php'); + $json = new JSON; + $result = array('error' => '', 'content' => '', 'need_insure' => 0); + + /* 取得购物类型 */ + $flow_type = isset($_SESSION['flow_type']) ? intval($_SESSION['flow_type']) : CART_GENERAL_GOODS; + + /* 获得收货人信息 */ + $consignee = get_consignee($_SESSION['user_id']); + + /* 对商品信息赋值 */ + $cart_goods = cart_goods($flow_type); // 取得商品列表,计算合计 + + if (empty($cart_goods) || !check_consignee_info($consignee, $flow_type)) + { + $result['error'] = $_LANG['no_goods_in_cart']; + } + else + { + /* 取得购物流程设置 */ + $smarty->assign('config', $_CFG); + + /* 取得订单信息 */ + $order = flow_order_info(); + + $order['need_insure'] = intval($_REQUEST['insure']); + + /* 保存 session */ + $_SESSION['flow_order'] = $order; + + /* 计算订单的费用 */ + $total = order_fee($order, $cart_goods, $consignee); + $smarty->assign('total', $total); + + /* 取得可以得到的积分和红包 */ + $smarty->assign('total_integral', cart_amount(false, $flow_type) - $total['bonus'] - $total['integral_money']); + $smarty->assign('total_bonus', price_format(get_total_bonus(), false)); + + /* 团购标志 */ + if ($flow_type == CART_GROUP_BUY_GOODS) + { + $smarty->assign('is_group_buy', 1); + } + + $result['content'] = $smarty->fetch('library/order_total.lbi'); + } + + echo $json->encode($result); + exit; +} +elseif ($_REQUEST['step'] == 'select_payment') +{ + /*------------------------------------------------------ */ + //-- 改变支付方式 + /*------------------------------------------------------ */ + + include_once('includes/cls_json.php'); + $json = new JSON; + $result = array('error' => '', 'content' => '', 'need_insure' => 0, 'payment' => 1); + + /* 取得购物类型 */ + $flow_type = isset($_SESSION['flow_type']) ? intval($_SESSION['flow_type']) : CART_GENERAL_GOODS; + + /* 获得收货人信息 */ + $consignee = get_consignee($_SESSION['user_id']); + + /* 对商品信息赋值 */ + $cart_goods = cart_goods($flow_type); // 取得商品列表,计算合计 + + if (empty($cart_goods) || !check_consignee_info($consignee, $flow_type)) + { + $result['error'] = $_LANG['no_goods_in_cart']; + } + else + { + /* 取得购物流程设置 */ + $smarty->assign('config', $_CFG); + + /* 取得订单信息 */ + $order = flow_order_info(); + + $order['pay_id'] = intval($_REQUEST['payment']); + $payment_info = payment_info($order['pay_id']); + $result['pay_code'] = $payment_info['pay_code']; + + /* 保存 session */ + $_SESSION['flow_order'] = $order; + + /* 计算订单的费用 */ + $total = order_fee($order, $cart_goods, $consignee); + $smarty->assign('total', $total); + + /* 取得可以得到的积分和红包 */ + $smarty->assign('total_integral', cart_amount(false, $flow_type) - $total['bonus'] - $total['integral_money']); + $smarty->assign('total_bonus', price_format(get_total_bonus(), false)); + + /* 团购标志 */ + if ($flow_type == CART_GROUP_BUY_GOODS) + { + $smarty->assign('is_group_buy', 1); + } + + $result['content'] = $smarty->fetch('library/order_total.lbi'); + } + + echo $json->encode($result); + exit; +} +elseif ($_REQUEST['step'] == 'select_pack') +{ + /*------------------------------------------------------ */ + //-- 改变商品包装 + /*------------------------------------------------------ */ + + include_once('includes/cls_json.php'); + $json = new JSON; + $result = array('error' => '', 'content' => '', 'need_insure' => 0); + + /* 取得购物类型 */ + $flow_type = isset($_SESSION['flow_type']) ? intval($_SESSION['flow_type']) : CART_GENERAL_GOODS; + + /* 获得收货人信息 */ + $consignee = get_consignee($_SESSION['user_id']); + + /* 对商品信息赋值 */ + $cart_goods = cart_goods($flow_type); // 取得商品列表,计算合计 + + if (empty($cart_goods) || !check_consignee_info($consignee, $flow_type)) + { + $result['error'] = $_LANG['no_goods_in_cart']; + } + else + { + /* 取得购物流程设置 */ + $smarty->assign('config', $_CFG); + + /* 取得订单信息 */ + $order = flow_order_info(); + + $order['pack_id'] = intval($_REQUEST['pack']); + + /* 保存 session */ + $_SESSION['flow_order'] = $order; + + /* 计算订单的费用 */ + $total = order_fee($order, $cart_goods, $consignee); + $smarty->assign('total', $total); + + /* 取得可以得到的积分和红包 */ + $smarty->assign('total_integral', cart_amount(false, $flow_type) - $total['bonus'] - $total['integral_money']); + $smarty->assign('total_bonus', price_format(get_total_bonus(), false)); + + /* 团购标志 */ + if ($flow_type == CART_GROUP_BUY_GOODS) + { + $smarty->assign('is_group_buy', 1); + } + + $result['content'] = $smarty->fetch('library/order_total.lbi'); + } + + echo $json->encode($result); + exit; +} +elseif ($_REQUEST['step'] == 'select_card') +{ + /*------------------------------------------------------ */ + //-- 改变贺卡 + /*------------------------------------------------------ */ + + include_once('includes/cls_json.php'); + $json = new JSON; + $result = array('error' => '', 'content' => '', 'need_insure' => 0); + + /* 取得购物类型 */ + $flow_type = isset($_SESSION['flow_type']) ? intval($_SESSION['flow_type']) : CART_GENERAL_GOODS; + + /* 获得收货人信息 */ + $consignee = get_consignee($_SESSION['user_id']); + + /* 对商品信息赋值 */ + $cart_goods = cart_goods($flow_type); // 取得商品列表,计算合计 + + if (empty($cart_goods) || !check_consignee_info($consignee, $flow_type)) + { + $result['error'] = $_LANG['no_goods_in_cart']; + } + else + { + /* 取得购物流程设置 */ + $smarty->assign('config', $_CFG); + + /* 取得订单信息 */ + $order = flow_order_info(); + + $order['card_id'] = intval($_REQUEST['card']); + + /* 保存 session */ + $_SESSION['flow_order'] = $order; + + /* 计算订单的费用 */ + $total = order_fee($order, $cart_goods, $consignee); + $smarty->assign('total', $total); + + /* 取得可以得到的积分和红包 */ + $smarty->assign('total_integral', cart_amount(false, $flow_type) - $order['bonus'] - $total['integral_money']); + $smarty->assign('total_bonus', price_format(get_total_bonus(), false)); + + /* 团购标志 */ + if ($flow_type == CART_GROUP_BUY_GOODS) + { + $smarty->assign('is_group_buy', 1); + } + + $result['content'] = $smarty->fetch('library/order_total.lbi'); + } + + echo $json->encode($result); + exit; +} +elseif ($_REQUEST['step'] == 'change_surplus') +{ + /*------------------------------------------------------ */ + //-- 改变余额 + /*------------------------------------------------------ */ + include_once('includes/cls_json.php'); + + $surplus = floatval($_GET['surplus']); + $user_info = user_info($_SESSION['user_id']); + + if ($user_info['user_money'] + $user_info['credit_line'] < $surplus) + { + $result['error'] = $_LANG['surplus_not_enough']; + } + else + { + /* 取得购物类型 */ + $flow_type = isset($_SESSION['flow_type']) ? intval($_SESSION['flow_type']) : CART_GENERAL_GOODS; + + /* 取得购物流程设置 */ + $smarty->assign('config', $_CFG); + + /* 获得收货人信息 */ + $consignee = get_consignee($_SESSION['user_id']); + + /* 对商品信息赋值 */ + $cart_goods = cart_goods($flow_type); // 取得商品列表,计算合计 + + if (empty($cart_goods) || !check_consignee_info($consignee, $flow_type)) + { + $result['error'] = $_LANG['no_goods_in_cart']; + } + else + { + /* 取得订单信息 */ + $order = flow_order_info(); + $order['surplus'] = $surplus; + + /* 计算订单的费用 */ + $total = order_fee($order, $cart_goods, $consignee); + $smarty->assign('total', $total); + + /* 团购标志 */ + if ($flow_type == CART_GROUP_BUY_GOODS) + { + $smarty->assign('is_group_buy', 1); + } + + $result['content'] = $smarty->fetch('library/order_total.lbi'); + } + } + + $json = new JSON(); + die($json->encode($result)); +} +elseif ($_REQUEST['step'] == 'change_integral') +{ + /*------------------------------------------------------ */ + //-- 改变积分 + /*------------------------------------------------------ */ + include_once('includes/cls_json.php'); + + $points = floatval($_GET['points']); + $user_info = user_info($_SESSION['user_id']); + + /* 取得订单信息 */ + $order = flow_order_info(); + + $flow_points = flow_available_points(); // 该订单允许使用的积分 + $user_points = $user_info['pay_points']; // 用户的积分总数 + + if ($points > $user_points) + { + $result['error'] = $_LANG['integral_not_enough']; + } + elseif ($points > $flow_points) + { + $result['error'] = sprintf($_LANG['integral_too_much'], $flow_points); + } + else + { + /* 取得购物类型 */ + $flow_type = isset($_SESSION['flow_type']) ? intval($_SESSION['flow_type']) : CART_GENERAL_GOODS; + + $order['integral'] = $points; + + /* 获得收货人信息 */ + $consignee = get_consignee($_SESSION['user_id']); + + /* 对商品信息赋值 */ + $cart_goods = cart_goods($flow_type); // 取得商品列表,计算合计 + + if (empty($cart_goods) || !check_consignee_info($consignee, $flow_type)) + { + $result['error'] = $_LANG['no_goods_in_cart']; + } + else + { + /* 计算订单的费用 */ + $total = order_fee($order, $cart_goods, $consignee); + $smarty->assign('total', $total); + $smarty->assign('config', $_CFG); + + /* 团购标志 */ + if ($flow_type == CART_GROUP_BUY_GOODS) + { + $smarty->assign('is_group_buy', 1); + } + + $result['content'] = $smarty->fetch('library/order_total.lbi'); + $result['error'] = ''; + } + } + + $json = new JSON(); + die($json->encode($result)); +} +elseif ($_REQUEST['step'] == 'change_bonus') +{ + /*------------------------------------------------------ */ + //-- 改变红包 + /*------------------------------------------------------ */ + include_once('includes/cls_json.php'); + $result = array('error' => '', 'content' => ''); + + /* 取得购物类型 */ + $flow_type = isset($_SESSION['flow_type']) ? intval($_SESSION['flow_type']) : CART_GENERAL_GOODS; + + /* 获得收货人信息 */ + $consignee = get_consignee($_SESSION['user_id']); + + /* 对商品信息赋值 */ + $cart_goods = cart_goods($flow_type); // 取得商品列表,计算合计 + + if (empty($cart_goods) || !check_consignee_info($consignee, $flow_type)) + { + $result['error'] = $_LANG['no_goods_in_cart']; + } + else + { + /* 取得购物流程设置 */ + $smarty->assign('config', $_CFG); + + /* 取得订单信息 */ + $order = flow_order_info(); + + $bonus = bonus_info(intval($_GET['bonus'])); + + if ((!empty($bonus) && $bonus['user_id'] == $_SESSION['user_id']) || $_GET['bonus'] == 0) + { + $order['bonus_id'] = $_GET['bonus']; + } + else + { + $order['bonus_id'] = 0; + $result['error'] = $_LANG['invalid_bonus']; + } + + /* 计算订单的费用 */ + $total = order_fee($order, $cart_goods, $consignee); + $smarty->assign('total', $total); + + /* 团购标志 */ + if ($flow_type == CART_GROUP_BUY_GOODS) + { + $smarty->assign('is_group_buy', 1); + } + + $result['content'] = $smarty->fetch('library/order_total.lbi'); + } + + $json = new JSON(); + die($json->encode($result)); +} +elseif ($_REQUEST['step'] == 'change_needinv') +{ + /*------------------------------------------------------ */ + //-- 改变发票的设置 + /*------------------------------------------------------ */ + include_once('includes/cls_json.php'); + $result = array('error' => '', 'content' => ''); + $json = new JSON(); + $_GET['inv_type'] = !empty($_GET['inv_type']) ? json_str_iconv(urldecode($_GET['inv_type'])) : ''; + $_GET['invPayee'] = !empty($_GET['invPayee']) ? json_str_iconv(urldecode($_GET['invPayee'])) : ''; + $_GET['inv_content'] = !empty($_GET['inv_content']) ? json_str_iconv(urldecode($_GET['inv_content'])) : ''; + + /* 取得购物类型 */ + $flow_type = isset($_SESSION['flow_type']) ? intval($_SESSION['flow_type']) : CART_GENERAL_GOODS; + + /* 获得收货人信息 */ + $consignee = get_consignee($_SESSION['user_id']); + + /* 对商品信息赋值 */ + $cart_goods = cart_goods($flow_type); // 取得商品列表,计算合计 + + if (empty($cart_goods) || !check_consignee_info($consignee, $flow_type)) + { + $result['error'] = $_LANG['no_goods_in_cart']; + die($json->encode($result)); + } + else + { + /* 取得购物流程设置 */ + $smarty->assign('config', $_CFG); + + /* 取得订单信息 */ + $order = flow_order_info(); + + if (isset($_GET['need_inv']) && intval($_GET['need_inv']) == 1) + { + $order['need_inv'] = 1; + $order['inv_type'] = trim(stripslashes($_GET['inv_type'])); + $order['inv_payee'] = trim(stripslashes($_GET['inv_payee'])); + $order['inv_content'] = trim(stripslashes($_GET['inv_content'])); + } + else + { + $order['need_inv'] = 0; + $order['inv_type'] = ''; + $order['inv_payee'] = ''; + $order['inv_content'] = ''; + } + + /* 计算订单的费用 */ + $total = order_fee($order, $cart_goods, $consignee); + $smarty->assign('total', $total); + + /* 团购标志 */ + if ($flow_type == CART_GROUP_BUY_GOODS) + { + $smarty->assign('is_group_buy', 1); + } + + die($smarty->fetch('library/order_total.lbi')); + } +} +elseif ($_REQUEST['step'] == 'change_oos') +{ + /*------------------------------------------------------ */ + //-- 改变缺货处理时的方式 + /*------------------------------------------------------ */ + + /* 取得订单信息 */ + $order = flow_order_info(); + + $order['how_oos'] = intval($_GET['oos']); + + /* 保存 session */ + $_SESSION['flow_order'] = $order; +} +elseif ($_REQUEST['step'] == 'check_surplus') +{ + /*------------------------------------------------------ */ + //-- 检查用户输入的余额 + /*------------------------------------------------------ */ + $surplus = floatval($_GET['surplus']); + $user_info = user_info($_SESSION['user_id']); + + if (($user_info['user_money'] + $user_info['credit_line'] < $surplus)) + { + die($_LANG['surplus_not_enough']); + } + + exit; +} +elseif ($_REQUEST['step'] == 'check_integral') +{ + /*------------------------------------------------------ */ + //-- 检查用户输入的余额 + /*------------------------------------------------------ */ + $points = floatval($_GET['integral']); + $user_info = user_info($_SESSION['user_id']); + $flow_points = flow_available_points(); // 该订单允许使用的积分 + $user_points = $user_info['pay_points']; // 用户的积分总数 + + if ($points > $user_points) + { + die($_LANG['integral_not_enough']); + } + + if ($points > $flow_points) + { + die(sprintf($_LANG['integral_too_much'], $flow_points)); + } + + exit; +} +/*------------------------------------------------------ */ +//-- 完成所有订单操作,提交到数据库 +/*------------------------------------------------------ */ +elseif ($_REQUEST['step'] == 'done') +{ + include_once('includes/lib_clips.php'); + include_once('includes/lib_payment.php'); + + /* 取得购物类型 */ + $flow_type = isset($_SESSION['flow_type']) ? intval($_SESSION['flow_type']) : CART_GENERAL_GOODS; + + /* 检查购物车中是否有商品 */ + $sql = "SELECT COUNT(*) FROM " . $ecs->table('cart') . + " WHERE session_id = '" . SESS_ID . "' " . + "AND parent_id = 0 AND is_gift = 0 AND rec_type = '$flow_type'"; + if ($db->getOne($sql) == 0) + { + show_message($_LANG['no_goods_in_cart'], '', '', 'warning'); + } + + /* 检查商品库存 */ + /* 如果使用库存,且下订单时减库存,则减少库存 */ + if ($_CFG['use_storage'] == '1' && $_CFG['stock_dec_time'] == SDT_PLACE) + { + $cart_goods_stock = get_cart_goods(); + $_cart_goods_stock = array(); + foreach ($cart_goods_stock['goods_list'] as $value) + { + $_cart_goods_stock[$value['rec_id']] = $value['goods_number']; + } + flow_cart_stock($_cart_goods_stock); + unset($cart_goods_stock, $_cart_goods_stock); + } + + /* + * 检查用户是否已经登录 + * 如果用户已经登录了则检查是否有默认的收货地址 + * 如果没有登录则跳转到登录和注册页面 + */ + if (empty($_SESSION['direct_shopping']) && $_SESSION['user_id'] == 0) + { + /* 用户没有登录且没有选定匿名购物,转向到登录页面 */ + ecs_header("Location: flow.php?step=login\n"); + exit; + } + + $consignee = get_consignee($_SESSION['user_id']); + + /* 检查收货人信息是否完整 */ + if (!check_consignee_info($consignee, $flow_type)) + { + /* 如果不完整则转向到收货人信息填写界面 */ + ecs_header("Location: flow.php?step=consignee\n"); + exit; + } + + $_POST['how_oos'] = isset($_POST['how_oos']) ? intval($_POST['how_oos']) : 0; + $_POST['card_message'] = isset($_POST['card_message']) ? htmlspecialchars($_POST['card_message']) : ''; + $_POST['inv_type'] = !empty($_POST['inv_type']) ? htmlspecialchars($_POST['inv_type']) : ''; + $_POST['inv_payee'] = isset($_POST['inv_payee']) ? htmlspecialchars($_POST['inv_payee']) : ''; + $_POST['inv_content'] = isset($_POST['inv_content']) ? htmlspecialchars($_POST['inv_content']) : ''; + $_POST['postscript'] = isset($_POST['postscript']) ? htmlspecialchars($_POST['postscript']) : ''; + + $order = array( + 'shipping_id' => intval($_POST['shipping']), + 'pay_id' => intval($_POST['payment']), + 'pack_id' => isset($_POST['pack']) ? intval($_POST['pack']) : 0, + 'card_id' => isset($_POST['card']) ? intval($_POST['card']) : 0, + 'card_message' => trim($_POST['card_message']), + 'surplus' => isset($_POST['surplus']) ? floatval($_POST['surplus']) : 0.00, + 'integral' => isset($_POST['integral']) ? intval($_POST['integral']) : 0, + 'bonus_id' => isset($_POST['bonus']) ? intval($_POST['bonus']) : 0, + 'need_inv' => empty($_POST['need_inv']) ? 0 : 1, + 'inv_type' => $_POST['inv_type'], + 'inv_payee' => trim($_POST['inv_payee']), + 'inv_content' => $_POST['inv_content'], + 'postscript' => trim($_POST['postscript']), + 'how_oos' => isset($_LANG['oos'][$_POST['how_oos']]) ? addslashes($_LANG['oos'][$_POST['how_oos']]) : '', + 'need_insure' => isset($_POST['need_insure']) ? intval($_POST['need_insure']) : 0, + 'user_id' => $_SESSION['user_id'], + 'add_time' => gmtime(), + 'order_status' => OS_UNCONFIRMED, + 'shipping_status' => SS_UNSHIPPED, + 'pay_status' => PS_UNPAYED, + 'agency_id' => get_agency_by_regions(array($consignee['country'], $consignee['province'], $consignee['city'], $consignee['district'])) + ); + + /* 扩展信息 */ + if (isset($_SESSION['flow_type']) && intval($_SESSION['flow_type']) != CART_GENERAL_GOODS) + { + $order['extension_code'] = $_SESSION['extension_code']; + $order['extension_id'] = $_SESSION['extension_id']; + } + else + { + $order['extension_code'] = ''; + $order['extension_id'] = 0; + } + + /* 检查积分余额是否合法 */ + $user_id = $_SESSION['user_id']; + if ($user_id > 0) + { + $user_info = user_info($user_id); + + $order['surplus'] = min($order['surplus'], $user_info['user_money'] + $user_info['credit_line']); + if ($order['surplus'] < 0) + { + $order['surplus'] = 0; + } + + // 查询用户有多少积分 + $flow_points = flow_available_points(); // 该订单允许使用的积分 + $user_points = $user_info['pay_points']; // 用户的积分总数 + + $order['integral'] = min($order['integral'], $user_points, $flow_points); + if ($order['integral'] < 0) + { + $order['integral'] = 0; + } + } + else + { + $order['surplus'] = 0; + $order['integral'] = 0; + } + + /* 检查红包是否存在 */ + if ($order['bonus_id'] > 0) + { + $bonus = bonus_info($order['bonus_id']); + + if (empty($bonus) || $bonus['user_id'] != $user_id || $bonus['order_id'] > 0 || $bonus['min_goods_amount'] > cart_amount(true, $flow_type)) + { + $order['bonus_id'] = 0; + } + } + elseif (isset($_POST['bonus_sn'])) + { + $bonus_sn = trim($_POST['bonus_sn']); + $bonus = bonus_info(0, $bonus_sn); + $now = gmtime(); + if (empty($bonus) || $bonus['user_id'] > 0 || $bonus['order_id'] > 0 || $bonus['min_goods_amount'] > cart_amount(true, $flow_type) || $now > $bonus['use_end_date']) + { + } + else + { + if ($user_id > 0) + { + $sql = "UPDATE " . $ecs->table('user_bonus') . " SET user_id = '$user_id' WHERE bonus_id = '$bonus[bonus_id]' LIMIT 1"; + $db->query($sql); + } + $order['bonus_id'] = $bonus['bonus_id']; + $order['bonus_sn'] = $bonus_sn; + } + } + + /* 订单中的商品 */ + $cart_goods = cart_goods($flow_type); + + if (empty($cart_goods)) + { + show_message($_LANG['no_goods_in_cart'], $_LANG['back_home'], './', 'warning'); + } + + /* 检查商品总额是否达到最低限购金额 */ + if ($flow_type == CART_GENERAL_GOODS && cart_amount(true, CART_GENERAL_GOODS) < $_CFG['min_goods_amount']) + { + show_message(sprintf($_LANG['goods_amount_not_enough'], price_format($_CFG['min_goods_amount'], false))); + } + + /* 收货人信息 */ + foreach ($consignee as $key => $value) + { + $order[$key] = addslashes($value); + } + + /* 订单中的总额 */ + $total = order_fee($order, $cart_goods, $consignee); + + $order['bonus'] = $total['bonus']; + $order['goods_amount'] = $total['goods_price']; + $order['discount'] = $total['discount']; + $order['surplus'] = $total['surplus']; + $order['tax'] = $total['tax']; + + // 购物车中的商品能享受红包支付的总额 + $discount_amout = compute_discount_amount(); + // 红包和积分最多能支付的金额为商品总额 + $temp_amout = $order['goods_amount'] - $discount_amout; + if ($temp_amout <= 0) + { + $order['bonus_id'] = 0; + } + + /* 配送方式 */ + if ($order['shipping_id'] > 0) + { + $shipping = shipping_info($order['shipping_id']); + $order['shipping_name'] = addslashes($shipping['shipping_name']); + } + $order['shipping_fee'] = $total['shipping_fee']; + $order['insure_fee'] = $total['shipping_insure']; + + /* 支付方式 */ + if ($order['pay_id'] > 0) + { + $payment = payment_info($order['pay_id']); + $order['pay_name'] = addslashes($payment['pay_name']); + } + $order['pay_fee'] = $total['pay_fee']; + $order['cod_fee'] = $total['cod_fee']; + + /* 商品包装 */ + if ($order['pack_id'] > 0) + { + $pack = pack_info($order['pack_id']); + $order['pack_name'] = addslashes($pack['pack_name']); + } + $order['pack_fee'] = $total['pack_fee']; + + /* 祝福贺卡 */ + if ($order['card_id'] > 0) + { + $card = card_info($order['card_id']); + $order['card_name'] = addslashes($card['card_name']); + } + $order['card_fee'] = $total['card_fee']; + + $order['order_amount'] = number_format($total['amount'], 2, '.', ''); + + /* 如果全部使用余额支付,检查余额是否足够 */ + if ($payment['pay_code'] == 'balance' && $order['order_amount'] > 0) + { + if($order['surplus'] >0) //余额支付里如果输入了一个金额 + { + $order['order_amount'] = $order['order_amount'] + $order['surplus']; + $order['surplus'] = 0; + } + if ($order['order_amount'] > ($user_info['user_money'] + $user_info['credit_line'])) + { + show_message($_LANG['balance_not_enough']); + } + else + { + $order['surplus'] = $order['order_amount']; + $order['order_amount'] = 0; + } + } + + /* 如果订单金额为0(使用余额或积分或红包支付),修改订单状态为已确认、已付款 */ + if ($order['order_amount'] <= 0) + { + $order['order_status'] = OS_CONFIRMED; + $order['confirm_time'] = gmtime(); + $order['pay_status'] = PS_PAYED; + $order['pay_time'] = gmtime(); + $order['order_amount'] = 0; + } + + $order['integral_money'] = $total['integral_money']; + $order['integral'] = $total['integral']; + + if ($order['extension_code'] == 'exchange_goods') + { + $order['integral_money'] = 0; + $order['integral'] = $total['exchange_integral']; + } + + $order['from_ad'] = !empty($_SESSION['from_ad']) ? $_SESSION['from_ad'] : '0'; + $order['referer'] = !empty($_SESSION['referer']) ? addslashes($_SESSION['referer']) : ''; + + /* 记录扩展信息 */ + if ($flow_type != CART_GENERAL_GOODS) + { + $order['extension_code'] = $_SESSION['extension_code']; + $order['extension_id'] = $_SESSION['extension_id']; + } + + $affiliate = unserialize($_CFG['affiliate']); + if(isset($affiliate['on']) && $affiliate['on'] == 1 && $affiliate['config']['separate_by'] == 1) + { + //推荐订单分成 + $parent_id = get_affiliate(); + if($user_id == $parent_id) + { + $parent_id = 0; + } + } + elseif(isset($affiliate['on']) && $affiliate['on'] == 1 && $affiliate['config']['separate_by'] == 0) + { + //推荐注册分成 + $parent_id = 0; + } + else + { + //分成功能关闭 + $parent_id = 0; + } + $order['parent_id'] = $parent_id; + + /* 插入订单表 */ + $error_no = 0; + do + { + $order['order_sn'] = get_order_sn(); //获取新订单号 + $GLOBALS['db']->autoExecute($GLOBALS['ecs']->table('order_info'), $order, 'INSERT'); + + $error_no = $GLOBALS['db']->errno(); + + if ($error_no > 0 && $error_no != 1062) + { + die($GLOBALS['db']->errorMsg()); + } + } + while ($error_no == 1062); //如果是订单号重复则重新提交数据 + + $new_order_id = $db->insert_id(); + $order['order_id'] = $new_order_id; + + /* 插入订单商品 */ + $sql = "INSERT INTO " . $ecs->table('order_goods') . "( " . + "order_id, goods_id, goods_name, goods_sn, product_id, goods_number, market_price, ". + "goods_price, goods_attr, is_real, extension_code, parent_id, is_gift, goods_attr_id) ". + " SELECT '$new_order_id', goods_id, goods_name, goods_sn, product_id, goods_number, market_price, ". + "goods_price, goods_attr, is_real, extension_code, parent_id, is_gift, goods_attr_id". + " FROM " .$ecs->table('cart') . + " WHERE session_id = '".SESS_ID."' AND rec_type = '$flow_type'"; + $db->query($sql); + /* 修改拍卖活动状态 */ + if ($order['extension_code']=='auction') + { + $sql = "UPDATE ". $ecs->table('goods_activity') ." SET is_finished='2' WHERE act_id=".$order['extension_id']; + $db->query($sql); + } + + /* 处理余额、积分、红包 */ + if ($order['user_id'] > 0 && $order['surplus'] > 0) + { + log_account_change($order['user_id'], $order['surplus'] * (-1), 0, 0, 0, sprintf($_LANG['pay_order'], $order['order_sn'])); + } + if ($order['user_id'] > 0 && $order['integral'] > 0) + { + log_account_change($order['user_id'], 0, 0, 0, $order['integral'] * (-1), sprintf($_LANG['pay_order'], $order['order_sn'])); + } + + + if ($order['bonus_id'] > 0 && $temp_amout > 0) + { + use_bonus($order['bonus_id'], $new_order_id); + } + + /* 如果使用库存,且下订单时减库存,则减少库存 */ + if ($_CFG['use_storage'] == '1' && $_CFG['stock_dec_time'] == SDT_PLACE) + { + change_order_goods_storage($order['order_id'], true, SDT_PLACE); + } + + /* 给商家发邮件 */ + /* 增加是否给客服发送邮件选项 */ + if ($_CFG['send_service_email'] && $_CFG['service_email'] != '') + { + $tpl = get_mail_template('remind_of_new_order'); + $smarty->assign('order', $order); + $smarty->assign('goods_list', $cart_goods); + $smarty->assign('shop_name', $_CFG['shop_name']); + $smarty->assign('send_date', date($_CFG['time_format'])); + $content = $smarty->fetch('str:' . $tpl['template_content']); + send_mail($_CFG['shop_name'], $_CFG['service_email'], $tpl['template_subject'], $content, $tpl['is_html']); + } + + /* 如果需要,发短信 */ + if ($_CFG['sms_order_placed'] == '1' && $_CFG['sms_shop_mobile'] != '') + { + include_once('includes/cls_sms.php'); + $sms = new sms(); + $msg = $order['pay_status'] == PS_UNPAYED ? + $_LANG['order_placed_sms'] : $_LANG['order_placed_sms'] . '[' . $_LANG['sms_paid'] . ']'; + $sms->send($_CFG['sms_shop_mobile'], sprintf($msg, $order['consignee'], $order['tel']), 0); + } + + /* 如果订单金额为0 处理虚拟卡 */ + if ($order['order_amount'] <= 0) + { + $sql = "SELECT goods_id, goods_name, goods_number AS num FROM ". + $GLOBALS['ecs']->table('cart') . + " WHERE is_real = 0 AND extension_code = 'virtual_card'". + " AND session_id = '".SESS_ID."' AND rec_type = '$flow_type'"; + + $res = $GLOBALS['db']->getAll($sql); + + $virtual_goods = array(); + foreach ($res AS $row) + { + $virtual_goods['virtual_card'][] = array('goods_id' => $row['goods_id'], 'goods_name' => $row['goods_name'], 'num' => $row['num']); + } + + if ($virtual_goods AND $flow_type != CART_GROUP_BUY_GOODS) + { + /* 虚拟卡发货 */ + if (virtual_goods_ship($virtual_goods,$msg, $order['order_sn'], true)) + { + /* 如果没有实体商品,修改发货状态,送积分和红包 */ + $sql = "SELECT COUNT(*)" . + " FROM " . $ecs->table('order_goods') . + " WHERE order_id = '$order[order_id]' " . + " AND is_real = 1"; + if ($db->getOne($sql) <= 0) + { + /* 修改订单状态 */ + update_order($order['order_id'], array('shipping_status' => SS_SHIPPED, 'shipping_time' => gmtime())); + + /* 如果订单用户不为空,计算积分,并发给用户;发红包 */ + if ($order['user_id'] > 0) + { + /* 取得用户信息 */ + $user = user_info($order['user_id']); + + /* 计算并发放积分 */ + $integral = integral_to_give($order); + log_account_change($order['user_id'], 0, 0, intval($integral['rank_points']), intval($integral['custom_points']), sprintf($_LANG['order_gift_integral'], $order['order_sn'])); + + /* 发放红包 */ + send_order_bonus($order['order_id']); + } + } + } + } + + } + + /* 清空购物车 */ + clear_cart($flow_type); + /* 清除缓存,否则买了商品,但是前台页面读取缓存,商品数量不减少 */ + clear_all_files(); + + /* 插入支付日志 */ + $order['log_id'] = insert_pay_log($new_order_id, $order['order_amount'], PAY_ORDER); + + /* 取得支付信息,生成支付代码 */ + if ($order['order_amount'] > 0) + { + $payment = payment_info($order['pay_id']); + + include_once('includes/modules/payment/' . $payment['pay_code'] . '.php'); + + $pay_obj = new $payment['pay_code']; + + $pay_online = $pay_obj->get_code($order, unserialize_config($payment['pay_config'])); + + $order['pay_desc'] = $payment['pay_desc']; + + $smarty->assign('pay_online', $pay_online); + } + if(!empty($order['shipping_name'])) + { + $order['shipping_name']=trim(stripcslashes($order['shipping_name'])); + } + + /* 订单信息 */ + $smarty->assign('order', $order); + $smarty->assign('total', $total); + $smarty->assign('goods_list', $cart_goods); + $smarty->assign('order_submit_back', sprintf($_LANG['order_submit_back'], $_LANG['back_home'], $_LANG['goto_user_center'])); // 返回提示 + + user_uc_call('add_feed', array($order['order_id'], BUY_GOODS)); //推送feed到uc + unset($_SESSION['flow_consignee']); // 清除session中保存的收货人信息 + unset($_SESSION['flow_order']); + unset($_SESSION['direct_shopping']); +} + +/*------------------------------------------------------ */ +//-- 更新购物车 +/*------------------------------------------------------ */ + +elseif ($_REQUEST['step'] == 'update_cart') +{ + if (isset($_POST['goods_number']) && is_array($_POST['goods_number'])) + { + flow_update_cart($_POST['goods_number']); + } + + show_message($_LANG['update_cart_notice'], $_LANG['back_to_cart'], 'flow.php'); + exit; +} + +/*------------------------------------------------------ */ +//-- 删除购物车中的商品 +/*------------------------------------------------------ */ + +elseif ($_REQUEST['step'] == 'drop_goods') +{ + $rec_id = intval($_GET['id']); + flow_drop_cart_goods($rec_id); + + ecs_header("Location: flow.php\n"); + exit; +} + +/* 把优惠活动加入购物车 */ +elseif ($_REQUEST['step'] == 'add_favourable') +{ + /* 取得优惠活动信息 */ + $act_id = intval($_POST['act_id']); + $favourable = favourable_info($act_id); + if (empty($favourable)) + { + show_message($_LANG['favourable_not_exist']); + } + + /* 判断用户能否享受该优惠 */ + if (!favourable_available($favourable)) + { + show_message($_LANG['favourable_not_available']); + } + + /* 检查购物车中是否已有该优惠 */ + $cart_favourable = cart_favourable(); + if (favourable_used($favourable, $cart_favourable)) + { + show_message($_LANG['favourable_used']); + } + + /* 赠品(特惠品)优惠 */ + if ($favourable['act_type'] == FAT_GOODS) + { + /* 检查是否选择了赠品 */ + if (empty($_POST['gift'])) + { + show_message($_LANG['pls_select_gift']); + } + + /* 检查是否已在购物车 */ + $sql = "SELECT goods_name" . + " FROM " . $ecs->table('cart') . + " WHERE session_id = '" . SESS_ID . "'" . + " AND rec_type = '" . CART_GENERAL_GOODS . "'" . + " AND is_gift = '$act_id'" . + " AND goods_id " . db_create_in($_POST['gift']); + $gift_name = $db->getCol($sql); + if (!empty($gift_name)) + { + show_message(sprintf($_LANG['gift_in_cart'], join(',', $gift_name))); + } + + /* 检查数量是否超过上限 */ + $count = isset($cart_favourable[$act_id]) ? $cart_favourable[$act_id] : 0; + if ($favourable['act_type_ext'] > 0 && $count + count($_POST['gift']) > $favourable['act_type_ext']) + { + show_message($_LANG['gift_count_exceed']); + } + + /* 添加赠品到购物车 */ + foreach ($favourable['gift'] as $gift) + { + if (in_array($gift['id'], $_POST['gift'])) + { + add_gift_to_cart($act_id, $gift['id'], $gift['price']); + } + } + } + elseif ($favourable['act_type'] == FAT_DISCOUNT) + { + add_favourable_to_cart($act_id, $favourable['act_name'], cart_favourable_amount($favourable) * (100 - $favourable['act_type_ext']) / 100); + } + elseif ($favourable['act_type'] == FAT_PRICE) + { + add_favourable_to_cart($act_id, $favourable['act_name'], $favourable['act_type_ext']); + } + + /* 刷新购物车 */ + ecs_header("Location: flow.php\n"); + exit; +} +elseif ($_REQUEST['step'] == 'clear') +{ + $sql = "DELETE FROM " . $ecs->table('cart') . " WHERE session_id='" . SESS_ID . "'"; + $db->query($sql); + + ecs_header("Location:./\n"); +} +elseif ($_REQUEST['step'] == 'drop_to_collect') +{ + if ($_SESSION['user_id'] > 0) + { + $rec_id = intval($_GET['id']); + $goods_id = $db->getOne("SELECT goods_id FROM " .$ecs->table('cart'). " WHERE rec_id = '$rec_id' AND session_id = '" . SESS_ID . "' "); + $count = $db->getOne("SELECT goods_id FROM " . $ecs->table('collect_goods') . " WHERE user_id = '$_SESSION[user_id]' AND goods_id = '$goods_id'"); + if (empty($count)) + { + $time = gmtime(); + $sql = "INSERT INTO " .$GLOBALS['ecs']->table('collect_goods'). " (user_id, goods_id, add_time)" . + "VALUES ('$_SESSION[user_id]', '$goods_id', '$time')"; + $db->query($sql); + } + flow_drop_cart_goods($rec_id); + } + ecs_header("Location: flow.php\n"); + exit; +} + +/* 验证红包序列号 */ +elseif ($_REQUEST['step'] == 'validate_bonus') +{ + $bonus_sn = trim($_REQUEST['bonus_sn']); + if (is_numeric($bonus_sn)) + { + $bonus = bonus_info(0, $bonus_sn); + } + else + { + $bonus = array(); + } + +// if (empty($bonus) || $bonus['user_id'] > 0 || $bonus['order_id'] > 0) +// { +// die($_LANG['bonus_sn_error']); +// } +// if ($bonus['min_goods_amount'] > cart_amount()) +// { +// die(sprintf($_LANG['bonus_min_amount_error'], price_format($bonus['min_goods_amount'], false))); +// } +// die(sprintf($_LANG['bonus_is_ok'], price_format($bonus['type_money'], false))); + $bonus_kill = price_format($bonus['type_money'], false); + + include_once('includes/cls_json.php'); + $result = array('error' => '', 'content' => ''); + + /* 取得购物类型 */ + $flow_type = isset($_SESSION['flow_type']) ? intval($_SESSION['flow_type']) : CART_GENERAL_GOODS; + + /* 获得收货人信息 */ + $consignee = get_consignee($_SESSION['user_id']); + + /* 对商品信息赋值 */ + $cart_goods = cart_goods($flow_type); // 取得商品列表,计算合计 + + if (empty($cart_goods) || !check_consignee_info($consignee, $flow_type)) + { + $result['error'] = $_LANG['no_goods_in_cart']; + } + else + { + /* 取得购物流程设置 */ + $smarty->assign('config', $_CFG); + + /* 取得订单信息 */ + $order = flow_order_info(); + + + if (((!empty($bonus) && $bonus['user_id'] == $_SESSION['user_id']) || ($bonus['type_money'] > 0 && empty($bonus['user_id']))) && $bonus['order_id'] <= 0) + { + //$order['bonus_kill'] = $bonus['type_money']; + $now = gmtime(); + if ($now > $bonus['use_end_date']) + { + $order['bonus_id'] = ''; + $result['error']=$_LANG['bonus_use_expire']; + } + else + { + $order['bonus_id'] = $bonus['bonus_id']; + $order['bonus_sn'] = $bonus_sn; + } + } + else + { + //$order['bonus_kill'] = 0; + $order['bonus_id'] = ''; + $result['error'] = $_LANG['invalid_bonus']; + } + + /* 计算订单的费用 */ + $total = order_fee($order, $cart_goods, $consignee); + + $smarty->assign('total', $total); + + /* 团购标志 */ + if ($flow_type == CART_GROUP_BUY_GOODS) + { + $smarty->assign('is_group_buy', 1); + } + + $result['content'] = $smarty->fetch('library/order_total.lbi'); + } + $json = new JSON(); + die($json->encode($result)); +} +/*------------------------------------------------------ */ +//-- 添加礼包到购物车 +/*------------------------------------------------------ */ +elseif ($_REQUEST['step'] == 'add_package_to_cart') +{ + include_once('includes/cls_json.php'); + $_POST['package_info'] = json_str_iconv($_POST['package_info']); + + $result = array('error' => 0, 'message' => '', 'content' => '', 'package_id' => ''); + $json = new JSON; + + if (empty($_POST['package_info'])) + { + $result['error'] = 1; + die($json->encode($result)); + } + + $package = $json->decode($_POST['package_info']); + + /* 如果是一步购物,先清空购物车 */ + if ($_CFG['one_step_buy'] == '1') + { + clear_cart(); + } + + /* 商品数量是否合法 */ + if (!is_numeric($package->number) || intval($package->number) <= 0) + { + $result['error'] = 1; + $result['message'] = $_LANG['invalid_number']; + } + else + { + /* 添加到购物车 */ + if (add_package_to_cart($package->package_id, $package->number)) + { + if ($_CFG['cart_confirm'] > 2) + { + $result['message'] = ''; + } + else + { + $result['message'] = $_CFG['cart_confirm'] == 1 ? $_LANG['addto_cart_success_1'] : $_LANG['addto_cart_success_2']; + } + + $result['content'] = insert_cart_info(); + $result['one_step_buy'] = $_CFG['one_step_buy']; + } + else + { + $result['message'] = $err->last_message(); + $result['error'] = $err->error_no; + $result['package_id'] = stripslashes($package->package_id); + } + } + $result['confirm_type'] = !empty($_CFG['cart_confirm']) ? $_CFG['cart_confirm'] : 2; + die($json->encode($result)); +} +else +{ + /* 标记购物流程为普通商品 */ + $_SESSION['flow_type'] = CART_GENERAL_GOODS; + + /* 如果是一步购物,跳到结算中心 */ + if ($_CFG['one_step_buy'] == '1') + { + ecs_header("Location: flow.php?step=checkout\n"); + exit; + } + + /* 取得商品列表,计算合计 */ + $cart_goods = get_cart_goods(); + $smarty->assign('goods_list', $cart_goods['goods_list']); + $smarty->assign('total', $cart_goods['total']); + + //购物车的描述的格式化 + $smarty->assign('shopping_money', sprintf($_LANG['shopping_money'], $cart_goods['total']['goods_price'])); + $smarty->assign('market_price_desc', sprintf($_LANG['than_market_price'], + $cart_goods['total']['market_price'], $cart_goods['total']['saving'], $cart_goods['total']['save_rate'])); + + // 显示收藏夹内的商品 + if ($_SESSION['user_id'] > 0) + { + require_once(ROOT_PATH . 'includes/lib_clips.php'); + $collection_goods = get_collection_goods($_SESSION['user_id']); + $smarty->assign('collection_goods', $collection_goods); + } + + /* 取得优惠活动 */ + $favourable_list = favourable_list($_SESSION['user_rank']); + usort($favourable_list, 'cmp_favourable'); + + $smarty->assign('favourable_list', $favourable_list); + + /* 计算折扣 */ + $discount = compute_discount(); + $smarty->assign('discount', $discount['discount']); + $favour_name = empty($discount['name']) ? '' : join(',', $discount['name']); + $smarty->assign('your_discount', sprintf($_LANG['your_discount'], $favour_name, price_format($discount['discount']))); + + /* 增加是否在购物车里显示商品图 */ + $smarty->assign('show_goods_thumb', $GLOBALS['_CFG']['show_goods_in_cart']); + + /* 增加是否在购物车里显示商品属性 */ + $smarty->assign('show_goods_attribute', $GLOBALS['_CFG']['show_attr_in_cart']); + + /* 购物车中商品配件列表 */ + //取得购物车中基本件ID + $sql = "SELECT goods_id " . + "FROM " . $GLOBALS['ecs']->table('cart') . + " WHERE session_id = '" . SESS_ID . "' " . + "AND rec_type = '" . CART_GENERAL_GOODS . "' " . + "AND is_gift = 0 " . + "AND extension_code <> 'package_buy' " . + "AND parent_id = 0 "; + $parent_list = $GLOBALS['db']->getCol($sql); + + $fittings_list = get_goods_fittings($parent_list); + + $smarty->assign('fittings_list', $fittings_list); +} + +$smarty->assign('currency_format', $_CFG['currency_format']); +$smarty->assign('integral_scale', $_CFG['integral_scale']); +$smarty->assign('step', $_REQUEST['step']); +assign_dynamic('shopping_flow'); + +$smarty->display('flow.dwt'); + +/*------------------------------------------------------ */ +//-- PRIVATE FUNCTION +/*------------------------------------------------------ */ + +/** + * 获得用户的可用积分 + * + * @access private + * @return integral + */ +function flow_available_points() +{ + $sql = "SELECT SUM(g.integral * c.goods_number) ". + "FROM " . $GLOBALS['ecs']->table('cart') . " AS c, " . $GLOBALS['ecs']->table('goods') . " AS g " . + "WHERE c.session_id = '" . SESS_ID . "' AND c.goods_id = g.goods_id AND c.is_gift = 0 AND g.integral > 0 " . + "AND c.rec_type = '" . CART_GENERAL_GOODS . "'"; + + $val = intval($GLOBALS['db']->getOne($sql)); + + return integral_of_value($val); +} + +/** + * 更新购物车中的商品数量 + * + * @access public + * @param array $arr + * @return void + */ +function flow_update_cart($arr) +{ + /* 处理 */ + foreach ($arr AS $key => $val) + { + $val = intval(make_semiangle($val)); + if ($val <= 0 && !is_numeric($key)) + { + continue; + } + + //查询: + $sql = "SELECT `goods_id`, `goods_attr_id`, `product_id`, `extension_code` FROM" .$GLOBALS['ecs']->table('cart'). + " WHERE rec_id='$key' AND session_id='" . SESS_ID . "'"; + $goods = $GLOBALS['db']->getRow($sql); + + $sql = "SELECT g.goods_name, g.goods_number ". + "FROM " .$GLOBALS['ecs']->table('goods'). " AS g, ". + $GLOBALS['ecs']->table('cart'). " AS c ". + "WHERE g.goods_id = c.goods_id AND c.rec_id = '$key'"; + $row = $GLOBALS['db']->getRow($sql); + + //查询:系统启用了库存,检查输入的商品数量是否有效 + if (intval($GLOBALS['_CFG']['use_storage']) > 0 && $goods['extension_code'] != 'package_buy') + { + if ($row['goods_number'] < $val) + { + show_message(sprintf($GLOBALS['_LANG']['stock_insufficiency'], $row['goods_name'], + $row['goods_number'], $row['goods_number'])); + exit; + } + /* 是货品 */ + $goods['product_id'] = trim($goods['product_id']); + if (!empty($goods['product_id'])) + { + $sql = "SELECT product_number FROM " .$GLOBALS['ecs']->table('products'). " WHERE goods_id = '" . $goods['goods_id'] . "' AND product_id = '" . $goods['product_id'] . "'"; + + $product_number = $GLOBALS['db']->getOne($sql); + if ($product_number < $val) + { + show_message(sprintf($GLOBALS['_LANG']['stock_insufficiency'], $row['goods_name'], + $product_number['product_number'], $product_number['product_number'])); + exit; + } + } + } + elseif (intval($GLOBALS['_CFG']['use_storage']) > 0 && $goods['extension_code'] == 'package_buy') + { + if (judge_package_stock($goods['goods_id'], $val)) + { + show_message($GLOBALS['_LANG']['package_stock_insufficiency']); + exit; + } + } + + /* 查询:检查该项是否为基本件 以及是否存在配件 */ + /* 此处配件是指添加商品时附加的并且是设置了优惠价格的配件 此类配件都有parent_id goods_number为1 */ + $sql = "SELECT b.goods_number, b.rec_id + FROM " .$GLOBALS['ecs']->table('cart') . " a, " .$GLOBALS['ecs']->table('cart') . " b + WHERE a.rec_id = '$key' + AND a.session_id = '" . SESS_ID . "' + AND a.extension_code <> 'package_buy' + AND b.parent_id = a.goods_id + AND b.session_id = '" . SESS_ID . "'"; + + $offers_accessories_res = $GLOBALS['db']->query($sql); + + //订货数量大于0 + if ($val > 0) + { + /* 判断是否为超出数量的优惠价格的配件 删除*/ + $row_num = 1; + while ($offers_accessories_row = $GLOBALS['db']->fetchRow($offers_accessories_res)) + { + if ($row_num > $val) + { + $sql = "DELETE FROM " . $GLOBALS['ecs']->table('cart') . + " WHERE session_id = '" . SESS_ID . "' " . + "AND rec_id = '" . $offers_accessories_row['rec_id'] ."' LIMIT 1"; + $GLOBALS['db']->query($sql); + } + + $row_num ++; + } + + /* 处理超值礼包 */ + if ($goods['extension_code'] == 'package_buy') + { + //更新购物车中的商品数量 + $sql = "UPDATE " .$GLOBALS['ecs']->table('cart'). + " SET goods_number = '$val' WHERE rec_id='$key' AND session_id='" . SESS_ID . "'"; + } + /* 处理普通商品或非优惠的配件 */ + else + { + $attr_id = empty($goods['goods_attr_id']) ? array() : explode(',', $goods['goods_attr_id']); + $goods_price = get_final_price($goods['goods_id'], $val, true, $attr_id); + + //更新购物车中的商品数量 + $sql = "UPDATE " .$GLOBALS['ecs']->table('cart'). + " SET goods_number = '$val', goods_price = '$goods_price' WHERE rec_id='$key' AND session_id='" . SESS_ID . "'"; + } + } + //订货数量等于0 + else + { + /* 如果是基本件并且有优惠价格的配件则删除优惠价格的配件 */ + while ($offers_accessories_row = $GLOBALS['db']->fetchRow($offers_accessories_res)) + { + $sql = "DELETE FROM " . $GLOBALS['ecs']->table('cart') . + " WHERE session_id = '" . SESS_ID . "' " . + "AND rec_id = '" . $offers_accessories_row['rec_id'] ."' LIMIT 1"; + $GLOBALS['db']->query($sql); + } + + $sql = "DELETE FROM " .$GLOBALS['ecs']->table('cart'). + " WHERE rec_id='$key' AND session_id='" .SESS_ID. "'"; + } + + $GLOBALS['db']->query($sql); + } + + /* 删除所有赠品 */ + $sql = "DELETE FROM " . $GLOBALS['ecs']->table('cart') . " WHERE session_id = '" .SESS_ID. "' AND is_gift <> 0"; + $GLOBALS['db']->query($sql); +} + +/** + * 检查订单中商品库存 + * + * @access public + * @param array $arr + * + * @return void + */ +function flow_cart_stock($arr) +{ + foreach ($arr AS $key => $val) + { + $val = intval(make_semiangle($val)); + if ($val <= 0) + { + continue; + } + + $sql = "SELECT `goods_id`, `goods_attr_id`, `extension_code` FROM" .$GLOBALS['ecs']->table('cart'). + " WHERE rec_id='$key' AND session_id='" . SESS_ID . "'"; + $goods = $GLOBALS['db']->getRow($sql); + + $sql = "SELECT g.goods_name, g.goods_number, c.product_id ". + "FROM " .$GLOBALS['ecs']->table('goods'). " AS g, ". + $GLOBALS['ecs']->table('cart'). " AS c ". + "WHERE g.goods_id = c.goods_id AND c.rec_id = '$key'"; + $row = $GLOBALS['db']->getRow($sql); + + //系统启用了库存,检查输入的商品数量是否有效 + if (intval($GLOBALS['_CFG']['use_storage']) > 0 && $goods['extension_code'] != 'package_buy') + { + if ($row['goods_number'] < $val) + { + show_message(sprintf($GLOBALS['_LANG']['stock_insufficiency'], $row['goods_name'], + $row['goods_number'], $row['goods_number'])); + exit; + } + + /* 是货品 */ + $row['product_id'] = trim($row['product_id']); + if (!empty($row['product_id'])) + { + $sql = "SELECT product_number FROM " .$GLOBALS['ecs']->table('products'). " WHERE goods_id = '" . $goods['goods_id'] . "' AND product_id = '" . $row['product_id'] . "'"; + $product_number = $GLOBALS['db']->getOne($sql); + if ($product_number < $val) + { + show_message(sprintf($GLOBALS['_LANG']['stock_insufficiency'], $row['goods_name'], + $row['goods_number'], $row['goods_number'])); + exit; + } + } + } + elseif (intval($GLOBALS['_CFG']['use_storage']) > 0 && $goods['extension_code'] == 'package_buy') + { + if (judge_package_stock($goods['goods_id'], $val)) + { + show_message($GLOBALS['_LANG']['package_stock_insufficiency']); + exit; + } + } + } + +} + +/** + * 删除购物车中的商品 + * + * @access public + * @param integer $id + * @return void + */ +function flow_drop_cart_goods($id) +{ + /* 取得商品id */ + $sql = "SELECT * FROM " .$GLOBALS['ecs']->table('cart'). " WHERE rec_id = '$id'"; + $row = $GLOBALS['db']->getRow($sql); + if ($row) + { + //如果是超值礼包 + if ($row['extension_code'] == 'package_buy') + { + $sql = "DELETE FROM " . $GLOBALS['ecs']->table('cart') . + " WHERE session_id = '" . SESS_ID . "' " . + "AND rec_id = '$id' LIMIT 1"; + } + + //如果是普通商品,同时删除所有赠品及其配件 + elseif ($row['parent_id'] == 0 && $row['is_gift'] == 0) + { + /* 检查购物车中该普通商品的不可单独销售的配件并删除 */ + $sql = "SELECT c.rec_id + FROM " . $GLOBALS['ecs']->table('cart') . " AS c, " . $GLOBALS['ecs']->table('group_goods') . " AS gg, " . $GLOBALS['ecs']->table('goods'). " AS g + WHERE gg.parent_id = '" . $row['goods_id'] . "' + AND c.goods_id = gg.goods_id + AND c.parent_id = '" . $row['goods_id'] . "' + AND c.extension_code <> 'package_buy' + AND gg.goods_id = g.goods_id + AND g.is_alone_sale = 0"; + $res = $GLOBALS['db']->query($sql); + $_del_str = $id . ','; + while ($id_alone_sale_goods = $GLOBALS['db']->fetchRow($res)) + { + $_del_str .= $id_alone_sale_goods['rec_id'] . ','; + } + $_del_str = trim($_del_str, ','); + + $sql = "DELETE FROM " . $GLOBALS['ecs']->table('cart') . + " WHERE session_id = '" . SESS_ID . "' " . + "AND (rec_id IN ($_del_str) OR parent_id = '$row[goods_id]' OR is_gift <> 0)"; + } + + //如果不是普通商品,只删除该商品即可 + else + { + $sql = "DELETE FROM " . $GLOBALS['ecs']->table('cart') . + " WHERE session_id = '" . SESS_ID . "' " . + "AND rec_id = '$id' LIMIT 1"; + } + + $GLOBALS['db']->query($sql); + } + + flow_clear_cart_alone(); +} + +/** + * 删除购物车中不能单独销售的商品 + * + * @access public + * @return void + */ +function flow_clear_cart_alone() +{ + /* 查询:购物车中所有不可以单独销售的配件 */ + $sql = "SELECT c.rec_id, gg.parent_id + FROM " . $GLOBALS['ecs']->table('cart') . " AS c + LEFT JOIN " . $GLOBALS['ecs']->table('group_goods') . " AS gg ON c.goods_id = gg.goods_id + LEFT JOIN" . $GLOBALS['ecs']->table('goods') . " AS g ON c.goods_id = g.goods_id + WHERE c.session_id = '" . SESS_ID . "' + AND c.extension_code <> 'package_buy' + AND gg.parent_id > 0 + AND g.is_alone_sale = 0"; + $res = $GLOBALS['db']->query($sql); + $rec_id = array(); + while ($row = $GLOBALS['db']->fetchRow($res)) + { + $rec_id[$row['rec_id']][] = $row['parent_id']; + } + + if (empty($rec_id)) + { + return; + } + + /* 查询:购物车中所有商品 */ + $sql = "SELECT DISTINCT goods_id + FROM " . $GLOBALS['ecs']->table('cart') . " + WHERE session_id = '" . SESS_ID . "' + AND extension_code <> 'package_buy'"; + $res = $GLOBALS['db']->query($sql); + $cart_good = array(); + while ($row = $GLOBALS['db']->fetchRow($res)) + { + $cart_good[] = $row['goods_id']; + } + + if (empty($cart_good)) + { + return; + } + + /* 如果购物车中不可以单独销售配件的基本件不存在则删除该配件 */ + $del_rec_id = ''; + foreach ($rec_id as $key => $value) + { + foreach ($value as $v) + { + if (in_array($v, $cart_good)) + { + continue 2; + } + } + + $del_rec_id = $key . ','; + } + $del_rec_id = trim($del_rec_id, ','); + + if ($del_rec_id == '') + { + return; + } + + /* 删除 */ + $sql = "DELETE FROM " . $GLOBALS['ecs']->table('cart') ." + WHERE session_id = '" . SESS_ID . "' + AND rec_id IN ($del_rec_id)"; + $GLOBALS['db']->query($sql); +} + +/** + * 比较优惠活动的函数,用于排序(把可用的排在前面) + * @param array $a 优惠活动a + * @param array $b 优惠活动b + * @return int 相等返回0,小于返回-1,大于返回1 + */ +function cmp_favourable($a, $b) +{ + if ($a['available'] == $b['available']) + { + if ($a['sort_order'] == $b['sort_order']) + { + return 0; + } + else + { + return $a['sort_order'] < $b['sort_order'] ? -1 : 1; + } + } + else + { + return $a['available'] ? -1 : 1; + } +} + +/** + * 取得某用户等级当前时间可以享受的优惠活动 + * @param int $user_rank 用户等级id,0表示非会员 + * @return array + */ +function favourable_list($user_rank) +{ + /* 购物车中已有的优惠活动及数量 */ + $used_list = cart_favourable(); + + /* 当前用户可享受的优惠活动 */ + $favourable_list = array(); + $user_rank = ',' . $user_rank . ','; + $now = gmtime(); + $sql = "SELECT * " . + "FROM " . $GLOBALS['ecs']->table('favourable_activity') . + " WHERE CONCAT(',', user_rank, ',') LIKE '%" . $user_rank . "%'" . + " AND start_time <= '$now' AND end_time >= '$now'" . + " AND act_type = '" . FAT_GOODS . "'" . + " ORDER BY sort_order"; + $res = $GLOBALS['db']->query($sql); + while ($favourable = $GLOBALS['db']->fetchRow($res)) + { + $favourable['start_time'] = local_date($GLOBALS['_CFG']['time_format'], $favourable['start_time']); + $favourable['end_time'] = local_date($GLOBALS['_CFG']['time_format'], $favourable['end_time']); + $favourable['formated_min_amount'] = price_format($favourable['min_amount'], false); + $favourable['formated_max_amount'] = price_format($favourable['max_amount'], false); + $favourable['gift'] = unserialize($favourable['gift']); + + foreach ($favourable['gift'] as $key => $value) + { + $favourable['gift'][$key]['formated_price'] = price_format($value['price'], false); + $sql = "SELECT COUNT(*) FROM " . $GLOBALS['ecs']->table('goods') . " WHERE is_on_sale = 1 AND goods_id = ".$value['id']; + $is_sale = $GLOBALS['db']->getOne($sql); + if(!$is_sale) + { + unset($favourable['gift'][$key]); + } + } + + $favourable['act_range_desc'] = act_range_desc($favourable); + $favourable['act_type_desc'] = sprintf($GLOBALS['_LANG']['fat_ext'][$favourable['act_type']], $favourable['act_type_ext']); + + /* 是否能享受 */ + $favourable['available'] = favourable_available($favourable); + if ($favourable['available']) + { + /* 是否尚未享受 */ + $favourable['available'] = !favourable_used($favourable, $used_list); + } + + $favourable_list[] = $favourable; + } + + return $favourable_list; +} + +/** + * 根据购物车判断是否可以享受某优惠活动 + * @param array $favourable 优惠活动信息 + * @return bool + */ +function favourable_available($favourable) +{ + /* 会员等级是否符合 */ + $user_rank = $_SESSION['user_rank']; + if (strpos(',' . $favourable['user_rank'] . ',', ',' . $user_rank . ',') === false) + { + return false; + } + + /* 优惠范围内的商品总额 */ + $amount = cart_favourable_amount($favourable); + + /* 金额上限为0表示没有上限 */ + return $amount >= $favourable['min_amount'] && + ($amount <= $favourable['max_amount'] || $favourable['max_amount'] == 0); +} + +/** + * 取得优惠范围描述 + * @param array $favourable 优惠活动 + * @return string + */ +function act_range_desc($favourable) +{ + if ($favourable['act_range'] == FAR_BRAND) + { + $sql = "SELECT brand_name FROM " . $GLOBALS['ecs']->table('brand') . + " WHERE brand_id " . db_create_in($favourable['act_range_ext']); + return join(',', $GLOBALS['db']->getCol($sql)); + } + elseif ($favourable['act_range'] == FAR_CATEGORY) + { + $sql = "SELECT cat_name FROM " . $GLOBALS['ecs']->table('category') . + " WHERE cat_id " . db_create_in($favourable['act_range_ext']); + return join(',', $GLOBALS['db']->getCol($sql)); + } + elseif ($favourable['act_range'] == FAR_GOODS) + { + $sql = "SELECT goods_name FROM " . $GLOBALS['ecs']->table('goods') . + " WHERE goods_id " . db_create_in($favourable['act_range_ext']); + return join(',', $GLOBALS['db']->getCol($sql)); + } + else + { + return ''; + } +} + +/** + * 取得购物车中已有的优惠活动及数量 + * @return array + */ +function cart_favourable() +{ + $list = array(); + $sql = "SELECT is_gift, COUNT(*) AS num " . + "FROM " . $GLOBALS['ecs']->table('cart') . + " WHERE session_id = '" . SESS_ID . "'" . + " AND rec_type = '" . CART_GENERAL_GOODS . "'" . + " AND is_gift > 0" . + " GROUP BY is_gift"; + $res = $GLOBALS['db']->query($sql); + while ($row = $GLOBALS['db']->fetchRow($res)) + { + $list[$row['is_gift']] = $row['num']; + } + + return $list; +} + +/** + * 购物车中是否已经有某优惠 + * @param array $favourable 优惠活动 + * @param array $cart_favourable购物车中已有的优惠活动及数量 + */ +function favourable_used($favourable, $cart_favourable) +{ + if ($favourable['act_type'] == FAT_GOODS) + { + return isset($cart_favourable[$favourable['act_id']]) && + $cart_favourable[$favourable['act_id']] >= $favourable['act_type_ext'] && + $favourable['act_type_ext'] > 0; + } + else + { + return isset($cart_favourable[$favourable['act_id']]); + } +} + +/** + * 添加优惠活动(赠品)到购物车 + * @param int $act_id 优惠活动id + * @param int $id 赠品id + * @param float $price 赠品价格 + */ +function add_gift_to_cart($act_id, $id, $price) +{ + $sql = "INSERT INTO " . $GLOBALS['ecs']->table('cart') . " (" . + "user_id, session_id, goods_id, goods_sn, goods_name, market_price, goods_price, ". + "goods_number, is_real, extension_code, parent_id, is_gift, rec_type ) ". + "SELECT '$_SESSION[user_id]', '" . SESS_ID . "', goods_id, goods_sn, goods_name, market_price, ". + "'$price', 1, is_real, extension_code, 0, '$act_id', '" . CART_GENERAL_GOODS . "' " . + "FROM " . $GLOBALS['ecs']->table('goods') . + " WHERE goods_id = '$id'"; + $GLOBALS['db']->query($sql); +} + +/** + * 添加优惠活动(非赠品)到购物车 + * @param int $act_id 优惠活动id + * @param string $act_name 优惠活动name + * @param float $amount 优惠金额 + */ +function add_favourable_to_cart($act_id, $act_name, $amount) +{ + $sql = "INSERT INTO " . $GLOBALS['ecs']->table('cart') . "(" . + "user_id, session_id, goods_id, goods_sn, goods_name, market_price, goods_price, ". + "goods_number, is_real, extension_code, parent_id, is_gift, rec_type ) ". + "VALUES('$_SESSION[user_id]', '" . SESS_ID . "', 0, '', '$act_name', 0, ". + "'" . (-1) * $amount . "', 1, 0, '', 0, '$act_id', '" . CART_GENERAL_GOODS . "')"; + $GLOBALS['db']->query($sql); +} + +/** + * 取得购物车中某优惠活动范围内的总金额 + * @param array $favourable 优惠活动 + * @return float + */ +function cart_favourable_amount($favourable) +{ + /* 查询优惠范围内商品总额的sql */ + $sql = "SELECT SUM(c.goods_price * c.goods_number) " . + "FROM " . $GLOBALS['ecs']->table('cart') . " AS c, " . $GLOBALS['ecs']->table('goods') . " AS g " . + "WHERE c.goods_id = g.goods_id " . + "AND c.session_id = '" . SESS_ID . "' " . + "AND c.rec_type = '" . CART_GENERAL_GOODS . "' " . + "AND c.is_gift = 0 " . + "AND c.goods_id > 0 "; + + /* 根据优惠范围修正sql */ + if ($favourable['act_range'] == FAR_ALL) + { + // sql do not change + } + elseif ($favourable['act_range'] == FAR_CATEGORY) + { + /* 取得优惠范围分类的所有下级分类 */ + $id_list = array(); + $cat_list = explode(',', $favourable['act_range_ext']); + foreach ($cat_list as $id) + { + $id_list = array_merge($id_list, array_keys(cat_list(intval($id), 0, false))); + } + + $sql .= "AND g.cat_id " . db_create_in($id_list); + } + elseif ($favourable['act_range'] == FAR_BRAND) + { + $id_list = explode(',', $favourable['act_range_ext']); + + $sql .= "AND g.brand_id " . db_create_in($id_list); + } + else + { + $id_list = explode(',', $favourable['act_range_ext']); + + $sql .= "AND g.goods_id " . db_create_in($id_list); + } + + /* 优惠范围内的商品总额 */ + return $GLOBALS['db']->getOne($sql); +} + + + +?> \ No newline at end of file diff --git a/gallery.php b/gallery.php new file mode 100644 index 0000000..14e6a24 --- /dev/null +++ b/gallery.php @@ -0,0 +1,68 @@ +table('goods') . "WHERE goods_id = '$_REQUEST[id]'"; +$goods_name = $db->getOne($sql); + +/* 如果该商品不存在,返回首页 */ +if ($goods_name === false) +{ + ecs_header("Location: ./\n"); + + exit; +} + +/* 获得所有的图片 */ +$sql = 'SELECT img_id, img_desc, thumb_url, img_url'. + ' FROM ' .$ecs->table('goods_gallery'). + " WHERE goods_id = '$_REQUEST[id]' ORDER BY img_id"; +$img_list = $db->getAll($sql); + +$img_count = count($img_list); + +$gallery = array('goods_name' => htmlspecialchars($goods_name, ENT_QUOTES), 'list' => array()); +if ($img_count == 0) +{ + /* 如果没有图片,返回商品详情页 */ + ecs_header('Location: goods.php?id=' . $_REQUEST['id'] . "\n"); + exit; +} +else +{ + foreach ($img_list AS $key => $img) + { + $gallery['list'][] = array( + 'gallery_thumb' => get_image_path($_REQUEST['id'], $img_list[$key]['thumb_url'], true, 'gallery'), + 'gallery' => get_image_path($_REQUEST['id'], $img_list[$key]['img_url'], false, 'gallery'), + 'img_desc' => $img_list[$key]['img_desc'] + ); + } +} + +$smarty->assign('shop_name', $_CFG['shop_name']); +$smarty->assign('watermark', str_replace('../', './', $_CFG['watermark'])); +$smarty->assign('gallery', $gallery); +$smarty->display('gallery.dwt'); + +?> \ No newline at end of file diff --git a/goods.php b/goods.php new file mode 100644 index 0000000..5bedcff --- /dev/null +++ b/goods.php @@ -0,0 +1,625 @@ +caching = true; +} + +$affiliate = unserialize($GLOBALS['_CFG']['affiliate']); +$smarty->assign('affiliate', $affiliate); + +/*------------------------------------------------------ */ +//-- INPUT +/*------------------------------------------------------ */ + +$goods_id = isset($_REQUEST['id']) ? intval($_REQUEST['id']) : 0; + +/*------------------------------------------------------ */ +//-- 改变属性、数量时重新计算商品价格 +/*------------------------------------------------------ */ + +if (!empty($_REQUEST['act']) && $_REQUEST['act'] == 'price') +{ + include('includes/cls_json.php'); + + $json = new JSON; + $res = array('err_msg' => '', 'result' => '', 'qty' => 1); + + $attr_id = isset($_REQUEST['attr']) ? explode(',', $_REQUEST['attr']) : array(); + $number = (isset($_REQUEST['number'])) ? intval($_REQUEST['number']) : 1; + + if ($goods_id == 0) + { + $res['err_msg'] = $_LANG['err_change_attr']; + $res['err_no'] = 1; + } + else + { + if ($number == 0) + { + $res['qty'] = $number = 1; + } + else + { + $res['qty'] = $number; + } + + $shop_price = get_final_price($goods_id, $number, true, $attr_id); + $res['result'] = price_format($shop_price * $number); + } + + die($json->encode($res)); +} + + +/*------------------------------------------------------ */ +//-- 商品购买记录ajax处理 +/*------------------------------------------------------ */ + +if (!empty($_REQUEST['act']) && $_REQUEST['act'] == 'gotopage') +{ + include('includes/cls_json.php'); + + $json = new JSON; + $res = array('err_msg' => '', 'result' => ''); + + $goods_id = isset($_REQUEST['id']) ? intval($_REQUEST['id']) : 0; + $page = (isset($_REQUEST['page'])) ? intval($_REQUEST['page']) : 1; + + if (!empty($goods_id)) + { + $need_cache = $GLOBALS['smarty']->caching; + $need_compile = $GLOBALS['smarty']->force_compile; + + $GLOBALS['smarty']->caching = false; + $GLOBALS['smarty']->force_compile = true; + + /* 商品购买记录 */ + $sql = 'SELECT u.user_name, og.goods_number, oi.add_time, IF(oi.order_status IN (2, 3, 4), 0, 1) AS order_status ' . + 'FROM ' . $ecs->table('order_info') . ' AS oi LEFT JOIN ' . $ecs->table('users') . ' AS u ON oi.user_id = u.user_id, ' . $ecs->table('order_goods') . ' AS og ' . + 'WHERE oi.order_id = og.order_id AND ' . time() . ' - oi.add_time < 2592000 AND og.goods_id = ' . $goods_id . ' ORDER BY oi.add_time DESC LIMIT ' . (($page > 1) ? ($page-1) : 0) * 5 . ',5'; + $bought_notes = $db->getAll($sql); + + foreach ($bought_notes as $key => $val) + { + $bought_notes[$key]['add_time'] = local_date("Y-m-d G:i:s", $val['add_time']); + } + + $sql = 'SELECT count(*) ' . + 'FROM ' . $ecs->table('order_info') . ' AS oi LEFT JOIN ' . $ecs->table('users') . ' AS u ON oi.user_id = u.user_id, ' . $ecs->table('order_goods') . ' AS og ' . + 'WHERE oi.order_id = og.order_id AND ' . time() . ' - oi.add_time < 2592000 AND og.goods_id = ' . $goods_id; + $count = $db->getOne($sql); + + + /* 商品购买记录分页样式 */ + $pager = array(); + $pager['page'] = $page; + $pager['size'] = $size = 5; + $pager['record_count'] = $count; + $pager['page_count'] = $page_count = ($count > 0) ? intval(ceil($count / $size)) : 1;; + $pager['page_first'] = "javascript:gotoBuyPage(1,$goods_id)"; + $pager['page_prev'] = $page > 1 ? "javascript:gotoBuyPage(" .($page-1). ",$goods_id)" : 'javascript:;'; + $pager['page_next'] = $page < $page_count ? 'javascript:gotoBuyPage(' .($page + 1) . ",$goods_id)" : 'javascript:;'; + $pager['page_last'] = $page < $page_count ? 'javascript:gotoBuyPage(' .$page_count. ",$goods_id)" : 'javascript:;'; + + $smarty->assign('notes', $bought_notes); + $smarty->assign('pager', $pager); + + + $res['result'] = $GLOBALS['smarty']->fetch('library/bought_notes.lbi'); + + $GLOBALS['smarty']->caching = $need_cache; + $GLOBALS['smarty']->force_compile = $need_compile; + } + + die($json->encode($res)); +} + + +/*------------------------------------------------------ */ +//-- PROCESSOR +/*------------------------------------------------------ */ + +$cache_id = $goods_id . '-' . $_SESSION['user_rank'].'-'.$_CFG['lang']; +$cache_id = sprintf('%X', crc32($cache_id)); +if (!$smarty->is_cached('goods.dwt', $cache_id)) +{ + $smarty->assign('image_width', $_CFG['image_width']); + $smarty->assign('image_height', $_CFG['image_height']); + $smarty->assign('helps', get_shop_help()); // 网店帮助 + $smarty->assign('id', $goods_id); + $smarty->assign('type', 0); + $smarty->assign('cfg', $_CFG); + $smarty->assign('promotion', get_promotion_info($goods_id));//促销信息 + $smarty->assign('promotion_info', get_promotion_info()); + + /* 获得商品的信息 */ + $goods = get_goods_info($goods_id); + + if ($goods === false) + { + /* 如果没有找到任何记录则跳回到首页 */ + ecs_header("Location: ./\n"); + exit; + } + else + { + if ($goods['brand_id'] > 0) + { + $goods['goods_brand_url'] = build_uri('brand', array('bid'=>$goods['brand_id']), $goods['goods_brand']); + } + + $shop_price = $goods['shop_price']; + $linked_goods = get_linked_goods($goods_id); + + $goods['goods_style_name'] = add_style($goods['goods_name'], $goods['goods_name_style']); + + /* 购买该商品可以得到多少钱的红包 */ + if ($goods['bonus_type_id'] > 0) + { + $time = gmtime(); + $sql = "SELECT type_money FROM " . $ecs->table('bonus_type') . + " WHERE type_id = '$goods[bonus_type_id]' " . + " AND send_type = '" . SEND_BY_GOODS . "' " . + " AND send_start_date <= '$time'" . + " AND send_end_date >= '$time'"; + $goods['bonus_money'] = floatval($db->getOne($sql)); + if ($goods['bonus_money'] > 0) + { + $goods['bonus_money'] = price_format($goods['bonus_money']); + } + } + + $smarty->assign('goods', $goods); + $smarty->assign('goods_id', $goods['goods_id']); + $smarty->assign('promote_end_time', $goods['gmt_end_time']); + $smarty->assign('categories', get_categories_tree()); // 分类树 + + /* meta */ + $smarty->assign('keywords', htmlspecialchars($goods['keywords'])); + $smarty->assign('description', htmlspecialchars($goods['goods_brief'])); + + + $catlist = array(); + foreach(get_parent_cats($goods['cat_id']) as $k=>$v) + { + $catlist[] = $v['cat_id']; + } + + assign_template('c', $catlist); + + /* 上一个商品下一个商品 */ + $prev_gid = $db->getOne("SELECT goods_id FROM " .$ecs->table('goods'). " WHERE cat_id=" . $goods['cat_id'] . " AND goods_id > " . $goods['goods_id'] . " AND is_on_sale = 1 AND is_alone_sale = 1 AND is_delete = 0 LIMIT 1"); + if (!empty($prev_gid)) + { + $prev_good['url'] = build_uri('goods', array('gid' => $prev_gid), $goods['goods_name']); + $smarty->assign('prev_good', $prev_good);//上一个商品 + } + + $next_gid = $db->getOne("SELECT max(goods_id) FROM " . $ecs->table('goods') . " WHERE cat_id=".$goods['cat_id']." AND goods_id < ".$goods['goods_id'] . " AND is_on_sale = 1 AND is_alone_sale = 1 AND is_delete = 0"); + if (!empty($next_gid)) + { + $next_good['url'] = build_uri('goods', array('gid' => $next_gid), $goods['goods_name']); + $smarty->assign('next_good', $next_good);//下一个商品 + } + + $position = assign_ur_here($goods['cat_id'], $goods['goods_name']); + + /* current position */ + $smarty->assign('page_title', $position['title']); // 页面标题 + $smarty->assign('ur_here', $position['ur_here']); // 当前位置 + + $properties = get_goods_properties($goods_id); // 获得商品的规格和属性 + + $smarty->assign('properties', $properties['pro']); // 商品属性 + $smarty->assign('specification', $properties['spe']); // 商品规格 + $smarty->assign('attribute_linked', get_same_attribute_goods($properties)); // 相同属性的关联商品 + $smarty->assign('related_goods', $linked_goods); // 关联商品 + $smarty->assign('goods_article_list', get_linked_articles($goods_id)); // 关联文章 + $smarty->assign('fittings', get_goods_fittings(array($goods_id))); // 配件 + $smarty->assign('rank_prices', get_user_rank_prices($goods_id, $shop_price)); // 会员等级价格 + $smarty->assign('pictures', get_goods_gallery($goods_id)); // 商品相册 + $smarty->assign('bought_goods', get_also_bought($goods_id)); // 购买了该商品的用户还购买了哪些商品 + $smarty->assign('goods_rank', get_goods_rank($goods_id)); // 商品的销售排名 + + //获取tag + $tag_array = get_tags($goods_id); + $smarty->assign('tags', $tag_array); // 商品的标记 + + //获取关联礼包 + $package_goods_list = get_package_goods_list($goods['goods_id']); + $smarty->assign('package_goods_list',$package_goods_list); // 获取关联礼包 + + assign_dynamic('goods'); + $volume_price_list = get_volume_price_list($goods['goods_id'], '1'); + $smarty->assign('volume_price_list',$volume_price_list); // 商品优惠价格区间 + } +} + +/* 记录浏览历史 */ +if (!empty($_COOKIE['ECS']['history'])) +{ + $history = explode(',', $_COOKIE['ECS']['history']); + + array_unshift($history, $goods_id); + $history = array_unique($history); + + while (count($history) > $_CFG['history_number']) + { + array_pop($history); + } + + setcookie('ECS[history]', implode(',', $history), gmtime() + 3600 * 24 * 30); +} +else +{ + setcookie('ECS[history]', $goods_id, gmtime() + 3600 * 24 * 30); +} + + +/* 更新点击次数 */ +$db->query('UPDATE ' . $ecs->table('goods') . " SET click_count = click_count + 1 WHERE goods_id = '$_REQUEST[id]'"); + +$smarty->assign('now_time', gmtime()); // 当前系统时间 +$smarty->display('goods.dwt', $cache_id); + +/*------------------------------------------------------ */ +//-- PRIVATE FUNCTION +/*------------------------------------------------------ */ + +/** + * 获得指定商品的关联商品 + * + * @access public + * @param integer $goods_id + * @return array + */ +function get_linked_goods($goods_id) +{ + $sql = 'SELECT g.goods_id, g.goods_name, g.goods_thumb, g.goods_img, g.shop_price AS org_price, ' . + "IFNULL(mp.user_price, g.shop_price * '$_SESSION[discount]') AS shop_price, ". + 'g.market_price, g.promote_price, g.promote_start_date, g.promote_end_date ' . + 'FROM ' . $GLOBALS['ecs']->table('link_goods') . ' lg ' . + 'LEFT JOIN ' . $GLOBALS['ecs']->table('goods') . ' AS g ON g.goods_id = lg.link_goods_id ' . + "LEFT JOIN " . $GLOBALS['ecs']->table('member_price') . " AS mp ". + "ON mp.goods_id = g.goods_id AND mp.user_rank = '$_SESSION[user_rank]' ". + "WHERE lg.goods_id = '$goods_id' AND g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0 ". + "LIMIT " . $GLOBALS['_CFG']['related_goods_number']; + $res = $GLOBALS['db']->query($sql); + + $arr = array(); + while ($row = $GLOBALS['db']->fetchRow($res)) + { + $arr[$row['goods_id']]['goods_id'] = $row['goods_id']; + $arr[$row['goods_id']]['goods_name'] = $row['goods_name']; + $arr[$row['goods_id']]['short_name'] = $GLOBALS['_CFG']['goods_name_length'] > 0 ? + sub_str($row['goods_name'], $GLOBALS['_CFG']['goods_name_length']) : $row['goods_name']; + $arr[$row['goods_id']]['goods_thumb'] = get_image_path($row['goods_id'], $row['goods_thumb'], true); + $arr[$row['goods_id']]['goods_img'] = get_image_path($row['goods_id'], $row['goods_img']); + $arr[$row['goods_id']]['market_price'] = price_format($row['market_price']); + $arr[$row['goods_id']]['shop_price'] = price_format($row['shop_price']); + $arr[$row['goods_id']]['url'] = build_uri('goods', array('gid'=>$row['goods_id']), $row['goods_name']); + + if ($row['promote_price'] > 0) + { + $arr[$row['goods_id']]['promote_price'] = bargain_price($row['promote_price'], $row['promote_start_date'], $row['promote_end_date']); + $arr[$row['goods_id']]['formated_promote_price'] = price_format($arr[$row['goods_id']]['promote_price']); + } + else + { + $arr[$row['goods_id']]['promote_price'] = 0; + } + } + + return $arr; +} + +/** + * 获得指定商品的关联文章 + * + * @access public + * @param integer $goods_id + * @return void + */ +function get_linked_articles($goods_id) +{ + $sql = 'SELECT a.article_id, a.title, a.file_url, a.open_type, a.add_time ' . + 'FROM ' . $GLOBALS['ecs']->table('goods_article') . ' AS g, ' . + $GLOBALS['ecs']->table('article') . ' AS a ' . + "WHERE g.article_id = a.article_id AND g.goods_id = '$goods_id' AND a.is_open = 1 " . + 'ORDER BY a.add_time DESC'; + $res = $GLOBALS['db']->query($sql); + + $arr = array(); + while ($row = $GLOBALS['db']->fetchRow($res)) + { + $row['url'] = $row['open_type'] != 1 ? + build_uri('article', array('aid'=>$row['article_id']), $row['title']) : trim($row['file_url']); + $row['add_time'] = local_date($GLOBALS['_CFG']['date_format'], $row['add_time']); + $row['short_title'] = $GLOBALS['_CFG']['article_title_length'] > 0 ? + sub_str($row['title'], $GLOBALS['_CFG']['article_title_length']) : $row['title']; + + $arr[] = $row; + } + + return $arr; +} + +/** + * 获得指定商品的各会员等级对应的价格 + * + * @access public + * @param integer $goods_id + * @return array + */ +function get_user_rank_prices($goods_id, $shop_price) +{ + $sql = "SELECT rank_id, IFNULL(mp.user_price, r.discount * $shop_price / 100) AS price, r.rank_name, r.discount " . + 'FROM ' . $GLOBALS['ecs']->table('user_rank') . ' AS r ' . + 'LEFT JOIN ' . $GLOBALS['ecs']->table('member_price') . " AS mp ". + "ON mp.goods_id = '$goods_id' AND mp.user_rank = r.rank_id " . + "WHERE r.show_price = 1 OR r.rank_id = '$_SESSION[user_rank]'"; + $res = $GLOBALS['db']->query($sql); + + $arr = array(); + while ($row = $GLOBALS['db']->fetchRow($res)) + { + + $arr[$row['rank_id']] = array( + 'rank_name' => htmlspecialchars($row['rank_name']), + 'price' => price_format($row['price'])); + } + + return $arr; +} + +/** + * 获得购买过该商品的人还买过的商品 + * + * @access public + * @param integer $goods_id + * @return array + */ +function get_also_bought($goods_id) +{ + $sql = 'SELECT COUNT(b.goods_id ) AS num, g.goods_id, g.goods_name, g.goods_thumb, g.goods_img, g.shop_price, g.promote_price, g.promote_start_date, g.promote_end_date ' . + 'FROM ' . $GLOBALS['ecs']->table('order_goods') . ' AS a ' . + 'LEFT JOIN ' . $GLOBALS['ecs']->table('order_goods') . ' AS b ON b.order_id = a.order_id ' . + 'LEFT JOIN ' . $GLOBALS['ecs']->table('goods') . ' AS g ON g.goods_id = b.goods_id ' . + "WHERE a.goods_id = '$goods_id' AND b.goods_id <> '$goods_id' AND g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0 " . + 'GROUP BY b.goods_id ' . + 'ORDER BY num DESC ' . + 'LIMIT ' . $GLOBALS['_CFG']['bought_goods']; + $res = $GLOBALS['db']->query($sql); + + $key = 0; + $arr = array(); + while ($row = $GLOBALS['db']->fetchRow($res)) + { + $arr[$key]['goods_id'] = $row['goods_id']; + $arr[$key]['goods_name'] = $row['goods_name']; + $arr[$key]['short_name'] = $GLOBALS['_CFG']['goods_name_length'] > 0 ? + sub_str($row['goods_name'], $GLOBALS['_CFG']['goods_name_length']) : $row['goods_name']; + $arr[$key]['goods_thumb'] = get_image_path($row['goods_id'], $row['goods_thumb'], true); + $arr[$key]['goods_img'] = get_image_path($row['goods_id'], $row['goods_img']); + $arr[$key]['shop_price'] = price_format($row['shop_price']); + $arr[$key]['url'] = build_uri('goods', array('gid'=>$row['goods_id']), $row['goods_name']); + + if ($row['promote_price'] > 0) + { + $arr[$key]['promote_price'] = bargain_price($row['promote_price'], $row['promote_start_date'], $row['promote_end_date']); + $arr[$key]['formated_promote_price'] = price_format($arr[$key]['promote_price']); + } + else + { + $arr[$key]['promote_price'] = 0; + } + + $key++; + } + + return $arr; +} + +/** + * 获得指定商品的销售排名 + * + * @access public + * @param integer $goods_id + * @return integer + */ +function get_goods_rank($goods_id) +{ + /* 统计时间段 */ + $period = intval($GLOBALS['_CFG']['top10_time']); + if ($period == 1) // 一年 + { + $ext = " AND o.add_time > '" . local_strtotime('-1 years') . "'"; + } + elseif ($period == 2) // 半年 + { + $ext = " AND o.add_time > '" . local_strtotime('-6 months') . "'"; + } + elseif ($period == 3) // 三个月 + { + $ext = " AND o.add_time > '" . local_strtotime('-3 months') . "'"; + } + elseif ($period == 4) // 一个月 + { + $ext = " AND o.add_time > '" . local_strtotime('-1 months') . "'"; + } + else + { + $ext = ''; + } + + /* 查询该商品销量 */ + $sql = 'SELECT IFNULL(SUM(g.goods_number), 0) ' . + 'FROM ' . $GLOBALS['ecs']->table('order_info') . ' AS o, ' . + $GLOBALS['ecs']->table('order_goods') . ' AS g ' . + "WHERE o.order_id = g.order_id " . + "AND o.order_status = '" . OS_CONFIRMED . "' " . + "AND o.shipping_status " . db_create_in(array(SS_SHIPPED, SS_RECEIVED)) . + " AND o.pay_status " . db_create_in(array(PS_PAYED, PS_PAYING)) . + " AND g.goods_id = '$goods_id'" . $ext; + $sales_count = $GLOBALS['db']->getOne($sql); + + if ($sales_count > 0) + { + /* 只有在商品销售量大于0时才去计算该商品的排行 */ + $sql = 'SELECT DISTINCT SUM(goods_number) AS num ' . + 'FROM ' . $GLOBALS['ecs']->table('order_info') . ' AS o, ' . + $GLOBALS['ecs']->table('order_goods') . ' AS g ' . + "WHERE o.order_id = g.order_id " . + "AND o.order_status = '" . OS_CONFIRMED . "' " . + "AND o.shipping_status " . db_create_in(array(SS_SHIPPED, SS_RECEIVED)) . + " AND o.pay_status " . db_create_in(array(PS_PAYED, PS_PAYING)) . $ext . + " GROUP BY g.goods_id HAVING num > $sales_count"; + $res = $GLOBALS['db']->query($sql); + + $rank = $GLOBALS['db']->num_rows($res) + 1; + + if ($rank > 10) + { + $rank = 0; + } + } + else + { + $rank = 0; + } + + return $rank; +} + +/** + * 获得商品选定的属性的附加总价格 + * + * @param integer $goods_id + * @param array $attr + * + * @return void + */ +function get_attr_amount($goods_id, $attr) +{ + $sql = "SELECT SUM(attr_price) FROM " . $GLOBALS['ecs']->table('goods_attr') . + " WHERE goods_id='$goods_id' AND " . db_create_in($attr, 'goods_attr_id'); + + return $GLOBALS['db']->getOne($sql); +} + +/** + * 取得跟商品关联的礼包列表 + * + * @param string $goods_id 商品编号 + * + * @return 礼包列表 + */ +function get_package_goods_list($goods_id) +{ + $now = gmtime(); + $sql = "SELECT pg.goods_id, ga.act_id, ga.act_name, ga.act_desc, ga.goods_name, ga.start_time, + ga.end_time, ga.is_finished, ga.ext_info + FROM " . $GLOBALS['ecs']->table('goods_activity') . " AS ga, " . $GLOBALS['ecs']->table('package_goods') . " AS pg + WHERE pg.package_id = ga.act_id + AND ga.start_time <= '" . $now . "' + AND ga.end_time >= '" . $now . "' + AND pg.goods_id = " . $goods_id . " + GROUP BY ga.act_id + ORDER BY ga.act_id "; + $res = $GLOBALS['db']->getAll($sql); + + foreach ($res as $tempkey => $value) + { + $subtotal = 0; + $row = unserialize($value['ext_info']); + unset($value['ext_info']); + if ($row) + { + foreach ($row as $key=>$val) + { + $res[$tempkey][$key] = $val; + } + } + + $sql = "SELECT pg.package_id, pg.goods_id, pg.goods_number, pg.admin_id, p.goods_attr, g.goods_sn, g.goods_name, g.market_price, g.goods_thumb, IFNULL(mp.user_price, g.shop_price * '$_SESSION[discount]') AS rank_price + FROM " . $GLOBALS['ecs']->table('package_goods') . " AS pg + LEFT JOIN ". $GLOBALS['ecs']->table('goods') . " AS g + ON g.goods_id = pg.goods_id + LEFT JOIN ". $GLOBALS['ecs']->table('products') . " AS p + ON p.product_id = pg.product_id + LEFT JOIN " . $GLOBALS['ecs']->table('member_price') . " AS mp + ON mp.goods_id = g.goods_id AND mp.user_rank = '$_SESSION[user_rank]' + WHERE pg.package_id = " . $value['act_id']. " + ORDER BY pg.package_id, pg.goods_id"; + + $goods_res = $GLOBALS['db']->getAll($sql); + + foreach($goods_res as $key => $val) + { + $goods_id_array[] = $val['goods_id']; + $goods_res[$key]['goods_thumb'] = get_image_path($val['goods_id'], $val['goods_thumb'], true); + $goods_res[$key]['market_price'] = price_format($val['market_price']); + $goods_res[$key]['rank_price'] = price_format($val['rank_price']); + $subtotal += $val['rank_price'] * $val['goods_number']; + } + + /* 取商品属性 */ + $sql = "SELECT ga.goods_attr_id, ga.attr_value + FROM " .$GLOBALS['ecs']->table('goods_attr'). " AS ga, " .$GLOBALS['ecs']->table('attribute'). " AS a + WHERE a.attr_id = ga.attr_id + AND a.attr_type = 1 + AND " . db_create_in($goods_id_array, 'goods_id'); + $result_goods_attr = $GLOBALS['db']->getAll($sql); + + $_goods_attr = array(); + foreach ($result_goods_attr as $value) + { + $_goods_attr[$value['goods_attr_id']] = $value['attr_value']; + } + + /* 处理货品 */ + $format = '[%s]'; + foreach($goods_res as $key => $val) + { + if ($val['goods_attr'] != '') + { + $goods_attr_array = explode('|', $val['goods_attr']); + + $goods_attr = array(); + foreach ($goods_attr_array as $_attr) + { + $goods_attr[] = $_goods_attr[$_attr]; + } + + $goods_res[$key]['goods_attr_str'] = sprintf($format, implode(',', $goods_attr)); + } + } + + $res[$tempkey]['goods_list'] = $goods_res; + $res[$tempkey]['subtotal'] = price_format($subtotal); + $res[$tempkey]['saving'] = price_format(($subtotal - $res[$tempkey]['package_price'])); + $res[$tempkey]['package_price'] = price_format($res[$tempkey]['package_price']); + } + + return $res; +} + +?> \ No newline at end of file diff --git a/goods_script.php b/goods_script.php new file mode 100644 index 0000000..15f82ac --- /dev/null +++ b/goods_script.php @@ -0,0 +1,158 @@ +caching = true; +} + +$charset = empty($_GET['charset']) ? EC_CHARSET : $_GET['charset']; +$type = empty($_GET['type']) ? '' : 'collection'; +if (strtolower($charset) == 'gb2312') +{ + $charset = 'gbk'; +} +header('content-type: application/x-javascript; charset=' . ($charset == 'UTF8' ? 'utf-8' : $charset)); + +/*------------------------------------------------------ */ +//-- 判断是否存在缓存,如果存在则调用缓存,反之读取相应内容 +/*------------------------------------------------------ */ +/* 缓存编号 */ +$cache_id = sprintf('%X', crc32($_SERVER['QUERY_STRING'])); + +$tpl = ROOT_PATH . DATA_DIR . '/goods_script.html'; +if (!$smarty->is_cached($tpl, $cache_id)) +{ + $time = gmtime(); + $sql=''; + /* 根据参数生成查询语句 */ + if ($type == '') + { + $sitename = !empty($_GET['sitename']) ? $_GET['sitename'] : ''; + $_from = (!empty($_GET['charset']) && $_GET['charset'] != 'UTF8')? urlencode(ecs_iconv('UTF-8', 'GBK', $sitename)) : urlencode(@$sitename); + $goods_url = $ecs->url() . 'affiche.php?ad_id=-1&from=' . $_from . '&goods_id='; + + $sql = 'SELECT goods_id, goods_name, market_price, goods_thumb, RAND() AS rnd, ' . + "IF(is_promote = 1 AND '$time' >= promote_start_date AND ". + "'$time' <= promote_end_date, promote_price, shop_price) AS goods_price " . + 'FROM ' . $ecs->table('goods') . ' AS g ' . + "WHERE is_delete = '0' AND is_on_sale = '1' AND is_alone_sale = '1' "; + if (!empty($_GET['cat_id'])) + { + $sql .= ' AND ' . get_children(intval($_GET['cat_id'])); + } + if (!empty($_GET['brand_id'])) + { + $sql .= " AND brand_id = '" . intval($_GET['brand_id']) . "'"; + } + if (!empty($_GET['intro_type'])) + { + $_GET['intro_type'] = trim($_GET['intro_type']); + + if ($_GET['intro_type'] == 'is_best' || $_GET['intro_type'] == 'is_new' || $_GET['intro_type'] == 'is_hot' || $_GET['intro_type'] == 'is_promote' || $_GET['intro_type'] == 'is_random') + { + if ($_GET['intro_type'] == 'is_random') + { + $sql .= ' ORDER BY rnd'; + } + else + { + if ($_GET['intro_type'] == 'is_promote') + { + $sql .= " AND promote_start_date <= '$time' AND promote_end_date >= '$time'"; + } + $sql .= " AND " . $_GET['intro_type'] . " = 1 ORDER BY add_time DESC"; + } + } + } + } + elseif ($type == 'collection') + { + $uid = (int)$_GET['u']; + $goods_url = $ecs->url() . "goods.php?u=$uid&id="; + $sql = "SELECT g.goods_id, g.goods_name, g.market_price, g.goods_thumb, IF(g.is_promote = 1 AND '$time' >= g.promote_start_date AND ". + "'$time' <= g.promote_end_date, g.promote_price, g.shop_price) AS goods_price FROM " . $ecs->table('goods') . " g LEFT JOIN " . $ecs->table('collect_goods') . " c ON g.goods_id = c.goods_id " . + " WHERE c.user_id = '$uid'"; + } + $sql .= " LIMIT " . (!empty($_GET['goods_num']) ? intval($_GET['goods_num']) : 10); + $res = $db->query($sql); + + $goods_list = array(); + while ($goods = $db->fetchRow($res)) + { + // 转换编码 + $goods['goods_price'] = price_format($goods['goods_price']); + if ($charset != EC_CHARSET) + { + if (EC_CHARSET == 'gbk') + { + $tmp_goods_name = htmlentities($goods['goods_name'], ENT_QUOTES, 'gb2312'); + } + else + { + $tmp_goods_name = htmlentities($goods['goods_name'], ENT_QUOTES, EC_CHARSET); + } + $goods['goods_name'] = ecs_iconv(EC_CHARSET, $charset, $tmp_goods_name); + $goods['goods_price'] = ecs_iconv(EC_CHARSET, $charset, $goods['goods_price']); + } + $goods['goods_name'] = $GLOBALS['_CFG']['goods_name_length'] > 0 ? sub_str($goods['goods_name'], $GLOBALS['_CFG']['goods_name_length']) : $goods['goods_name']; + $goods['goods_thumb'] = get_image_path($goods['goods_id'], $goods['goods_thumb'], true); + $goods_list[] = $goods; + } + + /* 排列方式 */ + $arrange = empty($_GET['arrange']) || !in_array($_GET['arrange'], array('h', 'v')) ? 'h' : $_GET['arrange']; + + /* 排列显示条目个数 */ + $goods_num = !empty($_GET['goods_num']) ? intval($_GET['goods_num']) : 10; + $rows_num = !empty($_GET['rows_num']) ? intval($_GET['rows_num']) : '1'; + if($arrange == 'h') + { + $goods_items = array_chunk($goods_list,$rows_num); + } + else + { + $columns_num = ceil($goods_num / $rows_num); + $goods_items = array_chunk($goods_list,$columns_num); + } + $smarty->assign('goods_list', $goods_items); + + + /* 是否需要图片 */ + $need_image = empty($_GET['need_image']) || $_GET['need_image'] == 'true' ? 1 : 0; + $smarty->assign('need_image', $need_image); + + /* 图片大小 */ + $smarty->assign('thumb_width', intval($_CFG['thumb_width'])); + $smarty->assign('thumb_height', intval($_CFG['thumb_height'])); + + /* 网站根目录 */ + $smarty->assign('url', $ecs->url()); + + /* 商品页面连接 */ + $smarty->assign('goods_url', $goods_url); +} +$output = $smarty->fetch($tpl, $cache_id); +$output = str_replace("\r", '', $output); +$output = str_replace("\n", '', $output); + +echo "document.write('$output');"; + +?> diff --git a/group_buy.php b/group_buy.php new file mode 100644 index 0000000..c8e4024 --- /dev/null +++ b/group_buy.php @@ -0,0 +1,375 @@ +caching = true; +} + +/*------------------------------------------------------ */ +//-- act 操作项的初始化 +/*------------------------------------------------------ */ +if (empty($_REQUEST['act'])) +{ + $_REQUEST['act'] = 'list'; +} + +/*------------------------------------------------------ */ +//-- 团购商品 --> 团购活动商品列表 +/*------------------------------------------------------ */ +if ($_REQUEST['act'] == 'list') +{ + /* 取得团购活动总数 */ + $count = group_buy_count(); + if ($count > 0) + { + /* 取得每页记录数 */ + $size = isset($_CFG['page_size']) && intval($_CFG['page_size']) > 0 ? intval($_CFG['page_size']) : 10; + + /* 计算总页数 */ + $page_count = ceil($count / $size); + + /* 取得当前页 */ + $page = isset($_REQUEST['page']) && intval($_REQUEST['page']) > 0 ? intval($_REQUEST['page']) : 1; + $page = $page > $page_count ? $page_count : $page; + + /* 缓存id:语言 - 每页记录数 - 当前页 */ + $cache_id = $_CFG['lang'] . '-' . $size . '-' . $page; + $cache_id = sprintf('%X', crc32($cache_id)); + } + else + { + /* 缓存id:语言 */ + $cache_id = $_CFG['lang']; + $cache_id = sprintf('%X', crc32($cache_id)); + } + + /* 如果没有缓存,生成缓存 */ + if (!$smarty->is_cached('group_buy_list.dwt', $cache_id)) + { + if ($count > 0) + { + /* 取得当前页的团购活动 */ + $gb_list = group_buy_list($size, $page); + $smarty->assign('gb_list', $gb_list); + + /* 设置分页链接 */ + $pager = get_pager('group_buy.php', array('act' => 'list'), $count, $page, $size); + $smarty->assign('pager', $pager); + } + + /* 模板赋值 */ + $smarty->assign('cfg', $_CFG); + assign_template(); + $position = assign_ur_here(); + $smarty->assign('page_title', $position['title']); // 页面标题 + $smarty->assign('ur_here', $position['ur_here']); // 当前位置 + $smarty->assign('categories', get_categories_tree()); // 分类树 + $smarty->assign('helps', get_shop_help()); // 网店帮助 + $smarty->assign('top_goods', get_top10()); // 销售排行 + $smarty->assign('promotion_info', get_promotion_info()); + $smarty->assign('feed_url', ($_CFG['rewrite'] == 1) ? "feed-typegroup_buy.xml" : 'feed.php?type=group_buy'); // RSS URL + + assign_dynamic('group_buy_list'); + } + + /* 显示模板 */ + $smarty->display('group_buy_list.dwt', $cache_id); +} + +/*------------------------------------------------------ */ +//-- 团购商品 --> 商品详情 +/*------------------------------------------------------ */ +elseif ($_REQUEST['act'] == 'view') +{ + /* 取得参数:团购活动id */ + $group_buy_id = isset($_REQUEST['id']) ? intval($_REQUEST['id']) : 0; + if ($group_buy_id <= 0) + { + ecs_header("Location: ./\n"); + exit; + } + + /* 取得团购活动信息 */ + $group_buy = group_buy_info($group_buy_id); + + if (empty($group_buy)) + { + ecs_header("Location: ./\n"); + exit; + } +// elseif ($group_buy['is_on_sale'] == 0 || $group_buy['is_alone_sale'] == 0) +// { +// header("Location: ./\n"); +// exit; +// } + + /* 缓存id:语言,团购活动id,状态,(如果是进行中)当前数量和是否登录 */ + $cache_id = $_CFG['lang'] . '-' . $group_buy_id . '-' . $group_buy['status']; + if ($group_buy['status'] == GBS_UNDER_WAY) + { + $cache_id = $cache_id . '-' . $group_buy['valid_goods'] . '-' . intval($_SESSION['user_id'] > 0); + } + $cache_id = sprintf('%X', crc32($cache_id)); + + /* 如果没有缓存,生成缓存 */ + if (!$smarty->is_cached('group_buy_goods.dwt', $cache_id)) + { + $group_buy['gmt_end_date'] = $group_buy['end_date']; + $smarty->assign('group_buy', $group_buy); + + /* 取得团购商品信息 */ + $goods_id = $group_buy['goods_id']; + $goods = goods_info($goods_id); + if (empty($goods)) + { + ecs_header("Location: ./\n"); + exit; + } + $goods['url'] = build_uri('goods', array('gid' => $goods_id), $goods['goods_name']); + $smarty->assign('gb_goods', $goods); + + /* 取得商品的规格 */ + $properties = get_goods_properties($goods_id); + $smarty->assign('specification', $properties['spe']); // 商品规格 + + //模板赋值 + $smarty->assign('cfg', $_CFG); + assign_template(); + + $position = assign_ur_here(0, $goods['goods_name']); + $smarty->assign('page_title', $position['title']); // 页面标题 + $smarty->assign('ur_here', $position['ur_here']); // 当前位置 + + $smarty->assign('categories', get_categories_tree()); // 分类树 + $smarty->assign('helps', get_shop_help()); // 网店帮助 + $smarty->assign('top_goods', get_top10()); // 销售排行 + $smarty->assign('promotion_info', get_promotion_info()); + assign_dynamic('group_buy_goods'); + } + + //更新商品点击次数 + $sql = 'UPDATE ' . $ecs->table('goods') . ' SET click_count = click_count + 1 '. + "WHERE goods_id = '" . $group_buy['goods_id'] . "'"; + $db->query($sql); + + $smarty->assign('now_time', gmtime()); // 当前系统时间 + $smarty->display('group_buy_goods.dwt', $cache_id); +} + +/*------------------------------------------------------ */ +//-- 团购商品 --> 购买 +/*------------------------------------------------------ */ + +elseif ($_REQUEST['act'] == 'buy') +{ + /* 查询:判断是否登录 */ + if ($_SESSION['user_id'] <= 0) + { + show_message($_LANG['gb_error_login'], '', '', 'error'); + } + + /* 查询:取得参数:团购活动id */ + $group_buy_id = isset($_POST['group_buy_id']) ? intval($_POST['group_buy_id']) : 0; + if ($group_buy_id <= 0) + { + ecs_header("Location: ./\n"); + exit; + } + + /* 查询:取得数量 */ + $number = isset($_POST['number']) ? intval($_POST['number']) : 1; + $number = $number < 1 ? 1 : $number; + + /* 查询:取得团购活动信息 */ + $group_buy = group_buy_info($group_buy_id, $number); + if (empty($group_buy)) + { + ecs_header("Location: ./\n"); + exit; + } + + /* 查询:检查团购活动是否是进行中 */ + if ($group_buy['status'] != GBS_UNDER_WAY) + { + show_message($_LANG['gb_error_status'], '', '', 'error'); + } + + /* 查询:取得团购商品信息 */ + $goods = goods_info($group_buy['goods_id']); + if (empty($goods)) + { + ecs_header("Location: ./\n"); + exit; + } + + /* 查询:判断数量是否足够 */ + if (($group_buy['restrict_amount'] > 0 && $number > ($group_buy['restrict_amount'] - $group_buy['valid_goods'])) || $number > $goods['goods_number']) + { + show_message($_LANG['gb_error_goods_lacking'], '', '', 'error'); + } + + /* 查询:取得规格 */ + $specs = ''; + foreach ($_POST as $key => $value) + { + if (strpos($key, 'spec_') !== false) + { + $specs .= ',' . intval($value); + } + } + $specs = trim($specs, ','); + + /* 查询:如果商品有规格则取规格商品信息 配件除外 */ + if ($specs) + { + $_specs = explode(',', $specs); + $product_info = get_products_info($goods['goods_id'], $_specs); + } + + empty($product_info) ? $product_info = array('product_number' => 0, 'product_id' => 0) : ''; + + /* 查询:判断指定规格的货品数量是否足够 */ + if ($specs && $number > $product_info['product_number']) + { + show_message($_LANG['gb_error_goods_lacking'], '', '', 'error'); + } + + /* 查询:查询规格名称和值,不考虑价格 */ + $attr_list = array(); + $sql = "SELECT a.attr_name, g.attr_value " . + "FROM " . $ecs->table('goods_attr') . " AS g, " . + $ecs->table('attribute') . " AS a " . + "WHERE g.attr_id = a.attr_id " . + "AND g.goods_attr_id " . db_create_in($specs); + $res = $db->query($sql); + while ($row = $db->fetchRow($res)) + { + $attr_list[] = $row['attr_name'] . ': ' . $row['attr_value']; + } + $goods_attr = join(chr(13) . chr(10), $attr_list); + + /* 更新:清空购物车中所有团购商品 */ + include_once(ROOT_PATH . 'includes/lib_order.php'); + clear_cart(CART_GROUP_BUY_GOODS); + + /* 更新:加入购物车 */ + $goods_price = $group_buy['deposit'] > 0 ? $group_buy['deposit'] : $group_buy['cur_price']; + $cart = array( + 'user_id' => $_SESSION['user_id'], + 'session_id' => SESS_ID, + 'goods_id' => $group_buy['goods_id'], + 'product_id' => $product_info['product_id'], + 'goods_sn' => addslashes($goods['goods_sn']), + 'goods_name' => addslashes($goods['goods_name']), + 'market_price' => $goods['market_price'], + 'goods_price' => $goods_price, + 'goods_number' => $number, + 'goods_attr' => addslashes($goods_attr), + 'goods_attr_id' => $specs, + 'is_real' => $goods['is_real'], + 'extension_code' => addslashes($goods['extension_code']), + 'parent_id' => 0, + 'rec_type' => CART_GROUP_BUY_GOODS, + 'is_gift' => 0 + ); + $db->autoExecute($ecs->table('cart'), $cart, 'INSERT'); + + /* 更新:记录购物流程类型:团购 */ + $_SESSION['flow_type'] = CART_GROUP_BUY_GOODS; + $_SESSION['extension_code'] = 'group_buy'; + $_SESSION['extension_id'] = $group_buy_id; + + /* 进入收货人页面 */ + ecs_header("Location: ./flow.php?step=consignee\n"); + exit; +} + +/* 取得团购活动总数 */ +function group_buy_count() +{ + $now = gmtime(); + $sql = "SELECT COUNT(*) " . + "FROM " . $GLOBALS['ecs']->table('goods_activity') . + "WHERE act_type = '" . GAT_GROUP_BUY . "' " . + "AND start_time <= '$now' AND is_finished < 3"; + + return $GLOBALS['db']->getOne($sql); +} + +/** + * 取得某页的所有团购活动 + * @param int $size 每页记录数 + * @param int $page 当前页 + * @return array + */ +function group_buy_list($size, $page) +{ + /* 取得团购活动 */ + $gb_list = array(); + $now = gmtime(); + $sql = "SELECT b.*, IFNULL(g.goods_thumb, '') AS goods_thumb, b.act_id AS group_buy_id, ". + "b.start_time AS start_date, b.end_time AS end_date " . + "FROM " . $GLOBALS['ecs']->table('goods_activity') . " AS b " . + "LEFT JOIN " . $GLOBALS['ecs']->table('goods') . " AS g ON b.goods_id = g.goods_id " . + "WHERE b.act_type = '" . GAT_GROUP_BUY . "' " . + "AND b.start_time <= '$now' AND b.is_finished < 3 ORDER BY b.act_id DESC"; + $res = $GLOBALS['db']->selectLimit($sql, $size, ($page - 1) * $size); + while ($group_buy = $GLOBALS['db']->fetchRow($res)) + { + $ext_info = unserialize($group_buy['ext_info']); + $group_buy = array_merge($group_buy, $ext_info); + + /* 格式化时间 */ + $group_buy['formated_start_date'] = local_date($GLOBALS['_CFG']['time_format'], $group_buy['start_date']); + $group_buy['formated_end_date'] = local_date($GLOBALS['_CFG']['time_format'], $group_buy['end_date']); + + /* 格式化保证金 */ + $group_buy['formated_deposit'] = price_format($group_buy['deposit'], false); + + /* 处理价格阶梯 */ + $price_ladder = $group_buy['price_ladder']; + if (!is_array($price_ladder) || empty($price_ladder)) + { + $price_ladder = array(array('amount' => 0, 'price' => 0)); + } + else + { + foreach ($price_ladder as $key => $amount_price) + { + $price_ladder[$key]['formated_price'] = price_format($amount_price['price']); + } + } + $group_buy['price_ladder'] = $price_ladder; + + /* 处理图片 */ + if (empty($group_buy['goods_thumb'])) + { + $group_buy['goods_thumb'] = get_image_path($group_buy['goods_id'], $group_buy['goods_thumb'], true); + } + /* 处理链接 */ + $group_buy['url'] = build_uri('group_buy', array('gbid'=>$group_buy['group_buy_id'])); + /* 加入数组 */ + $gb_list[] = $group_buy; + } + + return $gb_list; +} + +?> \ No newline at end of file diff --git a/htaccess.txt b/htaccess.txt new file mode 100644 index 0000000..ce3b6c7 --- /dev/null +++ b/htaccess.txt @@ -0,0 +1,49 @@ + + order deny,allow + deny from all + + +RewriteEngine On +#RewriteBase / + +# direct one-word access +RewriteRule ^index\.html$ index\.php [L] +RewriteRule ^category$ index\.php [L] + +# access any object by its numeric identifier +RewriteRule ^feed-c([0-9]+)\.xml$ feed\.php\?cat=$1 [L] +RewriteRule ^feed-b([0-9]+)\.xml$ feed\.php\?brand=$1 [L] +RewriteRule ^feed-type([^-]+)\.xml$ feed\.php\?type=$1 [L] +RewriteRule ^feed\.xml$ feed\.php [L] + +RewriteRule ^category-([0-9]+)-b([0-9]+)-min([0-9]+)-max([0-9]+)-attr([^-]*)-([0-9]+)-(.+)-([a-zA-Z]+)(.*)\.html$ category\.php\?id=$1&brand=$2&price_min=$3&price_max=$4&filter_attr=$5&page=$6&sort=$7&order=$8 [QSA,L] +RewriteRule ^category-([0-9]+)-b([0-9]+)-min([0-9]+)-max([0-9]+)-attr([^-]*)(.*)\.html$ category\.php\?id=$1&brand=$2&price_min=$3&price_max=$4&filter_attr=$5 [QSA,L] +RewriteRule ^category-([0-9]+)-b([0-9]+)-([0-9]+)-(.+)-([a-zA-Z]+)(.*)\.html$ category\.php\?id=$1&brand=$2&page=$3&sort=$4&order=$5 [QSA,L] +RewriteRule ^category-([0-9]+)-b([0-9]+)-([0-9]+)(.*)\.html$ category\.php\?id=$1&brand=$2&page=$3 [QSA,L] +RewriteRule ^category-([0-9]+)-b([0-9]+)(.*)\.html$ category\.php\?id=$1&brand=$2 [QSA,L] +RewriteRule ^category-([0-9]+)(.*)\.html$ category\.php\?id=$1 [QSA,L] + +RewriteRule ^goods-([0-9]+)(.*)\.html$ goods\.php\?id=$1 [QSA,L] + +RewriteRule ^article_cat-([0-9]+)-([0-9]+)-(.+)-([a-zA-Z]+)(.*)\.html$ article_cat\.php\?id=$1&page=$2&sort=$3&order=$4 [QSA,L] +RewriteRule ^article_cat-([0-9]+)-([0-9]+)-(.+)(.*)\.html$ article_cat\.php\?id=$1&page=$2&keywords=$3 [QSA,L] +RewriteRule ^article_cat-([0-9]+)-([0-9]+)(.*)\.html$ article_cat\.php\?id=$1&page=$2 [QSA,L] +RewriteRule ^article_cat-([0-9]+)(.*)\.html$ article_cat\.php\?id=$1 [QSA,L] + +RewriteRule ^article-([0-9]+)(.*)\.html$ article\.php\?id=$1 [QSA,L] + +RewriteRule ^brand-([0-9]+)-c([0-9]+)-([0-9]+)-(.+)-([a-zA-Z]+)\.html brand\.php\?id=$1&cat=$2&page=$3&sort=$4&order=$5 [QSA,L] +RewriteRule ^brand-([0-9]+)-c([0-9]+)-([0-9]+)(.*)\.html brand\.php\?id=$1&cat=$2&page=$3 [QSA,L] +RewriteRule ^brand-([0-9]+)-c([0-9]+)(.*)\.html brand\.php\?id=$1&cat=$2 [QSA,L] +RewriteRule ^brand-([0-9]+)(.*)\.html brand\.php\?id=$1 [QSA,L] + +RewriteRule ^tag-(.*)\.html search\.php\?keywords=$1 [QSA,L] +RewriteRule ^snatch-([0-9]+)\.html$ snatch\.php\?id=$1 [QSA,L] +RewriteRule ^group_buy-([0-9]+)\.html$ group_buy\.php\?act=view&id=$1 [QSA,L] +RewriteRule ^auction-([0-9]+)\.html$ auction\.php\?act=view&id=$1 [QSA,L] + +RewriteRule ^exchange-id([0-9]+)(.*)\.html$ exchange\.php\?id=$1&act=view [QSA,L] +RewriteRule ^exchange-([0-9]+)-min([0-9]+)-max([0-9]+)-([0-9]+)-(.+)-([a-zA-Z]+)(.*)\.html$ exchange\.php\?cat_id=$1&integral_min=$2&integral_max=$3&page=$4&sort=$5&order=$6 [QSA,L] +RewriteRule ^exchange-([0-9]+)-([0-9]+)-(.+)-([a-zA-Z]+)(.*)\.html$ exchange\.php\?cat_id=$1&page=$2&sort=$3&order=$4 [QSA,L] +RewriteRule ^exchange-([0-9]+)-([0-9]+)(.*)\.html$ exchange\.php\?cat_id=$1&page=$2 [QSA,L] +RewriteRule ^exchange-([0-9]+)(.*)\.html$ exchange\.php\?cat_id=$1 [QSA,L] \ No newline at end of file diff --git a/includes/cls_captcha.php b/includes/cls_captcha.php new file mode 100644 index 0000000..d9bc3c3 --- /dev/null +++ b/includes/cls_captcha.php @@ -0,0 +1,284 @@ + 背景图片的文件名 + * 1 => Red, 2 => Green, 3 => Blue + * @var array $themes + */ + var $themes_jpg = array( + 1 => array('captcha_bg1.jpg', 255, 255, 255), + 2 => array('captcha_bg2.jpg', 0, 0, 0), + 3 => array('captcha_bg3.jpg', 0, 0, 0), + 4 => array('captcha_bg4.jpg', 255, 255, 255), + 5 => array('captcha_bg5.jpg', 255, 255, 255), + ); + + var $themes_gif = array( + 1 => array('captcha_bg1.gif', 255, 255, 255), + 2 => array('captcha_bg2.gif', 0, 0, 0), + 3 => array('captcha_bg3.gif', 0, 0, 0), + 4 => array('captcha_bg4.gif', 255, 255, 255), + 5 => array('captcha_bg5.gif', 255, 255, 255), + ); + + /** + * 图片的宽度 + * + * @var integer $width + */ + var $width = 130; + + /** + * 图片的高度 + * + * @var integer $height + */ + var $height = 20; + + /** + * 构造函数 + * + * @access public + * @param string $folder 背景图片所在目录 + * @param integer $width 图片宽度 + * @param integer $height 图片高度 + * @return bool + */ + function captcha($folder = '', $width = 145, $height = 20) + { + if (!empty($folder)) + { + $this->folder = $folder; + } + + $this->width = $width; + $this->height = $height; + + /* 检查是否支持 GD */ + if (PHP_VERSION >= '4.3') + { + + return (function_exists('imagecreatetruecolor') || function_exists('imagecreate')); + } + else + { + + return (((imagetypes() & IMG_GIF) > 0) || ((imagetypes() & IMG_JPG)) > 0 ); + } + } + + /** + * 构造函数 + * + * @access public + * @param + * + * @return void + */ + function __construct($folder = '', $width = 145, $height = 20) + { + $this->captcha($folder, $width, $height); + } + + + /** + * 检查给出的验证码是否和session中的一致 + * + * @access public + * @param string $word 验证码 + * @return bool + */ + function check_word($word) + { + $recorded = isset($_SESSION[$this->session_word]) ? base64_decode($_SESSION[$this->session_word]) : ''; + $given = $this->encrypts_word(strtoupper($word)); + + return (preg_match("/$given/", $recorded)); + } + + /** + * 生成图片并输出到浏览器 + * + * @access public + * @param string $word 验证码 + * @return mix + */ + function generate_image($word = false) + { + if (!$word) + { + $word = $this->generate_word(); + } + + /* 记录验证码到session */ + $this->record_word($word); + + /* 验证码长度 */ + $letters = strlen($word); + + /* 选择一个随机的方案 */ + mt_srand((double) microtime() * 1000000); + + if (function_exists('imagecreatefromjpeg') && ((imagetypes() & IMG_JPG) > 0)) + { + $theme = $this->themes_jpg[mt_rand(1, count($this->themes_jpg))]; + } + else + { + $theme = $this->themes_gif[mt_rand(1, count($this->themes_gif))]; + } + + if (!file_exists($this->folder . $theme[0])) + { + return false; + } + else + { + $img_bg = (function_exists('imagecreatefromjpeg') && ((imagetypes() & IMG_JPG) > 0)) ? + imagecreatefromjpeg($this->folder . $theme[0]) : imagecreatefromgif($this->folder . $theme[0]); + $bg_width = imagesx($img_bg); + $bg_height = imagesy($img_bg); + + $img_org = ((function_exists('imagecreatetruecolor')) && PHP_VERSION >= '4.3') ? + imagecreatetruecolor($this->width, $this->height) : imagecreate($this->width, $this->height); + + /* 将背景图象复制原始图象并调整大小 */ + if (function_exists('imagecopyresampled') && PHP_VERSION >= '4.3') // GD 2.x + { + imagecopyresampled($img_org, $img_bg, 0, 0, 0, 0, $this->width, $this->height, $bg_width, $bg_height); + } + else // GD 1.x + { + imagecopyresized($img_org, $img_bg, 0, 0, 0, 0, $this->width, $this->height, $bg_width, $bg_height); + } + imagedestroy($img_bg); + + $clr = imagecolorallocate($img_org, $theme[1], $theme[2], $theme[3]); + + /* 绘制边框 */ + //imagerectangle($img_org, 0, 0, $this->width - 1, $this->height - 1, $clr); + + /* 获得验证码的高度和宽度 */ + $x = ($this->width - (imagefontwidth(5) * $letters)) / 2; + $y = ($this->height - imagefontheight(5)) / 2; + imagestring($img_org, 5, $x, $y, $word, $clr); + + header('Expires: Thu, 01 Jan 1970 00:00:00 GMT'); + + // HTTP/1.1 + header('Cache-Control: private, no-store, no-cache, must-revalidate'); + header('Cache-Control: post-check=0, pre-check=0, max-age=0', false); + + // HTTP/1.0 + header('Pragma: no-cache'); + if ($this->img_type == 'jpeg' && function_exists('imagecreatefromjpeg')) + { + header('Content-type: image/jpeg'); + imageinterlace($img_org, 1); + imagejpeg($img_org, false, 95); + } + else + { + header('Content-type: image/png'); + imagepng($img_org); + } + + imagedestroy($img_org); + + return true; + } + } + + /*------------------------------------------------------ */ + //-- PRIVATE METHODs + /*------------------------------------------------------ */ + + /** + * 对需要记录的串进行加密 + * + * @access private + * @param string $word 原始字符串 + * @return string + */ + function encrypts_word($word) + { + return substr(md5($word), 1, 10); + } + + /** + * 将验证码保存到session + * + * @access private + * @param string $word 原始字符串 + * @return void + */ + function record_word($word) + { + $_SESSION[$this->session_word] = base64_encode($this->encrypts_word($word)); + } + + /** + * 生成随机的验证码 + * + * @access private + * @param integer $length 验证码长度 + * @return string + */ + function generate_word($length = 4) + { + $chars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ'; + + for ($i = 0, $count = strlen($chars); $i < $count; $i++) + { + $arr[$i] = $chars[$i]; + } + + mt_srand((double) microtime() * 1000000); + shuffle($arr); + + return substr(implode('', $arr), 5, $length); + } +} + +?> \ No newline at end of file diff --git a/includes/cls_ecshop.php b/includes/cls_ecshop.php new file mode 100644 index 0000000..fef0f7c --- /dev/null +++ b/includes/cls_ecshop.php @@ -0,0 +1,203 @@ +db_name = $db_name; + $this->prefix = $prefix; + } + + /** + * 将指定的表名加上前缀后返回 + * + * @access public + * @param string $str 表名 + * + * @return string + */ + function table($str) + { + return '`' . $this->db_name . '`.`' . $this->prefix . $str . '`'; + } + + /** + * ECSHOP 密码编译方法; + * + * @access public + * @param string $pass 需要编译的原始密码 + * + * @return string + */ + function compile_password($pass) + { + return md5($pass); + } + + /** + * 取得当前的域名 + * + * @access public + * + * @return string 当前的域名 + */ + function get_domain() + { + /* 协议 */ + $protocol = $this->http(); + + /* 域名或IP地址 */ + if (isset($_SERVER['HTTP_X_FORWARDED_HOST'])) + { + $host = $_SERVER['HTTP_X_FORWARDED_HOST']; + } + elseif (isset($_SERVER['HTTP_HOST'])) + { + $host = $_SERVER['HTTP_HOST']; + } + else + { + /* 端口 */ + if (isset($_SERVER['SERVER_PORT'])) + { + $port = ':' . $_SERVER['SERVER_PORT']; + + if ((':80' == $port && 'http://' == $protocol) || (':443' == $port && 'https://' == $protocol)) + { + $port = ''; + } + } + else + { + $port = ''; + } + + if (isset($_SERVER['SERVER_NAME'])) + { + $host = $_SERVER['SERVER_NAME'] . $port; + } + elseif (isset($_SERVER['SERVER_ADDR'])) + { + $host = $_SERVER['SERVER_ADDR'] . $port; + } + } + + return $protocol . $host; + } + + /** + * 获得 ECSHOP 当前环境的 URL 地址 + * + * @access public + * + * @return void + */ + function url() + { + $curr = strpos(PHP_SELF, ADMIN_PATH . '/') !== false ? + preg_replace('/(.*)(' . ADMIN_PATH . ')(\/?)(.)*/i', '\1', dirname(PHP_SELF)) : + dirname(PHP_SELF); + + $root = str_replace('\\', '/', $curr); + + if (substr($root, -1) != '/') + { + $root .= '/'; + } + + return $this->get_domain() . $root; + } + + /** + * 获得 ECSHOP 当前环境的 HTTP 协议方式 + * + * @access public + * + * @return void + */ + function http() + { + return (isset($_SERVER['HTTPS']) && (strtolower($_SERVER['HTTPS']) != 'off')) ? 'https://' : 'http://'; + } + + /** + * 获得数据目录的路径 + * + * @param int $sid + * + * @return string 路径 + */ + function data_dir($sid = 0) + { + if (empty($sid)) + { + $s = 'data'; + } + else + { + $s = 'user_files/'; + $s .= ceil($sid / 3000) . '/'; + $s .= $sid % 3000; + } + return $s; + } + + /** + * 获得图片的目录路径 + * + * @param int $sid + * + * @return string 路径 + */ + function image_dir($sid = 0) + { + if (empty($sid)) + { + $s = 'images'; + } + else + { + $s = 'user_files/'; + $s .= ceil($sid / 3000) . '/'; + $s .= ($sid % 3000) . '/'; + $s .= 'images'; + } + return $s; + } + +} + +?> \ No newline at end of file diff --git a/includes/cls_ecshop.php.bak b/includes/cls_ecshop.php.bak new file mode 100644 index 0000000..2ab0b75 --- /dev/null +++ b/includes/cls_ecshop.php.bak @@ -0,0 +1,203 @@ +db_name = $db_name; + $this->prefix = $prefix; + } + + /** + * ָıǰ׺󷵻 + * + * @access public + * @param string $str + * + * @return string + */ + function table($str) + { + return '`' . $this->db_name . '`.`' . $this->prefix . $str . '`'; + } + + /** + * ECSHOP 뷽; + * + * @access public + * @param string $pass Ҫԭʼ + * + * @return string + */ + function compile_password($pass) + { + return md5($pass); + } + + /** + * ȡõǰ + * + * @access public + * + * @return string ǰ + */ + function get_domain() + { + /* Э */ + $protocol = $this->http(); + + /* IPַ */ + if (isset($_SERVER['HTTP_X_FORWARDED_HOST'])) + { + $host = $_SERVER['HTTP_X_FORWARDED_HOST']; + } + elseif (isset($_SERVER['HTTP_HOST'])) + { + $host = $_SERVER['HTTP_HOST']; + } + else + { + /* ˿ */ + if (isset($_SERVER['SERVER_PORT'])) + { + $port = ':' . $_SERVER['SERVER_PORT']; + + if ((':80' == $port && 'http://' == $protocol) || (':443' == $port && 'https://' == $protocol)) + { + $port = ''; + } + } + else + { + $port = ''; + } + + if (isset($_SERVER['SERVER_NAME'])) + { + $host = $_SERVER['SERVER_NAME'] . $port; + } + elseif (isset($_SERVER['SERVER_ADDR'])) + { + $host = $_SERVER['SERVER_ADDR'] . $port; + } + } + + return $protocol . $host; + } + + /** + * ECSHOP ǰ URL ַ + * + * @access public + * + * @return void + */ + function url() + { + $curr = strpos(PHP_SELF, ADMIN_PATH . '/') !== false ? + preg_replace('/(.*)(' . ADMIN_PATH . ')(\/?)(.)*/i', '\1', dirname(PHP_SELF)) : + dirname(PHP_SELF); + + $root = str_replace('\\', '/', $curr); + + if (substr($root, -1) != '/') + { + $root .= '/'; + } + + return $this->get_domain() . $root; + } + + /** + * ECSHOP ǰ HTTP Э鷽ʽ + * + * @access public + * + * @return void + */ + function http() + { + return (isset($_SERVER['HTTPS']) && (strtolower($_SERVER['HTTPS']) != 'off')) ? 'https://' : 'http://'; + } + + /** + * Ŀ¼· + * + * @param int $sid + * + * @return string · + */ + function data_dir($sid = 0) + { + if (empty($sid)) + { + $s = 'data'; + } + else + { + $s = 'user_files/'; + $s .= ceil($sid / 3000) . '/'; + $s .= $sid % 3000; + } + return $s; + } + + /** + * ͼƬĿ¼· + * + * @param int $sid + * + * @return string · + */ + function image_dir($sid = 0) + { + if (empty($sid)) + { + $s = 'images'; + } + else + { + $s = 'user_files/'; + $s .= ceil($sid / 3000) . '/'; + $s .= ($sid % 3000) . '/'; + $s .= 'images'; + } + return $s; + } + +} + +?> \ No newline at end of file diff --git a/includes/cls_error.php b/includes/cls_error.php new file mode 100644 index 0000000..696cbf4 --- /dev/null +++ b/includes/cls_error.php @@ -0,0 +1,148 @@ +ecs_error($tpl); + } + + /** + * 构造函数 + * + * @access public + * @param string $tpl + * @return void + */ + function ecs_error($tpl) + { + $this->_template = $tpl; + } + + /** + * 添加一条错误信息 + * + * @access public + * @param string $msg + * @param integer $errno + * @return void + */ + function add($msg, $errno=1) + { + if (is_array($msg)) + { + $this->_message = array_merge($this->_message, $msg); + } + else + { + $this->_message[] = $msg; + } + + $this->error_no = $errno; + } + + /** + * 清空错误信息 + * + * @access public + * @return void + */ + function clean() + { + $this->_message = array(); + $this->error_no = 0; + } + + /** + * 返回所有的错误信息的数组 + * + * @access public + * @return array + */ + function get_all() + { + return $this->_message; + } + + /** + * 返回最后一条错误信息 + * + * @access public + * @return void + */ + function last_message() + { + return array_slice($this->_message, -1); + } + + /** + * 显示错误信息 + * + * @access public + * @param string $link + * @param string $href + * @return void + */ + function show($link = '', $href = '') + { + if ($this->error_no > 0) + { + $message = array(); + + $link = (empty($link)) ? $GLOBALS['_LANG']['back_up_page'] : $link; + $href = (empty($href)) ? 'javascript:history.back();' : $href; + $message['url_info'][$link] = $href; + $message['back_url'] = $href; + + foreach ($this->_message AS $msg) + { + $message['content'] = '
' . htmlspecialchars($msg) . '
'; + } + + if (isset($GLOBALS['smarty'])) + { + assign_template(); + $GLOBALS['smarty']->assign('auto_redirect', true); + $GLOBALS['smarty']->assign('message', $message); + $GLOBALS['smarty']->display($this->_template); + } + else + { + die($message['content']); + } + + exit; + } + } +} + +?> \ No newline at end of file diff --git a/includes/cls_iconv.php b/includes/cls_iconv.php new file mode 100644 index 0000000..a2cf629 --- /dev/null +++ b/includes/cls_iconv.php @@ -0,0 +1,677 @@ + UNICODE 对照表的内容 + * @变量类型 + * @访问 内部 + */ + var $unicode_table = array(); + + /** + * 访问中文繁简互换表的文件指针 + * + * @变量类型 对象 + * @访问 内部 + */ + var $ctf; + + /** + * 等待转换的字符串 + * @变量类型 + * @访问 内部 + */ + var $SourceText = ''; + + /** + * Chinese 的运行配置 + * + * @变量类型 数组 + * @访问 公开 + */ + var $config = array( + 'codetable_dir' => '', // 存放各种语言互换表的目录 + 'source_lang' => '', // 字符的原编码 + 'target_lang' => '', // 转换后的编码 + 'GBtoBIG5_table' => 'gb-big5.table', // 简体中文转换为繁体中文的对照表 + 'BIG5toGB_table' => 'big5-gb.table', // 繁体中文转换为简体中文的对照表 + 'GBtoUTF8_table' => 'gb_utf8.php', // 简体中文转换为UTF-8的对照表 + 'BIG5toUTF8_table' => 'big5_utf8.php' // 繁体中文转换为UTF-8的对照表 + ); + + var $iconv_enabled = false; // 是否存在 ICONV 模块,默认为否 + var $mbstring_enabled = false; // 是否存在 MBSTRING 模块,默认为否 + + + /** + * Chinese 的悉构函数 + * + * 详细说明 + * @形参 字符串 $source_lang 为需要转换的字符串的原编码 + * 字符串 $target_lang 为转换的目标编码 + * 字符串 $SourceText 为等待转换的字符串 + * @访问 公开 + * @返回值 无 + * @throws + */ + function Chinese($dir = './') + { + $this->config['codetable_dir'] = $dir . "includes/codetable/"; + + if (function_exists('iconv')) + { + $this->iconv_enabled = true; + } + + if (PHP_VERSION >= '5.0' && function_exists('mb_convert_encoding') && function_exists('mb_list_encodings')) + { + $encodings = mb_list_encodings(); + + if (in_array('UTF-8', $encodings) == true && in_array('BIG-5', $encodings) == true && in_array('CP936', $encodings) == true) // CP936 就是 GBK 字符集的别名 + { + $this->mbstring_enabled = true; + } + } + } + + function Convert($source_lang, $target_lang, $source_string = '') + { + /* 如果字符串为空或者字符串不需要转换,直接返回 */ + if ($source_string == '' || preg_match("/[\x80-\xFF]+/", $source_string) == 0) + { + return $source_string; + } + + if ($source_lang) + { + $this->config['source_lang'] = $this->_lang($source_lang); + } + + if ($target_lang) + { + $this->config['target_lang'] = $this->_lang($target_lang); + } + + /* 如果编码相同,直接返回 */ + if ($this->config['source_lang'] == $this->config['target_lang']) + { + return $source_string; + } + + $this->SourceText = $source_string; + + if (($this->iconv_enabled || $this->mbstring_enabled) && !($this->config['source_lang'] == 'GBK' && $this->config['target_lang'] == 'BIG-5')) + { + if ($this->config['target_lang'] != 'UNICODE') + { + $string = $this->_convert_iconv_mbstring($this->SourceText, $this->config['target_lang'], $this->config['source_lang']); + + /* 如果正确转换 */ + if ($string) + { + return $string; + } + } + else + { + $string = ''; + $text = $SourceText; + while ($text) + { + if (ord(substr($text, 0, 1)) > 127) + { + if ($this->config['source_lang'] != 'UTF-8') + { + $char = $this->_convert_iconv_mbstring(substr($text, 0, 2), 'UTF-8', $this->config['source_lang']); + } + else + { + $char = substr($text, 0, 3); + } + /* 如果转换出错 */ + if ($char == '') + { + $string = ''; + + break; + } + + switch (strlen($char)) + { + case 1: + $uchar = ord($char); + break; + + case 2: + $uchar = (ord($char[0]) & 0x3f) << 6; + $uchar += ord($char[1]) & 0x3f; + break; + + case 3: + $uchar = (ord($char[0]) & 0x1f) << 12; + $uchar += (ord($char[1]) & 0x3f) << 6; + $uchar += ord($char[2]) & 0x3f; + break; + + case 4: + $uchar = (ord($char[0]) & 0x0f) << 18; + $uchar += (ord($char[1]) & 0x3f) << 12; + $uchar += (ord($char[2]) & 0x3f) << 6; + $uchar += ord($char[3]) & 0x3f; + break; + } + $string .= '&#x' . dechex($uchar) . ';'; + + if ($this->config['source_lang'] != 'UTF-8') + { + $text = substr($text, 2); + } + else + { + $text = substr($text, 3); + } + } + else + { + $string .= substr($text, 0, 1); + $text = substr($text, 1); + } + } + + /* 如果正确转换 */ + if ($string) + { + return $string; + } + } + } + + $this->OpenTable(); + // 判断是否为中文繁、简转换 + if (($this->config['source_lang'] == 'GBK' || $this->config['source_lang'] == 'BIG-5') && ($this->config['target_lang'] == 'GBK' || $this->config['target_lang'] == 'BIG-5')) + { + return $this->GBtoBIG5(); + } + + // 判断是否为简体、繁体中文与UTF8转换 + if (($this->config['source_lang'] == 'GBK' || $this->config['source_lang'] == 'BIG-5' || $this->config['source_lang'] == 'UTF-8') && ($this->config['target_lang'] == 'UTF-8' || $this->config['target_lang'] == 'GBK' || $this->config['target_lang'] == 'BIG-5')) + { + return $this->CHStoUTF8(); + } + + // 判断是否为简体、繁体中文与UNICODE转换 + if (($this->config['source_lang'] == 'GBK' || $this->config['source_lang'] == 'BIG-5') && $this->config['target_lang'] == 'UNICODE') + { + return $this->CHStoUNICODE(); + } + } + + function _lang($lang) + { + $lang = strtoupper($lang); + + if (substr($lang, 0, 2) == 'GB') + { + return 'GBK'; + } + else + { + switch(substr($lang, 0, 3)) + { + case 'BIG': + return 'BIG-5'; + + case 'UTF': + return 'UTF-8'; + + case 'UNI': + return 'UNICODE'; + + default: + return ''; + } + } + } + + function _convert_iconv_mbstring($string, $target_lang, $source_lang) + { + if ($this->iconv_enabled) + { + $return_string = @iconv($source_lang, $target_lang, $string); + if ($return_string !== false) + { + return $return_string; + } + } + + if ($this->mbstring_enabled) + { + if ($source_lang == 'GBK') + { + $source_lang = 'CP936'; + } + if ($target_lang == 'GBK') + { + $target_lang = 'CP936'; + } + + $return_string = @mb_convert_encoding($string, $target_lang, $source_lang); + if ($return_string !== false) + { + return $return_string; + } + else + { + return false; + } + } + } + + /** + * 将 16 进制转换为 2 进制字符 + * + * 详细说明 + * @形参 $hexdata 为16进制的编码 + * @访问 内部 + * @返回 字符串 + * @throws + */ + function _hex2bin($hexdata) + { + $bindata = ''; + + for ($i = 0, $count = strlen($hexdata); $i < $count; $i += 2) + { + $bindata .= chr(hexdec($hexdata{$i} . $hexdata{$i + 1})); + } + + return $bindata; + } + + /** + * 打开对照表 + * + * 详细说明 + * @形参 + * @访问 内部 + * @返回 无 + * @throws + */ + function OpenTable() + { + static $gb_utf8_table = NULL; + static $gb_unicode_table = NULL; + static $utf8_gb_table = NULL; + + static $big5_utf8_table = NULL; + static $big5_unicode_table = NULL; + static $utf8_big5_table = NULL; + + // 假如原编码为简体中文的话 + if ($this->config['source_lang'] == 'GBK') + { + // 假如转换目标编码为繁体中文的话 + if ($this->config['target_lang'] == 'BIG-5') + { + $this->ctf = @fopen($this->config['codetable_dir'] . $this->config['GBtoBIG5_table'], 'rb'); + if (is_null($this->ctf)) + { + echo '打开打开转换表文件失败!'; + + exit; + } + } + + // 假如转换目标编码为 UTF8 的话 + if ($this->config['target_lang'] == 'UTF-8') + { + if ($gb_utf8_table === NULL) + { + require_once($this->config['codetable_dir'] . $this->config['GBtoUTF8_table']); + } + $this->unicode_table = $gb_utf8_table; + } + + // 假如转换目标编码为 UNICODE 的话 + if ($this->config['target_lang'] == 'UNICODE') + { + if ($gb_unicode_table === NULL) + { + if (isset($gb_utf8_table) === false) + { + require_once($this->config['codetable_dir'] . $this->config['GBtoUTF8_table']); + } + foreach ($gb_utf8_table AS $key => $value) + { + $gb_unicode_table[$key] = substr($value, 2); + } + } + $this->unicode_table = $gb_unicode_table; + } + } + + // 假如原编码为繁体中文的话 + if ($this->config['source_lang'] == 'BIG-5') + { + // 假如转换目标编码为简体中文的话 + if ($this->config['target_lang'] == 'GBK') + { + $this->ctf = @fopen($this->config['codetable_dir'] . $this->config['BIG5toGB_table'], 'rb'); + if (is_null($this->ctf)) + { + echo '打开打开转换表文件失败!'; + + exit; + } + } + // 假如转换目标编码为 UTF8 的话 + if ($this->config['target_lang'] == 'UTF-8') + { + if ($big5_utf8_table === NULL) + { + require_once($this->config['codetable_dir'] . $this->config['BIG5toUTF8_table']); + } + $this->unicode_table = $big5_utf8_table; + } + + // 假如转换目标编码为 UNICODE 的话 + if ($this->config['target_lang'] == 'UNICODE') + { + if ($big5_unicode_table === NULL) + { + if (isset($big5_utf8_table) === false) + { + require_once($this->config['codetable_dir'] . $this->config['BIG5toUTF8_table']); + } + foreach ($big5_utf8_table AS $key => $value) + { + $big5_unicode_table[$key] = substr($value, 2); + } + } + $this->unicode_table = $big5_unicode_table; + } + } + + // 假如原编码为 UTF8 的话 + if ($this->config['source_lang'] == 'UTF-8') + { + // 假如转换目标编码为 GBK 的话 + if ($this->config['target_lang'] == 'GBK') + { + if ($utf8_gb_table === NULL) + { + if (isset($gb_utf8_table) === false) + { + require_once($this->config['codetable_dir'] . $this->config['GBtoUTF8_table']); + } + foreach ($gb_utf8_table AS $key => $value) + { + $utf8_gb_table[hexdec($value)] = '0x' . dechex($key); + } + } + $this->unicode_table = $utf8_gb_table; + } + + // 假如转换目标编码为 BIG5 的话 + if ($this->config['target_lang'] == 'BIG-5') + { + if ($utf8_big5_table === NULL) + { + if (isset($big5_utf8_table) === false) + { + require_once($this->config['codetable_dir'] . $this->config['BIG5toUTF8_table']); + } + foreach ($big5_utf8_table AS $key => $value) + { + $utf8_big5_table[hexdec($value)] = '0x' . dechex($key); + } + } + $this->unicode_table = $utf8_big5_table; + } + } + } + + /** + * 将简体、繁体中文的 UNICODE 编码转换为 UTF8 字符 + * + * 详细说明 + * @形参 数字 $c 简体中文汉字的UNICODE编码的10进制 + * @访问 内部 + * @返回 字符串 + * @throws + */ + function CHSUtoUTF8($c) + { + $str=''; + + if ($c < 0x80) + { + $str .= $c; + } + elseif ($c < 0x800) + { + $str .= (0xC0 | $c >> 6); + $str .= (0x80 | $c & 0x3F); + } + elseif ($c < 0x10000) + { + $str .= (0xE0 | $c >> 12); + $str .= (0x80 | $c >> 6 & 0x3F); + $str .= (0x80 | $c & 0x3F); + } + elseif ($c < 0x200000) + { + $str .= (0xF0 | $c >> 18); + $str .= (0x80 | $c >> 12 & 0x3F); + $str .= (0x80 | $c >> 6 & 0x3F); + $str .= (0x80 | $c & 0x3F); + } + + return $str; + } + + /** + * 简体、繁体中文 <-> UTF8 互相转换的函数 + * + * 详细说明 + * @形参 + * @访问 内部 + * @返回 字符串 + * @throws + */ + function CHStoUTF8() + { + if ($this->config['source_lang'] == 'BIG-5' || $this->config['source_lang'] == 'GBK') + { + $ret = ''; + + while ($this->SourceText) + { + if (ord($this->SourceText{0}) > 127) + { + if ($this->config['source_lang'] == 'BIG-5') + { + $utf8 = $this->CHSUtoUTF8(hexdec(@$this->unicode_table[hexdec(bin2hex($this->SourceText{0} . $this->SourceText{1}))])); + } + if ($this->config['source_lang'] == 'GBK') + { + $utf8 = $this->CHSUtoUTF8(hexdec(@$this->unicode_table[hexdec(bin2hex($this->SourceText{0} . $this->SourceText{1})) - 0x8080])); + } + for ($i = 0, $count = strlen($utf8); $i < $count; $i += 3) + { + $ret .= chr(substr($utf8, $i, 3)); + } + + $this->SourceText = substr($this->SourceText, 2, strlen($this->SourceText)); + } + else + { + $ret .= $this->SourceText{0}; + $this->SourceText = substr($this->SourceText, 1, strlen($this->SourceText)); + } + } + $this->unicode_table = array(); + $this->SourceText = ''; + + return $ret; + } + + if ($this->config['source_lang'] == 'UTF-8') + { + $i = 0; + $out = ''; + $len = strlen($this->SourceText); + while ($i < $len) + { + $c = ord($this->SourceText{$i++}); + switch($c >> 4) + { + case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: + // 0xxxxxxx + $out .= $this->SourceText{$i - 1}; + break; + case 12: case 13: + // 110x xxxx 10xx xxxx + $char2 = ord($this->SourceText{$i++}); + $char3 = @$this->unicode_table[(($c & 0x1F) << 6) | ($char2 & 0x3F)]; + + if ($this->config['target_lang'] == 'GBK') + { + $out .= $this->_hex2bin(dechex($char3 + 0x8080)); + } + elseif ($this->config['target_lang'] == 'BIG-5') + { + $out .= $this->_hex2bin(dechex($char3 + 0x0000)); + } + break; + case 14: + // 1110 xxxx 10xx xxxx 10xx xxxx + $char2 = ord($this->SourceText{$i++}); + $char3 = ord($this->SourceText{$i++}); + $char4 = @$this->unicode_table[(($c & 0x0F) << 12) | (($char2 & 0x3F) << 6) | (($char3 & 0x3F) << 0)]; + + if ($this->config['target_lang'] == 'GBK') + { + $out .= $this->_hex2bin(dechex($char4 + 0x8080)); + } elseif ($this->config['target_lang'] == 'BIG-5') + { + $out .= $this->_hex2bin(dechex($char4 + 0x0000)); + } + + break; + } + } + + // 返回结果 + return $out; + } + } + + /** + * 简体、繁体中文转换为 UNICODE编码 + * + * 详细说明 + * @形参 + * @访问 内部 + * @返回 字符串 + * @throws + */ + function CHStoUNICODE() + { + $utf = ''; + + while ($this->SourceText) + { + if (ord($this->SourceText{0}) > 127) + { + if ($this->config['source_lang'] == 'GBK') + { + $utf .= '&#x' . $this->unicode_table[hexdec(bin2hex($this->SourceText{0} . $this->SourceText{1})) - 0x8080] . ';'; + } + elseif ($this->config['source_lang'] == 'BIG-5') + { + $utf .= '&#x' . $this->unicode_table[hexdec(bin2hex($this->SourceText{0} . $this->SourceText{1}))] . ';'; + } + + $this->SourceText = substr($this->SourceText, 2, strlen($this->SourceText)); + } + else + { + $utf .= $this->SourceText{0}; + $this->SourceText = substr($this->SourceText, 1, strlen($this->SourceText)); + } + } + + return $utf; + } + + /** + * 简体中文 <-> 繁体中文 互相转换的函数 + * + * 详细说明 + * @访问 内部 + * @返回值 经过编码的utf8字符 + * @throws + */ + function GBtoBIG5() + { + // 获取等待转换的字符串的总长度 + $max = strlen($this->SourceText) - 1; + + for ($i = 0; $i < $max; $i++) + { + $h = ord($this->SourceText{$i}); + if ($h >= 160) + { + $l = ord($this->SourceText{$i + 1}); + + if ($h == 161 && $l == 64) + { + $gb = ' '; + } + else + { + fseek($this->ctf, ($h - 160) * 510 + ($l - 1) * 2); + $gb = fread($this->ctf, 2); + } + + $this->SourceText{$i} = $gb{0}; + $this->SourceText{$i + 1} = $gb{1}; + + $i++; + } + } + fclose($this->ctf); + + // 将转换后的结果赋予 $result; + $result = $this->SourceText; + + // 清空 $thisSourceText + $this->SourceText = ''; + + // 返回转换结果 + return $result; + } +} + +?> diff --git a/includes/cls_image.php b/includes/cls_image.php new file mode 100644 index 0000000..40296cc --- /dev/null +++ b/includes/cls_image.php @@ -0,0 +1,762 @@ + 'image/gif', 2 => 'image/jpeg', 3 => 'image/png'); + + function __construct($bgcolor='') + { + $this->cls_image($bgcolor); + } + + function cls_image($bgcolor='') + { + if ($bgcolor) + { + $this->bgcolor = $bgcolor; + } + else + { + $this->bgcolor = "#FFFFFF"; + } + } + + /** + * 图片上传的处理函数 + * + * @access public + * @param array upload 包含上传的图片文件信息的数组 + * @param array dir 文件要上传在$this->data_dir下的目录名。如果为空图片放在则在$this->images_dir下以当月命名的目录下 + * @param array img_name 上传图片名称,为空则随机生成 + * @return mix 如果成功则返回文件名,否则返回false + */ + function upload_image($upload, $dir = '', $img_name = '') + { + /* 没有指定目录默认为根目录images */ + if (empty($dir)) + { + /* 创建当月目录 */ + $dir = date('Ym'); + $dir = ROOT_PATH . $this->images_dir . '/' . $dir . '/'; + } + else + { + /* 创建目录 */ + $dir = ROOT_PATH . $this->data_dir . '/' . $dir . '/'; + if ($img_name) + { + $img_name = $dir . $img_name; // 将图片定位到正确地址 + } + } + + /* 如果目标目录不存在,则创建它 */ + if (!file_exists($dir)) + { + if (!make_dir($dir)) + { + /* 创建目录失败 */ + $this->error_msg = sprintf($GLOBALS['_LANG']['directory_readonly'], $dir); + $this->error_no = ERR_DIRECTORY_READONLY; + + return false; + } + } + + if (empty($img_name)) + { + $img_name = $this->unique_name($dir); + $img_name = $dir . $img_name . $this->get_filetype($upload['name']); + } + + if (!$this->check_img_type($upload['type'])) + { + $this->error_msg = $GLOBALS['_LANG']['invalid_upload_image_type']; + $this->error_no = ERR_INVALID_IMAGE_TYPE; + return false; + } + + /* 允许上传的文件类型 */ + $allow_file_types = '|GIF|JPG|JEPG|PNG|BMP|SWF|'; + if (!check_file_type($upload['tmp_name'], $img_name, $allow_file_types)) + { + $this->error_msg = $GLOBALS['_LANG']['invalid_upload_image_type']; + $this->error_no = ERR_INVALID_IMAGE_TYPE; + return false; + } + + if ($this->move_file($upload, $img_name)) + { + return str_replace(ROOT_PATH, '', $img_name); + } + else + { + $this->error_msg = sprintf($GLOBALS['_LANG']['upload_failure'], $upload['name']); + $this->error_no = ERR_UPLOAD_FAILURE; + + return false; + } + } + + /** + * 创建图片的缩略图 + * + * @access public + * @param string $img 原始图片的路径 + * @param int $thumb_width 缩略图宽度 + * @param int $thumb_height 缩略图高度 + * @param strint $path 指定生成图片的目录名 + * @return mix 如果成功返回缩略图的路径,失败则返回false + */ + function make_thumb($img, $thumb_width = 0, $thumb_height = 0, $path = '', $bgcolor='') + { + $gd = $this->gd_version(); //获取 GD 版本。0 表示没有 GD 库,1 表示 GD 1.x,2 表示 GD 2.x + if ($gd == 0) + { + $this->error_msg = $GLOBALS['_LANG']['missing_gd']; + return false; + } + + /* 检查缩略图宽度和高度是否合法 */ + if ($thumb_width == 0 && $thumb_height == 0) + { + return str_replace(ROOT_PATH, '', str_replace('\\', '/', realpath($img))); + } + + /* 检查原始文件是否存在及获得原始文件的信息 */ + $org_info = @getimagesize($img); + if (!$org_info) + { + $this->error_msg = sprintf($GLOBALS['_LANG']['missing_orgin_image'], $img); + $this->error_no = ERR_IMAGE_NOT_EXISTS; + + return false; + } + + if (!$this->check_img_function($org_info[2])) + { + $this->error_msg = sprintf($GLOBALS['_LANG']['nonsupport_type'], $this->type_maping[$org_info[2]]); + $this->error_no = ERR_NO_GD; + + return false; + } + + $img_org = $this->img_resource($img, $org_info[2]); + + /* 原始图片以及缩略图的尺寸比例 */ + $scale_org = $org_info[0] / $org_info[1]; + /* 处理只有缩略图宽和高有一个为0的情况,这时背景和缩略图一样大 */ + if ($thumb_width == 0) + { + $thumb_width = $thumb_height * $scale_org; + } + if ($thumb_height == 0) + { + $thumb_height = $thumb_width / $scale_org; + } + + /* 创建缩略图的标志符 */ + if ($gd == 2) + { + $img_thumb = imagecreatetruecolor($thumb_width, $thumb_height); + } + else + { + $img_thumb = imagecreate($thumb_width, $thumb_height); + } + + /* 背景颜色 */ + if (empty($bgcolor)) + { + $bgcolor = $this->bgcolor; + } + $bgcolor = trim($bgcolor,"#"); + sscanf($bgcolor, "%2x%2x%2x", $red, $green, $blue); + $clr = imagecolorallocate($img_thumb, $red, $green, $blue); + imagefilledrectangle($img_thumb, 0, 0, $thumb_width, $thumb_height, $clr); + + if ($org_info[0] / $thumb_width > $org_info[1] / $thumb_height) + { + $lessen_width = $thumb_width; + $lessen_height = $thumb_width / $scale_org; + } + else + { + /* 原始图片比较高,则以高度为准 */ + $lessen_width = $thumb_height * $scale_org; + $lessen_height = $thumb_height; + } + + $dst_x = ($thumb_width - $lessen_width) / 2; + $dst_y = ($thumb_height - $lessen_height) / 2; + + /* 将原始图片进行缩放处理 */ + if ($gd == 2) + { + imagecopyresampled($img_thumb, $img_org, $dst_x, $dst_y, 0, 0, $lessen_width, $lessen_height, $org_info[0], $org_info[1]); + } + else + { + imagecopyresized($img_thumb, $img_org, $dst_x, $dst_y, 0, 0, $lessen_width, $lessen_height, $org_info[0], $org_info[1]); + } + + /* 创建当月目录 */ + if (empty($path)) + { + $dir = ROOT_PATH . $this->images_dir . '/' . date('Ym').'/'; + } + else + { + $dir = $path; + } + + + /* 如果目标目录不存在,则创建它 */ + if (!file_exists($dir)) + { + if (!make_dir($dir)) + { + /* 创建目录失败 */ + $this->error_msg = sprintf($GLOBALS['_LANG']['directory_readonly'], $dir); + $this->error_no = ERR_DIRECTORY_READONLY; + return false; + } + } + + /* 如果文件名为空,生成不重名随机文件名 */ + $filename = $this->unique_name($dir); + + /* 生成文件 */ + if (function_exists('imagejpeg')) + { + $filename .= '.jpg'; + imagejpeg($img_thumb, $dir . $filename); + } + elseif (function_exists('imagegif')) + { + $filename .= '.gif'; + imagegif($img_thumb, $dir . $filename); + } + elseif (function_exists('imagepng')) + { + $filename .= '.png'; + imagepng($img_thumb, $dir . $filename); + } + else + { + $this->error_msg = $GLOBALS['_LANG']['creating_failure']; + $this->error_no = ERR_NO_GD; + + return false; + } + + imagedestroy($img_thumb); + imagedestroy($img_org); + + //确认文件是否生成 + if (file_exists($dir . $filename)) + { + return str_replace(ROOT_PATH, '', $dir) . $filename; + } + else + { + $this->error_msg = $GLOBALS['_LANG']['writting_failure']; + $this->error_no = ERR_DIRECTORY_READONLY; + + return false; + } + } + + /** + * 为图片增加水印 + * + * @access public + * @param string filename 原始图片文件名,包含完整路径 + * @param string target_file 需要加水印的图片文件名,包含完整路径。如果为空则覆盖源文件 + * @param string $watermark 水印完整路径 + * @param int $watermark_place 水印位置代码 + * @return mix 如果成功则返回文件路径,否则返回false + */ + function add_watermark($filename, $target_file='', $watermark='', $watermark_place='', $watermark_alpha = 0.65) + { + // 是否安装了GD + $gd = $this->gd_version(); + if ($gd == 0) + { + $this->error_msg = $GLOBALS['_LANG']['missing_gd']; + $this->error_no = ERR_NO_GD; + + return false; + } + + // 文件是否存在 + if ((!file_exists($filename)) || (!is_file($filename))) + { + $this->error_msg = sprintf($GLOBALS['_LANG']['missing_orgin_image'], $filename); + $this->error_no = ERR_IMAGE_NOT_EXISTS; + + return false; + } + + /* 如果水印的位置为0,则返回原图 */ + if ($watermark_place == 0 || empty($watermark)) + { + return str_replace(ROOT_PATH, '', str_replace('\\', '/', realpath($filename))); + } + + if (!$this->validate_image($watermark)) + { + /* 已经记录了错误信息 */ + return false; + } + + // 获得水印文件以及源文件的信息 + $watermark_info = @getimagesize($watermark); + $watermark_handle = $this->img_resource($watermark, $watermark_info[2]); + + if (!$watermark_handle) + { + $this->error_msg = sprintf($GLOBALS['_LANG']['create_watermark_res'], $this->type_maping[$watermark_info[2]]); + $this->error_no = ERR_INVALID_IMAGE; + + return false; + } + + // 根据文件类型获得原始图片的操作句柄 + $source_info = @getimagesize($filename); + $source_handle = $this->img_resource($filename, $source_info[2]); + if (!$source_handle) + { + $this->error_msg = sprintf($GLOBALS['_LANG']['create_origin_image_res'], $this->type_maping[$source_info[2]]); + $this->error_no = ERR_INVALID_IMAGE; + + return false; + } + + // 根据系统设置获得水印的位置 + switch ($watermark_place) + { + case '1': + $x = 0; + $y = 0; + break; + case '2': + $x = $source_info[0] - $watermark_info[0]; + $y = 0; + break; + case '4': + $x = 0; + $y = $source_info[1] - $watermark_info[1]; + break; + case '5': + $x = $source_info[0] - $watermark_info[0]; + $y = $source_info[1] - $watermark_info[1]; + break; + default: + $x = $source_info[0]/2 - $watermark_info[0]/2; + $y = $source_info[1]/2 - $watermark_info[1]/2; + } + + if (strpos(strtolower($watermark_info['mime']), 'png') !== false) + { + imageAlphaBlending($watermark_handle, true); + imagecopy($source_handle, $watermark_handle, $x, $y, 0, 0,$watermark_info[0], $watermark_info[1]); + } + else + { + imagecopymerge($source_handle, $watermark_handle, $x, $y, 0, 0,$watermark_info[0], $watermark_info[1], $watermark_alpha); + } + $target = empty($target_file) ? $filename : $target_file; + + switch ($source_info[2] ) + { + case 'image/gif': + case 1: + imagegif($source_handle, $target); + break; + + case 'image/pjpeg': + case 'image/jpeg': + case 2: + imagejpeg($source_handle, $target); + break; + + case 'image/x-png': + case 'image/png': + case 3: + imagepng($source_handle, $target); + break; + + default: + $this->error_msg = $GLOBALS['_LANG']['creating_failure']; + $this->error_no = ERR_NO_GD; + + return false; + } + + imagedestroy($source_handle); + + $path = realpath($target); + if ($path) + { + return str_replace(ROOT_PATH, '', str_replace('\\', '/', $path)); + } + else + { + $this->error_msg = $GLOBALS['_LANG']['writting_failure']; + $this->error_no = ERR_DIRECTORY_READONLY; + + return false; + } + } + + /** + * 检查水印图片是否合法 + * + * @access public + * @param string $path 图片路径 + * + * @return boolen + */ + function validate_image($path) + { + if (empty($path)) + { + $this->error_msg = $GLOBALS['_LANG']['empty_watermark']; + $this->error_no = ERR_INVALID_PARAM; + + return false; + } + + /* 文件是否存在 */ + if (!file_exists($path)) + { + $this->error_msg = sprintf($GLOBALS['_LANG']['missing_watermark'], $path); + $this->error_no = ERR_IMAGE_NOT_EXISTS; + return false; + } + + // 获得文件以及源文件的信息 + $image_info = @getimagesize($path); + + if (!$image_info) + { + $this->error_msg = sprintf($GLOBALS['_LANG']['invalid_image_type'], $path); + $this->error_no = ERR_INVALID_IMAGE; + return false; + } + + /* 检查处理函数是否存在 */ + if (!$this->check_img_function($image_info[2])) + { + $this->error_msg = sprintf($GLOBALS['_LANG']['nonsupport_type'], $this->type_maping[$image_info[2]]); + $this->error_no = ERR_NO_GD; + return false; + } + + return true; + } + + /** + * 返回错误信息 + * + * @return string 错误信息 + */ + function error_msg() + { + return $this->error_msg; + } + + /*------------------------------------------------------ */ + //-- 工具函数 + /*------------------------------------------------------ */ + + /** + * 检查图片类型 + * @param string $img_type 图片类型 + * @return bool + */ + function check_img_type($img_type) + { + return $img_type == 'image/pjpeg' || + $img_type == 'image/x-png' || + $img_type == 'image/png' || + $img_type == 'image/gif' || + $img_type == 'image/jpeg'; + } + + /** + * 检查图片处理能力 + * + * @access public + * @param string $img_type 图片类型 + * @return void + */ + function check_img_function($img_type) + { + switch ($img_type) + { + case 'image/gif': + case 1: + + if (PHP_VERSION >= '4.3') + { + return function_exists('imagecreatefromgif'); + } + else + { + return (imagetypes() & IMG_GIF) > 0; + } + break; + + case 'image/pjpeg': + case 'image/jpeg': + case 2: + if (PHP_VERSION >= '4.3') + { + return function_exists('imagecreatefromjpeg'); + } + else + { + return (imagetypes() & IMG_JPG) > 0; + } + break; + + case 'image/x-png': + case 'image/png': + case 3: + if (PHP_VERSION >= '4.3') + { + return function_exists('imagecreatefrompng'); + } + else + { + return (imagetypes() & IMG_PNG) > 0; + } + break; + + default: + return false; + } + } + + /** + * 生成随机的数字串 + * + * @author: weber liu + * @return string + */ + function random_filename() + { + $str = ''; + for($i = 0; $i < 9; $i++) + { + $str .= mt_rand(0, 9); + } + + return gmtime() . $str; + } + + /** + * 生成指定目录不重名的文件名 + * + * @access public + * @param string $dir 要检查是否有同名文件的目录 + * + * @return string 文件名 + */ + function unique_name($dir) + { + $filename = ''; + while (empty($filename)) + { + $filename = cls_image::random_filename(); + if (file_exists($dir . $filename . '.jpg') || file_exists($dir . $filename . '.gif') || file_exists($dir . $filename . '.png')) + { + $filename = ''; + } + } + + return $filename; + } + + /** + * 返回文件后缀名,如‘.php’ + * + * @access public + * @param + * + * @return string 文件后缀名 + */ + function get_filetype($path) + { + $pos = strrpos($path, '.'); + if ($pos !== false) + { + return substr($path, $pos); + } + else + { + return ''; + } + } + + /** + * 根据来源文件的文件类型创建一个图像操作的标识符 + * + * @access public + * @param string $img_file 图片文件的路径 + * @param string $mime_type 图片文件的文件类型 + * @return resource 如果成功则返回图像操作标志符,反之则返回错误代码 + */ + function img_resource($img_file, $mime_type) + { + switch ($mime_type) + { + case 1: + case 'image/gif': + $res = imagecreatefromgif($img_file); + break; + + case 2: + case 'image/pjpeg': + case 'image/jpeg': + $res = imagecreatefromjpeg($img_file); + break; + + case 3: + case 'image/x-png': + case 'image/png': + $res = imagecreatefrompng($img_file); + break; + + default: + return false; + } + + return $res; + } + + /** + * 获得服务器上的 GD 版本 + * + * @access public + * @return int 可能的值为0,1,2 + */ + function gd_version() + { + static $version = -1; + + if ($version >= 0) + { + return $version; + } + + if (!extension_loaded('gd')) + { + $version = 0; + } + else + { + // 尝试使用gd_info函数 + if (PHP_VERSION >= '4.3') + { + if (function_exists('gd_info')) + { + $ver_info = gd_info(); + preg_match('/\d/', $ver_info['GD Version'], $match); + $version = $match[0]; + } + else + { + if (function_exists('imagecreatetruecolor')) + { + $version = 2; + } + elseif (function_exists('imagecreate')) + { + $version = 1; + } + } + } + else + { + if (preg_match('/phpinfo/', ini_get('disable_functions'))) + { + /* 如果phpinfo被禁用,无法确定gd版本 */ + $version = 1; + } + else + { + // 使用phpinfo函数 + ob_start(); + phpinfo(8); + $info = ob_get_contents(); + ob_end_clean(); + $info = stristr($info, 'gd version'); + preg_match('/\d/', $info, $match); + $version = $match[0]; + } + } + } + + return $version; + } + + /** + * + * + * @access public + * @param + * + * @return void + */ + function move_file($upload, $target) + { + if (isset($upload['error']) && $upload['error'] > 0) + { + return false; + } + + if (!move_upload_file($upload['tmp_name'], $target)) + { + return false; + } + + return true; + } +} + +?> \ No newline at end of file diff --git a/includes/cls_json.php b/includes/cls_json.php new file mode 100644 index 0000000..89635d6 --- /dev/null +++ b/includes/cls_json.php @@ -0,0 +1,595 @@ + $v) + { + if (!is_numeric($i)) + { + $numeric = false; + break; + } + } + + if ($numeric) + { + foreach ($arg AS $i => $v) + { + if (strlen($s) > 0) + { + $s .= ','; + } + $s .= $this->encode($arg[$i]); + } + + $returnValue = '[' . $s . ']'; + } + else + { + foreach ($arg AS $i => $v) + { + if (strlen($s) > 0) + { + $s .= ','; + } + $s .= $this->encode($i) . ':' . $this->encode($arg[$i]); + } + + $returnValue = '{' . $s . '}'; + } + break; + + case 'object': + foreach (get_object_vars($arg) AS $i => $v) + { + $v = $this->encode($v); + + if (strlen($s) > 0) + { + $s .= ','; + } + $s .= $this->encode($i) . ':' . $v; + } + + $returnValue = '{' . $s . '}'; + break; + + case 'integer': + case 'double': + $returnValue = is_numeric($arg) ? (string) $arg : 'null'; + break; + + case 'string': + $returnValue = '"' . strtr($arg, array( + "\r" => '\\r', "\n" => '\\n', "\t" => '\\t', "\b" => '\\b', + "\f" => '\\f', '\\' => '\\\\', '"' => '\"', + "\x00" => '\u0000', "\x01" => '\u0001', "\x02" => '\u0002', "\x03" => '\u0003', + "\x04" => '\u0004', "\x05" => '\u0005', "\x06" => '\u0006', "\x07" => '\u0007', + "\x08" => '\b', "\x0b" => '\u000b', "\x0c" => '\f', "\x0e" => '\u000e', + "\x0f" => '\u000f', "\x10" => '\u0010', "\x11" => '\u0011', "\x12" => '\u0012', + "\x13" => '\u0013', "\x14" => '\u0014', "\x15" => '\u0015', "\x16" => '\u0016', + "\x17" => '\u0017', "\x18" => '\u0018', "\x19" => '\u0019', "\x1a" => '\u001a', + "\x1b" => '\u001b', "\x1c" => '\u001c', "\x1d" => '\u001d', "\x1e" => '\u001e', + "\x1f" => '\u001f' + )) . '"'; + break; + + case 'boolean': + $returnValue = $arg?'true':'false'; + break; + + default: + $returnValue = 'null'; + } + + return $returnValue; + } + + function decode($text,$type=0) // 榛樿?type=0杩斿洖obj,type=1杩斿洖array + { + if (empty($text)) + { + return ''; + } + elseif (!is_string($text)) + { + return false; + } + + if (EC_CHARSET === 'utf-8' && function_exists('json_decode')) + { + return addslashes_deep_obj(json_decode(stripslashes($text),$type)); + } + + $this->at = 0; + $this->ch = ''; + $this->text = strtr(stripslashes($text), array( + "\r" => '', "\n" => '', "\t" => '', "\b" => '', + "\x00" => '', "\x01" => '', "\x02" => '', "\x03" => '', + "\x04" => '', "\x05" => '', "\x06" => '', "\x07" => '', + "\x08" => '', "\x0b" => '', "\x0c" => '', "\x0e" => '', + "\x0f" => '', "\x10" => '', "\x11" => '', "\x12" => '', + "\x13" => '', "\x14" => '', "\x15" => '', "\x16" => '', + "\x17" => '', "\x18" => '', "\x19" => '', "\x1a" => '', + "\x1b" => '', "\x1c" => '', "\x1d" => '', "\x1e" => '', + "\x1f" => '' + )); + + $this->next(); + $return = $this->val(); + + $result = empty($type) ? $return : $this->object_to_array($return); + + return addslashes_deep_obj($result); + } + + /** + * triggers a PHP_ERROR + * + * @access private + * @param string $m error message + * + * @return void + */ + function error($m) + { + echo($m . ' at offset ' . $this->at . ': ' . $this->text); + } + + /** + * returns the next character of a JSON string + * + * @access private + * + * @return string + */ + function next() + { + $this->ch = !isset($this->text{$this->at}) ? '' : $this->text{$this->at}; + $this->at++; + + return $this->ch; + } + + /** + * handles strings + * + * @access private + * + * @return void + */ + function str() + { + $i = ''; + $s = ''; + $t = ''; + $u = ''; + + if ($this->ch == '"') + { + while ($this->next() !== null) + { + if ($this->ch == '"') + { + $this->next(); + + return $s; + } + elseif ($this->ch == '\\') + { + switch ($this->next()) + { + case 'b': + $s .= '\b'; + break; + + case 'f': + $s .= '\f'; + break; + + case 'n': + $s .= '\n'; + break; + + case 'r': + $s .= '\r'; + break; + + case 't': + $s .= '\t'; + break; + + case 'u': + $u = 0; + + for ($i = 0; $i < 4; $i++) + { + $t = (integer) sprintf('%01c', hexdec($this->next())); + + if (!is_numeric($t)) + { + break 2; + } + $u = $u * 16 + $t; + } + + $s .= chr($u); + break; + case '\'': + $s .= '\''; + break; + default: + $s .= $this->ch; + } + } + else + { + $s .= $this->ch; + } + } + } + + $this->error('Bad string'); + } + + /** + * handless arrays + * + * @access private + * + * @return void + */ + function arr() + { + $a = array(); + + if ($this->ch == '[') + { + $this->next(); + + if ($this->ch == ']') + { + $this->next(); + + return $a; + } + + while (isset($this->ch)) + { + array_push($a, $this->val()); + + if ($this->ch == ']') + { + $this->next(); + + return $a; + + } + elseif ($this->ch != ',') + { + break; + } + + $this->next(); + + } + + $this->error('Bad array'); + } + } + + /** + * handles objects + * + * @access public + * + * @return void + */ + function obj() + { + $k = ''; + $o = new StdClass(); + + if ($this->ch == '{') + { + $this->next(); + + if ($this->ch == '}') + { + $this->next(); + + return $o; + } + + while ($this->ch) + { + $k = $this->str(); + + if ($this->ch != ':') + { + break; + } + + $this->next(); + $o->$k = $this->val(); + + if ($this->ch == '}') + { + $this->next(); + + return $o; + } + elseif ($this->ch != ',') + { + break; + } + + $this->next(); + } + } + + $this->error('Bad object'); + } + + /** + * handles objects + * + * @access public + * + * @return void + */ + function assoc() + { + $k = ''; + $a = array(); + + if ($this->ch == '<') + { + $this->next(); + + if ($this->ch == '>') + { + $this->next(); + + return $a; + } + + while ($this->ch) + { + $k = $this->str(); + + if ($this->ch != ':') + { + break; + } + + $this->next(); + $a[$k] = $this->val(); + + if ($this->ch == '>') + { + $this->next(); + + return $a; + } + elseif ($this->ch != ',') + { + break; + } + + $this->next(); + } + } + + $this->error('Bad associative array'); + } + + /** + * handles numbers + * + * @access private + * + * @return void + */ + function num() + { + $n = ''; + $v = ''; + + if ($this->ch == '-') + { + $n = '-'; + $this->next(); + } + + while ($this->ch >= '0' && $this->ch <= '9') + { + $n .= $this->ch; + $this->next(); + } + + if ($this->ch == '.') + { + $n .= '.'; + + while ($this->next() && $this->ch >= '0' && $this->ch <= '9') + { + $n .= $this->ch; + } + } + + if ($this->ch == 'e' || $this->ch == 'E') + { + $n .= 'e'; + $this->next(); + + if ($this->ch == '-' || $this->ch == '+') + { + $n .= $this->ch; + $this->next(); + } + + while ($this->ch >= '0' && $this->ch <= '9') + { + $n .= $this->ch; + $this->next(); + } + } + + $v += $n; + + if (!is_numeric($v)) + { + $this->error('Bad number'); + } + else + { + return $v; + } + } + + /** + * handles words + * + * @access private + * + * @return mixed + */ + function word() + { + switch ($this->ch) + { + case 't': + + if ($this->next() == 'r' && $this->next() == 'u' && $this->next() == 'e') + { + $this->next(); + + return true; + } + break; + + case 'f': + if ($this->next() == 'a' && $this->next() == 'l' && $this->next() == 's' && $this->next() == 'e') + { + $this->next(); + + return false; + } + break; + + case 'n': + if ($this->next() == 'u' && $this->next() == 'l' && $this->next() == 'l') + { + $this->next(); + + return null; + } + break; + } + + $this->error('Syntax error'); + } + + /** + * generic value handler + * + * @access private + * + * @return mixed + */ + function val() + { + switch ($this->ch) + { + case '{': + return $this->obj(); + + case '[': + return $this->arr(); + + case '<': + return $this->assoc(); + + case '"': + return $this->str(); + + case '-': + return $this->num(); + + default: + return ($this->ch >= '0' && $this->ch <= '9') ? $this->num() : $this->word(); + } + } + + /** + * Gets the properties of the given object recursion + * + * @access private + * + * @return array + */ + function object_to_array($obj) + { + $_arr = is_object($obj) ? get_object_vars($obj) : $obj; + foreach ($_arr as $key => $val) + { + $val = (is_array($val) || is_object($val)) ? $this->object_to_array($val) : $val; + $arr[$key] = $val; + } + return $arr; + } +} + +?> \ No newline at end of file diff --git a/includes/cls_mysql.php b/includes/cls_mysql.php new file mode 100644 index 0000000..4925d97 --- /dev/null +++ b/includes/cls_mysql.php @@ -0,0 +1,918 @@ +cls_mysql($dbhost, $dbuser, $dbpw, $dbname, $charset, $pconnect, $quiet); + } + + function cls_mysql($dbhost, $dbuser, $dbpw, $dbname = '', $charset = 'gbk', $pconnect = 0, $quiet = 0) + { + if (defined('EC_CHARSET')) + { + $charset = strtolower(str_replace('-', '', EC_CHARSET)); + } + + if (defined('ROOT_PATH') && !$this->root_path) + { + $this->root_path = ROOT_PATH; + } + + if ($quiet) + { + $this->connect($dbhost, $dbuser, $dbpw, $dbname, $charset, $pconnect, $quiet); + } + else + { + $this->settings = array( + 'dbhost' => $dbhost, + 'dbuser' => $dbuser, + 'dbpw' => $dbpw, + 'dbname' => $dbname, + 'charset' => $charset, + 'pconnect' => $pconnect + ); + } + } + + function connect($dbhost, $dbuser, $dbpw, $dbname = '', $charset = 'utf8', $pconnect = 0, $quiet = 0) + { + if ($pconnect) + { + if (!($this->link_id = @mysql_pconnect($dbhost, $dbuser, $dbpw))) + { + if (!$quiet) + { + $this->ErrorMsg("Can't pConnect MySQL Server($dbhost)!"); + } + + return false; + } + } + else + { + if (PHP_VERSION >= '4.2') + { + $this->link_id = @mysql_connect($dbhost, $dbuser, $dbpw, true); + } + else + { + $this->link_id = @mysql_connect($dbhost, $dbuser, $dbpw); + + mt_srand((double)microtime() * 1000000); // 对 PHP 4.2 以下的版本进行随机数函数的初始化工作 + } + if (!$this->link_id) + { + if (!$quiet) + { + $this->ErrorMsg("Can't Connect MySQL Server($dbhost)!"); + } + + return false; + } + } + + $this->dbhash = md5($this->root_path . $dbhost . $dbuser . $dbpw . $dbname); + $this->version = mysql_get_server_info($this->link_id); + + /* 如果mysql 版本是 4.1+ 以上,需要对字符集进行初始化 */ + if ($this->version > '4.1') + { + if ($charset != 'latin1') + { + mysql_query("SET character_set_connection=$charset, character_set_results=$charset, character_set_client=binary", $this->link_id); + } + if ($this->version > '5.0.1') + { + mysql_query("SET sql_mode=''", $this->link_id); + } + } + + $sqlcache_config_file = $this->root_path . $this->cache_data_dir . 'sqlcache_config_file_' . $this->dbhash . '.php'; + + @include($sqlcache_config_file); + + $this->starttime = time(); + + if ($this->max_cache_time && $this->starttime > $this->mysql_config_cache_file_time + $this->max_cache_time) + { + if ($dbhost != '.') + { + $result = mysql_query("SHOW VARIABLES LIKE 'basedir'", $this->link_id); + $row = mysql_fetch_assoc($result); + if (!empty($row['Value']{1}) && $row['Value']{1} == ':' && !empty($row['Value']{2}) && $row['Value']{2} == "\\") + { + $this->platform = 'WINDOWS'; + } + else + { + $this->platform = 'OTHER'; + } + } + else + { + $this->platform = 'WINDOWS'; + } + + if ($this->platform == 'OTHER' && + ($dbhost != '.' && strtolower($dbhost) != 'localhost:3306' && $dbhost != '127.0.0.1:3306') || + (PHP_VERSION >= '5.1' && date_default_timezone_get() == 'UTC')) + { + $result = mysql_query("SELECT UNIX_TIMESTAMP() AS timeline, UNIX_TIMESTAMP('" . date('Y-m-d H:i:s', $this->starttime) . "') AS timezone", $this->link_id); + $row = mysql_fetch_assoc($result); + + if ($dbhost != '.' && strtolower($dbhost) != 'localhost:3306' && $dbhost != '127.0.0.1:3306') + { + $this->timeline = $this->starttime - $row['timeline']; + } + + if (PHP_VERSION >= '5.1' && date_default_timezone_get() == 'UTC') + { + $this->timezone = $this->starttime - $row['timezone']; + } + } + + $content = '<' . "?php\r\n" . + '$this->mysql_config_cache_file_time = ' . $this->starttime . ";\r\n" . + '$this->timeline = ' . $this->timeline . ";\r\n" . + '$this->timezone = ' . $this->timezone . ";\r\n" . + '$this->platform = ' . "'" . $this->platform . "';\r\n?" . '>'; + + @file_put_contents($sqlcache_config_file, $content); + } + + /* 选择数据库 */ + if ($dbname) + { + if (mysql_select_db($dbname, $this->link_id) === false ) + { + if (!$quiet) + { + $this->ErrorMsg("Can't select MySQL database($dbname)!"); + } + + return false; + } + else + { + return true; + } + } + else + { + return true; + } + } + + function select_database($dbname) + { + return mysql_select_db($dbname, $this->link_id); + } + + function set_mysql_charset($charset) + { + /* 如果mysql 版本是 4.1+ 以上,需要对字符集进行初始化 */ + if ($this->version > '4.1') + { + if (in_array(strtolower($charset), array('gbk', 'big5', 'utf-8', 'utf8'))) + { + $charset = str_replace('-', '', $charset); + } + if ($charset != 'latin1') + { + mysql_query("SET character_set_connection=$charset, character_set_results=$charset, character_set_client=binary", $this->link_id); + } + } + } + + function fetch_array($query, $result_type = MYSQL_ASSOC) + { + return mysql_fetch_array($query, $result_type); + } + + function query($sql, $type = '') + { + if ($this->link_id === NULL) + { + $this->connect($this->settings['dbhost'], $this->settings['dbuser'], $this->settings['dbpw'], $this->settings['dbname'], $this->settings['charset'], $this->settings['pconnect']); + $this->settings = array(); + } + + if ($this->queryCount++ <= 99) + { + $this->queryLog[] = $sql; + } + if ($this->queryTime == '') + { + if (PHP_VERSION >= '5.0.0') + { + $this->queryTime = microtime(true); + } + else + { + $this->queryTime = microtime(); + } + } + + /* 当当前的时间大于类初始化时间的时候,自动执行 ping 这个自动重新连接操作 */ + if (PHP_VERSION >= '4.3' && time() > $this->starttime + 1) + { + mysql_ping($this->link_id); + } + + if (!($query = mysql_query($sql, $this->link_id)) && $type != 'SILENT') + { + $this->error_message[]['message'] = 'MySQL Query Error'; + $this->error_message[]['sql'] = $sql; + $this->error_message[]['error'] = mysql_error($this->link_id); + $this->error_message[]['errno'] = mysql_errno($this->link_id); + + $this->ErrorMsg(); + + return false; + } + + if (defined('DEBUG_MODE') && (DEBUG_MODE & 8) == 8) + { + $logfilename = $this->root_path . DATA_DIR . '/mysql_query_' . $this->dbhash . '_' . date('Y_m_d') . '.log'; + $str = $sql . "\n\n"; + + if (PHP_VERSION >= '5.0') + { + file_put_contents($logfilename, $str, FILE_APPEND); + } + else + { + $fp = @fopen($logfilename, 'ab+'); + if ($fp) + { + fwrite($fp, $str); + fclose($fp); + } + } + } + + return $query; + } + + function affected_rows() + { + return mysql_affected_rows($this->link_id); + } + + function error() + { + return mysql_error($this->link_id); + } + + function errno() + { + return mysql_errno($this->link_id); + } + + function result($query, $row) + { + return @mysql_result($query, $row); + } + + function num_rows($query) + { + return mysql_num_rows($query); + } + + function num_fields($query) + { + return mysql_num_fields($query); + } + + function free_result($query) + { + return mysql_free_result($query); + } + + function insert_id() + { + return mysql_insert_id($this->link_id); + } + + function fetchRow($query) + { + return mysql_fetch_assoc($query); + } + + function fetch_fields($query) + { + return mysql_fetch_field($query); + } + + function version() + { + return $this->version; + } + + function ping() + { + if (PHP_VERSION >= '4.3') + { + return mysql_ping($this->link_id); + } + else + { + return false; + } + } + + function escape_string($unescaped_string) + { + if (PHP_VERSION >= '4.3') + { + return mysql_real_escape_string($unescaped_string); + } + else + { + return mysql_escape_string($unescaped_string); + } + } + + function close() + { + return mysql_close($this->link_id); + } + + function ErrorMsg($message = '', $sql = '') + { + if ($message) + { + echo "ECSHOP info: $message\n\n

"; + //print('http://faq.comsenz.com/'); + } + else + { + echo "MySQL server error report:"; + print_r($this->error_message); + //echo "

http://faq.comsenz.com/"; + } + + exit; + } + +/* 仿真 Adodb 函数 */ + function selectLimit($sql, $num, $start = 0) + { + if ($start == 0) + { + $sql .= ' LIMIT ' . $num; + } + else + { + $sql .= ' LIMIT ' . $start . ', ' . $num; + } + + return $this->query($sql); + } + + function getOne($sql, $limited = false) + { + if ($limited == true) + { + $sql = trim($sql . ' LIMIT 1'); + } + + $res = $this->query($sql); + if ($res !== false) + { + $row = mysql_fetch_row($res); + + if ($row !== false) + { + return $row[0]; + } + else + { + return ''; + } + } + else + { + return false; + } + } + + function getOneCached($sql, $cached = 'FILEFIRST') + { + $sql = trim($sql . ' LIMIT 1'); + + $cachefirst = ($cached == 'FILEFIRST' || ($cached == 'MYSQLFIRST' && $this->platform != 'WINDOWS')) && $this->max_cache_time; + if (!$cachefirst) + { + return $this->getOne($sql, true); + } + else + { + $result = $this->getSqlCacheData($sql, $cached); + if (empty($result['storecache']) == true) + { + return $result['data']; + } + } + + $arr = $this->getOne($sql, true); + + if ($arr !== false && $cachefirst) + { + $this->setSqlCacheData($result, $arr); + } + + return $arr; + } + + function getAll($sql) + { + $res = $this->query($sql); + if ($res !== false) + { + $arr = array(); + while ($row = mysql_fetch_assoc($res)) + { + $arr[] = $row; + } + + return $arr; + } + else + { + return false; + } + } + + function getAllCached($sql, $cached = 'FILEFIRST') + { + $cachefirst = ($cached == 'FILEFIRST' || ($cached == 'MYSQLFIRST' && $this->platform != 'WINDOWS')) && $this->max_cache_time; + if (!$cachefirst) + { + return $this->getAll($sql); + } + else + { + $result = $this->getSqlCacheData($sql, $cached); + if (empty($result['storecache']) == true) + { + return $result['data']; + } + } + + $arr = $this->getAll($sql); + + if ($arr !== false && $cachefirst) + { + $this->setSqlCacheData($result, $arr); + } + + return $arr; + } + + function getRow($sql, $limited = false) + { + if ($limited == true) + { + $sql = trim($sql . ' LIMIT 1'); + } + + $res = $this->query($sql); + if ($res !== false) + { + return mysql_fetch_assoc($res); + } + else + { + return false; + } + } + + function getRowCached($sql, $cached = 'FILEFIRST') + { + $sql = trim($sql . ' LIMIT 1'); + + $cachefirst = ($cached == 'FILEFIRST' || ($cached == 'MYSQLFIRST' && $this->platform != 'WINDOWS')) && $this->max_cache_time; + if (!$cachefirst) + { + return $this->getRow($sql, true); + } + else + { + $result = $this->getSqlCacheData($sql, $cached); + if (empty($result['storecache']) == true) + { + return $result['data']; + } + } + + $arr = $this->getRow($sql, true); + + if ($arr !== false && $cachefirst) + { + $this->setSqlCacheData($result, $arr); + } + + return $arr; + } + + function getCol($sql) + { + $res = $this->query($sql); + if ($res !== false) + { + $arr = array(); + while ($row = mysql_fetch_row($res)) + { + $arr[] = $row[0]; + } + + return $arr; + } + else + { + return false; + } + } + + function getColCached($sql, $cached = 'FILEFIRST') + { + $cachefirst = ($cached == 'FILEFIRST' || ($cached == 'MYSQLFIRST' && $this->platform != 'WINDOWS')) && $this->max_cache_time; + if (!$cachefirst) + { + return $this->getCol($sql); + } + else + { + $result = $this->getSqlCacheData($sql, $cached); + if (empty($result['storecache']) == true) + { + return $result['data']; + } + } + + $arr = $this->getCol($sql); + + if ($arr !== false && $cachefirst) + { + $this->setSqlCacheData($result, $arr); + } + + return $arr; + } + + function autoExecute($table, $field_values, $mode = 'INSERT', $where = '', $querymode = '') + { + $field_names = $this->getCol('DESC ' . $table); + + $sql = ''; + if ($mode == 'INSERT') + { + $fields = $values = array(); + foreach ($field_names AS $value) + { + if (array_key_exists($value, $field_values) == true) + { + $fields[] = $value; + $values[] = "'" . $field_values[$value] . "'"; + } + } + + if (!empty($fields)) + { + $sql = 'INSERT INTO ' . $table . ' (' . implode(', ', $fields) . ') VALUES (' . implode(', ', $values) . ')'; + } + } + else + { + $sets = array(); + foreach ($field_names AS $value) + { + if (array_key_exists($value, $field_values) == true) + { + $sets[] = $value . " = '" . $field_values[$value] . "'"; + } + } + + if (!empty($sets)) + { + $sql = 'UPDATE ' . $table . ' SET ' . implode(', ', $sets) . ' WHERE ' . $where; + } + } + + if ($sql) + { + return $this->query($sql, $querymode); + } + else + { + return false; + } + } + + function autoReplace($table, $field_values, $update_values, $where = '', $querymode = '') + { + $field_descs = $this->getAll('DESC ' . $table); + + $primary_keys = array(); + foreach ($field_descs AS $value) + { + $field_names[] = $value['Field']; + if ($value['Key'] == 'PRI') + { + $primary_keys[] = $value['Field']; + } + } + + $fields = $values = array(); + foreach ($field_names AS $value) + { + if (array_key_exists($value, $field_values) == true) + { + $fields[] = $value; + $values[] = "'" . $field_values[$value] . "'"; + } + } + + $sets = array(); + foreach ($update_values AS $key => $value) + { + if (array_key_exists($key, $field_values) == true) + { + if (is_int($value) || is_float($value)) + { + $sets[] = $key . ' = ' . $key . ' + ' . $value; + } + else + { + $sets[] = $key . " = '" . $value . "'"; + } + } + } + + $sql = ''; + if (empty($primary_keys)) + { + if (!empty($fields)) + { + $sql = 'INSERT INTO ' . $table . ' (' . implode(', ', $fields) . ') VALUES (' . implode(', ', $values) . ')'; + } + } + else + { + if ($this->version() >= '4.1') + { + if (!empty($fields)) + { + $sql = 'INSERT INTO ' . $table . ' (' . implode(', ', $fields) . ') VALUES (' . implode(', ', $values) . ')'; + if (!empty($sets)) + { + $sql .= 'ON DUPLICATE KEY UPDATE ' . implode(', ', $sets); + } + } + } + else + { + if (empty($where)) + { + $where = array(); + foreach ($primary_keys AS $value) + { + if (is_numeric($value)) + { + $where[] = $value . ' = ' . $field_values[$value]; + } + else + { + $where[] = $value . " = '" . $field_values[$value] . "'"; + } + } + $where = implode(' AND ', $where); + } + + if ($where && (!empty($sets) || !empty($fields))) + { + if (intval($this->getOne("SELECT COUNT(*) FROM $table WHERE $where")) > 0) + { + if (!empty($sets)) + { + $sql = 'UPDATE ' . $table . ' SET ' . implode(', ', $sets) . ' WHERE ' . $where; + } + } + else + { + if (!empty($fields)) + { + $sql = 'REPLACE INTO ' . $table . ' (' . implode(', ', $fields) . ') VALUES (' . implode(', ', $values) . ')'; + } + } + } + } + } + + if ($sql) + { + return $this->query($sql, $querymode); + } + else + { + return false; + } + } + + function setMaxCacheTime($second) + { + $this->max_cache_time = $second; + } + + function getMaxCacheTime() + { + return $this->max_cache_time; + } + + function getSqlCacheData($sql, $cached = '') + { + $sql = trim($sql); + + $result = array(); + $result['filename'] = $this->root_path . $this->cache_data_dir . 'sqlcache_' . abs(crc32($this->dbhash . $sql)) . '_' . md5($this->dbhash . $sql) . '.php'; + + $data = @file_get_contents($result['filename']); + if (isset($data{23})) + { + $filetime = substr($data, 13, 10); + $data = substr($data, 23); + + if (($cached == 'FILEFIRST' && time() > $filetime + $this->max_cache_time) || ($cached == 'MYSQLFIRST' && $this->table_lastupdate($this->get_table_name($sql)) > $filetime)) + { + $result['storecache'] = true; + } + else + { + $result['data'] = @unserialize($data); + if ($result['data'] === false) + { + $result['storecache'] = true; + } + else + { + $result['storecache'] = false; + } + } + } + else + { + $result['storecache'] = true; + } + + return $result; + } + + function setSqlCacheData($result, $data) + { + if ($result['storecache'] === true && $result['filename']) + { + @file_put_contents($result['filename'], '' . time() . serialize($data)); + clearstatcache(); + } + } + + /* 获取 SQL 语句中最后更新的表的时间,有多个表的情况下,返回最新的表的时间 */ + function table_lastupdate($tables) + { + if ($this->link_id === NULL) + { + $this->connect($this->settings['dbhost'], $this->settings['dbuser'], $this->settings['dbpw'], $this->settings['dbname'], $this->settings['charset'], $this->settings['pconnect']); + $this->settings = array(); + } + + $lastupdatetime = '0000-00-00 00:00:00'; + + $tables = str_replace('`', '', $tables); + $this->mysql_disable_cache_tables = str_replace('`', '', $this->mysql_disable_cache_tables); + + foreach ($tables AS $table) + { + if (in_array($table, $this->mysql_disable_cache_tables) == true) + { + $lastupdatetime = '2037-12-31 23:59:59'; + + break; + } + + if (strstr($table, '.') != NULL) + { + $tmp = explode('.', $table); + $sql = 'SHOW TABLE STATUS FROM `' . trim($tmp[0]) . "` LIKE '" . trim($tmp[1]) . "'"; + } + else + { + $sql = "SHOW TABLE STATUS LIKE '" . trim($table) . "'"; + } + $result = mysql_query($sql, $this->link_id); + + $row = mysql_fetch_assoc($result); + if ($row['Update_time'] > $lastupdatetime) + { + $lastupdatetime = $row['Update_time']; + } + } + $lastupdatetime = strtotime($lastupdatetime) - $this->timezone + $this->timeline; + + return $lastupdatetime; + } + + function get_table_name($query_item) + { + $query_item = trim($query_item); + $table_names = array(); + + /* 判断语句中是不是含有 JOIN */ + if (stristr($query_item, ' JOIN ') == '') + { + /* 解析一般的 SELECT FROM 语句 */ + if (preg_match('/^SELECT.*?FROM\s*((?:`?\w+`?\s*\.\s*)?`?\w+`?(?:(?:\s*AS)?\s*`?\w+`?)?(?:\s*,\s*(?:`?\w+`?\s*\.\s*)?`?\w+`?(?:(?:\s*AS)?\s*`?\w+`?)?)*)/is', $query_item, $table_names)) + { + $table_names = preg_replace('/((?:`?\w+`?\s*\.\s*)?`?\w+`?)[^,]*/', '\1', $table_names[1]); + + return preg_split('/\s*,\s*/', $table_names); + } + } + else + { + /* 对含有 JOIN 的语句进行解析 */ + if (preg_match('/^SELECT.*?FROM\s*((?:`?\w+`?\s*\.\s*)?`?\w+`?)(?:(?:\s*AS)?\s*`?\w+`?)?.*?JOIN.*$/is', $query_item, $table_names)) + { + $other_table_names = array(); + preg_match_all('/JOIN\s*((?:`?\w+`?\s*\.\s*)?`?\w+`?)\s*/i', $query_item, $other_table_names); + + return array_merge(array($table_names[1]), $other_table_names[1]); + } + } + + return $table_names; + } + + /* 设置不允许进行缓存的表 */ + function set_disable_cache_tables($tables) + { + if (!is_array($tables)) + { + $tables = explode(',', $tables); + } + + foreach ($tables AS $table) + { + $this->mysql_disable_cache_tables[] = $table; + } + + array_unique($this->mysql_disable_cache_tables); + } +} + +?> \ No newline at end of file diff --git a/includes/cls_rss.php b/includes/cls_rss.php new file mode 100644 index 0000000..2c03c17 --- /dev/null +++ b/includes/cls_rss.php @@ -0,0 +1,1725 @@ + +// @copyright Michael Wimmer +// @link http://www.flaimo.com/ +// @global array $GLOBALS['_TICKER_ini_settings'] +// @abstract +// @package RSSBuilder +// @category FLP +// @version 1.001 +/*-----------------------------------------------------------------------*/ + +class RSSBase +{ + /*-----------------------*/ + /* C O N S T R U C T O R */ + /*-----------------------*/ + + //------------------------------------------------- + // Constructor + //------------------------------------------------- + // @desc Constructor + // @return (void) + // @access private + //------------------------------------------------- + function RSSBase() { + } // end constructor + +} // end class RSSBase + +//--------------------------------------------------------------------------- + +/*-----------------------------------------------------------------------*/ +// Class for creating a RSS file +//------------------------------------------------- +// Tested with WAMP (XP-SP1/1.3.24/4.0.12/4.3.0) +// Last change: 2003-05-30 +//------------------------------------------------- +// @desc Class for creating a RSS file +// @access public +// @author Michael Wimmer +// @copyright Michael Wimmer +// @link http://www.flaimo.com/ +// @example rss_sample_script.php Sample script +// @package RSSBuilder +// @category FLP +// @version 1.001 +/*-----------------------------------------------------------------------*/ +class RSSBuilder extends RSSBase +{ + /*-----------------------------------------------------------------------*/ + /* V A R I A B L E S + /*-----------------------------------------------------------------------*/ + + //------------------------------------------------- + // encoding of the XML file + //------------------------------------------------- + // @desc encoding of the XML file + // @var string + // @access private + //------------------------------------------------- + var $encoding; + + //------------------------------------------------- + // URL where the RSS document will be made available + //------------------------------------------------- + // @desc URL where the RSS document will be made available + // @var string + // @access private + //------------------------------------------------- + var $about; + + //------------------------------------------------- + // title of the rss stream + //------------------------------------------------- + // @desc title of the rss stream + // @var string + // @access private + //------------------------------------------------- + var $title; + + //------------------------------------------------- + // description of the rss stream + //------------------------------------------------- + // @desc description of the rss stream + // @var string + // @access private + //------------------------------------------------- + var $description; + + //------------------------------------------------- + // publisher of the rss stream (person, an organization, or a service) + //------------------------------------------------- + // @desc publisher of the rss stream + // @var string + // @access private + //------------------------------------------------- + var $publisher; + + //------------------------------------------------- + // creator of the rss stream (person, an organization, or a service) + //------------------------------------------------- + // @desc creator of the rss stream + // @var string + // @access private + //------------------------------------------------- + var $creator; + + //------------------------------------------------- + // creation date of the file (format: 2003-05-29T00:03:07+0200) + //------------------------------------------------- + // @desc creation date of the file (format: 2003-05-29T00:03:07+0200) + // @var string + // @access private + //------------------------------------------------- + var $date; + + //------------------------------------------------- + // iso format language + //------------------------------------------------- + // @desc iso format language + // @var string + // @access private + //------------------------------------------------- + var $language; + + //------------------------------------------------- + // copyrights for the rss stream + //------------------------------------------------- + // @desc copyrights for the rss stream + // @var string + // @access private + //------------------------------------------------- + var $rights; + + //------------------------------------------------- + // URL to an small image + //------------------------------------------------- + // @desc URL to an small image + // @var string + // @access private + //------------------------------------------------- + var $image_link; + + //------------------------------------------------- + // spatial location (a place name or geographic coordinates), temporal period (a period label, date, or date range) or jurisdiction (such as a named administrative entity) + //------------------------------------------------- + // @desc spatial location (a place name or geographic coordinates), temporal period (a period label, date, or date range) or jurisdiction (such as a named administrative entity) + // @var string + // @access private + //------------------------------------------------- + var $coverage; + + //------------------------------------------------- + // person, an organization, or a service + //------------------------------------------------- + // @desc person, an organization, or a service + // @var string + // @access private + //------------------------------------------------- + var $contributor; + + //------------------------------------------------- + // 'hourly' | 'daily' | 'weekly' | 'monthly' | 'yearly' + //------------------------------------------------- + // @desc 'hourly' | 'daily' | 'weekly' | 'monthly' | 'yearly' + // @var string + // @access private + //------------------------------------------------- + var $period; + + //------------------------------------------------- + // every X hours/days/weeks/... + //------------------------------------------------- + // @desc every X hours/days/weeks/... + // @var int + // @access private + //------------------------------------------------- + var $frequency; + + //------------------------------------------------- + // date (format: 2003-05-29T00:03:07+0200) + //------------------------------------------------- + // Defines a base date to be used in concert with updatePeriod and + // updateFrequency to calculate the publishing schedule. + //------------------------------------------------- + // @desc base date to calculate from (format: 2003-05-29T00:03:07+0200) + // @var string + // @access private + //------------------------------------------------- + var $base; + + //------------------------------------------------- + // category (rss 2.0) + //------------------------------------------------- + // @desc category (rss 2.0) + // @var string + // @access private + // @since 1.001 - 2003/05/30 + //------------------------------------------------- + var $category; + + //------------------------------------------------- + // caching time in minutes (rss 2.0) + //------------------------------------------------- + // @desc caching time in minutes (rss 2.0) + // @var int + // @access private + // @since 1.001 - 2003/05/30 + //------------------------------------------------- + var $cache; + + //------------------------------------------------- + // array wich all the rss items + //------------------------------------------------- + // @desc array wich all the rss items + // @var array + // @access private + //------------------------------------------------- + var $items = array(); + + //------------------------------------------------- + // compiled outputstring + //------------------------------------------------- + // @desc compiled outputstring + // @var string + // @access private + //------------------------------------------------- + var $output; + + //------------------------------------------------- + // use DC data + //------------------------------------------------- + // @desc use DC data + // @var boolean + // @access private + //------------------------------------------------- + var $use_dc_data = false; + + //------------------------------------------------- + // use SY data + //------------------------------------------------- + // @desc use SY data + // @var boolean + // @access private + //------------------------------------------------- + var $use_sy_data = false; + + /*-----------------------*/ + /* C O N S T R U C T O R */ + /*-----------------------*/ + + //------------------------------------------------- + // Constructor + //------------------------------------------------- + // @desc Constructor + // @param (string) $encoding encoding of the xml file + // @param (string) $about URL where the RSS document will be made available + // @param (string) $title + // @param (string) $description + // @param (string) $image_link URL + // @return (void) + // @uses setEncoding(), setAbout(), setTitle(), setDescription(), setImageLink(), setCategory(), setCache() + // @access private + //------------------------------------------------- + function RSSBuilder($encoding = '', + $about = '', + $title = '', + $description = '', + $image_link = '', + $category = '', + $cache = '') { + $this->setEncoding($encoding); + $this->setAbout($about); + $this->setTitle($title); + $this->setDescription($description); + $this->setImageLink($image_link); + $this->setCategory($category); + $this->setCache($cache); + } // end constructor + + /*-----------------------------------------------------------------------*/ + /* F U N C T I O N S */ + /*-----------------------------------------------------------------------*/ + + //------------------------------------------------- + // add additional DC data + //------------------------------------------------- + // @desc add additional DC data + // @param (string) $publisher person, an organization, or a service + // @param (string) $creator person, an organization, or a service + // @param (string) $date format: 2003-05-29T00:03:07+0200 + // @param (string) $language iso-format + // @param (string) $rights copyright information + // @param (string) $coverage spatial location (a place name or geographic coordinates), temporal period (a period label, date, or date range) or jurisdiction (such as a named administrative entity) + // @param (string) $contributor person, an organization, or a service + // @return (void) + // @uses setPublisher(), setCreator(), setDate(), setLanguage(), setRights(), setCoverage(), setContributor() + // @access public + //------------------------------------------------- + function addDCdata($publisher = '', + $creator = '', + $date = '', + $language = '', + $rights = '', + $coverage = '', + $contributor = '') { + $this->setPublisher($publisher); + $this->setCreator($creator); + $this->setDate($date); + $this->setLanguage($language); + $this->setRights($rights); + $this->setCoverage($coverage); + $this->setContributor($contributor); + $this->use_dc_data = (boolean) true; + } // end function + + //------------------------------------------------- + // add additional SY data + //------------------------------------------------- + // @desc add additional DC data + // @param (string) $period 'hourly' | 'daily' | 'weekly' | 'monthly' | 'yearly' + // @param (int) $frequency every x hours/days/weeks/... + // @param (string) $base format: 2003-05-29T00:03:07+0200 + // @return (void) + // @uses setPeriod(), setFrequency(), setBase() + // @access public + //------------------------------------------------- + function addSYdata($period = '', $frequency = '', $base = '') { + $this->setPeriod($period); + $this->setFrequency($frequency); + $this->setBase($base); + $this->use_sy_data = (boolean) true; + } // end function + + //------------------------------------------------- + // Checks if a given string is a valid iso-language-code + //------------------------------------------------- + // @desc Checks if a given string is a valid iso-language-code + // @param (string) $code String that should validated + // @return (boolean) $isvalid If string is valid or not + // @access public + // @static + //------------------------------------------------- + function isValidLanguageCode($code = '') { + return (boolean) ((preg_match('(^([a-zA-Z]{2})$)',$code) > 0) ? true : false); + } // end function + + //------------------------------------------------- + // Sets $encoding variable + //------------------------------------------------- + // @desc Sets $encoding variable + // @param (string) $encoding encoding of the xml file + // @return (void) + // @access private + // @see $encoding + //------------------------------------------------- + function setEncoding($encoding = '') { + if (!isset($this->encoding)) { + $this->encoding = (string) ((strlen(trim($encoding)) > 0) ? trim($encoding) : 'UTF-8'); + } // end if + } // end function + + //------------------------------------------------- + // Sets $about variable + //------------------------------------------------- + // @desc Sets $about variable + // @param (string) $about + // @return (void) + // @access private + // @see $about + //------------------------------------------------- + function setAbout($about = '') { + if (!isset($this->about) && strlen(trim($about)) > 0) { + $this->about = (string) trim($about); + } // end if + } // end function + + //------------------------------------------------- + // Sets $title variable + //------------------------------------------------- + // @desc Sets $title variable + // @param (string) $title + // @return (void) + // @access private + // @see $title + //------------------------------------------------- + function setTitle($title = '') { + if (!isset($this->title) && strlen(trim($title)) > 0) { + $this->title = (string) trim($title); + } // end if + } // end function + + //------------------------------------------------- + // Sets $description variable + //------------------------------------------------- + // @desc Sets $description variable + // @param (string) $description + // @return (void) + // @access private + // @see $description + //------------------------------------------------- + function setDescription($description = '') { + if (!isset($this->description) && strlen(trim($description)) > 0) { + $this->description = (string) trim($description); + } // end if + } // end function + + //------------------------------------------------- + // Sets $publisher variable + //------------------------------------------------- + // @desc Sets $publisher variable + // @param (string) $publisher + // @return (void) + // @access private + // @see $publisher + //------------------------------------------------- + function setPublisher($publisher = '') { + if (!isset($this->publisher) && strlen(trim($publisher)) > 0) { + $this->publisher = (string) trim($publisher); + } // end if + } // end function + + //------------------------------------------------- + // Sets $creator variable + //------------------------------------------------- + // @desc Sets $creator variable + // @param (string) $creator + // @return (void) + // @access private + // @see $creator + //------------------------------------------------- + function setCreator($creator = '') { + if (!isset($this->creator) && strlen(trim($creator)) > 0) { + $this->creator = (string) trim($creator); + } // end if + } // end function + + //------------------------------------------------- + // Sets $date variable + //------------------------------------------------- + // @desc Sets $date variable + // @param (string) $date format: 2003-05-29T00:03:07+0200 + // @return (void) + // @access private + // @see $date + //------------------------------------------------- + function setDate($date = '') { + if (!isset($this->date) && strlen(trim($date)) > 0) { + $this->date = (string) trim($date); + } // end if + } // end function + + //------------------------------------------------- + // Sets $language variable + //------------------------------------------------- + // @desc Sets $language variable + // @param (string) $language + // @return (void) + // @access private + // @see $language + // @uses isValidLanguageCode() + //------------------------------------------------- + function setLanguage($language = '') { + if (!isset($this->language) && $this->isValidLanguageCode($language) === true) { + $this->language = (string) trim($language); + } // end if + } // end function + + //------------------------------------------------- + // Sets $rights variable + //------------------------------------------------- + // @desc Sets $rights variable + // @param (string) $rights + // @return (void) + // @access private + // @see $rights + //------------------------------------------------- + function setRights($rights = '') { + if (!isset($this->rights) && strlen(trim($rights)) > 0) { + $this->rights = (string) trim($rights); + } // end if + } // end function + + //------------------------------------------------- + // Sets $coverage variable + //------------------------------------------------- + // @desc Sets $coverage variable + // @param (string) $coverage + // @return (void) + // @access private + // @see $coverage + //------------------------------------------------- + function setCoverage($coverage = '') { + if (!isset($this->coverage) && strlen(trim($coverage)) > 0) { + $this->coverage = (string) trim($coverage); + } // end if + } // end function + + //------------------------------------------------- + // Sets $contributor variable + //------------------------------------------------- + // @desc Sets $contributor variable + // @param (string) $contributor + // @return (void) + // @access private + // @see $contributor + //------------------------------------------------- + function setContributor($contributor = '') { + if (!isset($this->contributor) && strlen(trim($contributor)) > 0) { + $this->contributor = (string) trim($contributor); + } // end if + } // end function + + //------------------------------------------------- + // Sets $image_link variable + //------------------------------------------------- + // @desc Sets $image_link variable + // @param (string) $image_link + // @return (void) + // @access private + // @see $image_link + //------------------------------------------------- + function setImageLink($image_link = '') { + if (!isset($this->image_link) && strlen(trim($image_link)) > 0) { + $this->image_link = (string) trim($image_link); + } // end if + } // end function + + //------------------------------------------------- + // Sets $period variable + //------------------------------------------------- + // @desc Sets $period variable + // @param (string) $period 'hourly' | 'daily' | 'weekly' | 'monthly' | 'yearly' + // @return (void) + // @access private + // @see $period + //------------------------------------------------- + function setPeriod($period = '') { + if (!isset($this->period) && strlen(trim($period)) > 0) { + switch ($period) { + case 'hourly': + case 'daily': + case 'weekly': + case 'monthly': + case 'yearly': + $this->period = (string) trim($period); + break; + default: + $this->period = (string) ''; + break; + } // end switch + } // end if + } // end function + + //------------------------------------------------- + // Sets $frequency variable + //------------------------------------------------- + // @desc Sets $frequency variable + // @param (int) $frequency + // @return (void) + // @access private + // @see $frequency + //------------------------------------------------- + function setFrequency($frequency = '') { + if (!isset($this->frequency) && strlen(trim($frequency)) > 0) { + $this->frequency = (int) $frequency; + } // end if + } // end function + + //------------------------------------------------- + // Sets $base variable + //------------------------------------------------- + // @desc Sets $base variable + // @param (string) $base + // @return (void) + // @access private + // @see $base + //------------------------------------------------- + function setBase($base = '') { + if (!isset($this->base) && strlen(trim($base)) > 0) { + $this->base = (string) trim($base); + } // end if + } // end function + + //------------------------------------------------- + // Sets $category variable + //------------------------------------------------- + // @desc Sets $category variable + // @param (string) $category + // @return (void) + // @access private + // @see $category + // @since 1.001 - 2003/05/30 + //------------------------------------------------- + function setCategory($category = '') { + if (strlen(trim($category)) > 0) { + $this->category = (string) trim($category); + } // end if + } // end function + + //------------------------------------------------- + // Sets $cache variable + //------------------------------------------------- + // @desc Sets $cache variable + // @param (int) $cache + // @return (void) + // @access private + // @see $cache + // @since 1.001 - 2003/05/30 + //------------------------------------------------- + function setCache($cache = '') { + if (strlen(trim($cache)) > 0) { + $this->cache = (int) $cache; + } // end if + } // end function + + //------------------------------------------------- + // Returns $encoding variable + //------------------------------------------------- + // @desc Returns $encoding variable + // @return (string) $encoding + // @access public + // @see $image_link + //------------------------------------------------- + function getEncoding() { + return (string) $this->encoding; + } // end function + + //------------------------------------------------- + // Returns $about variable + //------------------------------------------------- + // @desc Returns $about variable + // @return (string) $about + // @access public + // @see $about + //------------------------------------------------- + function getAbout() { + return (string) $this->about; + } // end function + + //------------------------------------------------- + // Returns $title variable + //------------------------------------------------- + // @desc Returns $title variable + // @return (string) $title + // @access public + // @see $title + //------------------------------------------------- + function getTitle() { + return (string) $this->title; + } // end function + + //------------------------------------------------- + // Returns $description variable + //------------------------------------------------- + // @desc Returns $description variable + // @return (string) $description + // @access public + // @see $description + //------------------------------------------------- + function getDescription() { + return (string) $this->description; + } // end function + + //------------------------------------------------- + // Returns $publisher variable + //------------------------------------------------- + // @desc Returns $publisher variable + // @return (string) $publisher + // @access public + // @see $publisher + //------------------------------------------------- + function getPublisher() { + return (string) $this->publisher; + } // end function + + //------------------------------------------------- + // Returns $creator variable + //------------------------------------------------- + // @desc Returns $creator variable + // @return (string) $creator + // @access public + // @see $creator + //------------------------------------------------- + function getCreator() { + return (string) $this->creator; + } // end function + + //------------------------------------------------- + // Returns $date variable + //------------------------------------------------- + // @desc Returns $date variable + // @return (string) $date + // @access public + // @see $date + //------------------------------------------------- + function getDate() { + return (string) $this->date; + } // end function + + //------------------------------------------------- + // Returns $language variable + //------------------------------------------------- + // @desc Returns $language variable + // @return (string) $language + // @access public + // @see $language + //------------------------------------------------- + function getLanguage() { + return (string) $this->language; + } // end function + + //------------------------------------------------- + // Returns $rights variable + //------------------------------------------------- + // @desc Returns $rights variable + // @return (string) $rights + // @access public + // @see $rights + //------------------------------------------------- + function getRights() { + return (string) $this->rights; + } // end function + + //------------------------------------------------- + // Returns $coverage variable + //------------------------------------------------- + // @desc Returns $coverage variable + // @return (string) $coverage + // @access public + // @see $coverage + //------------------------------------------------- + function getCoverage() { + return (string) $this->coverage; + } // end function + + //------------------------------------------------- + // Returns $contributor variable + //------------------------------------------------- + // @desc Returns $contributor variable + // @return (string) $contributor + // @access public + // @see $contributor + //------------------------------------------------- + function getContributor() { + return (string) $this->contributor; + } // end function + + //------------------------------------------------- + // Returns $image_link variable + //------------------------------------------------- + // @desc Returns $image_link variable + // @return (string) $image_link + // @access public + // @see $image_link + //------------------------------------------------- + function getImageLink() { + return (string) $this->image_link; + } // end function + + //------------------------------------------------- + // Returns $period variable + //------------------------------------------------- + // @desc Returns $period variable + // @return (string) $period + // @access public + // @see $period + //------------------------------------------------- + function getPeriod() { + return (string) $this->period; + } // end function + + //------------------------------------------------- + // Returns $frequency variable + //------------------------------------------------- + // @desc Returns $frequency variable + // @return (string) $frequency + // @access public + // @see $frequency + //------------------------------------------------- + function getFrequency() { + return (int) $this->frequency; + } // end function + + //------------------------------------------------- + // Returns $base variable + //------------------------------------------------- + // @desc Returns $base variable + // @return (string) $base + // @access public + // @see $base + //------------------------------------------------- + function getBase() { + return (string) $this->base; + } // end function + + //------------------------------------------------- + // Returns $category variable + //------------------------------------------------- + // @desc Returns $category variable + // @return (string) $category + // @access public + // @see $category + // @since 1.001 - 2003/05/30 + //------------------------------------------------- + function getCategory() { + return (string) $this->category; + } // end function + + //------------------------------------------------- + // Returns $cache variable + //------------------------------------------------- + // @desc Returns $cache variable + // @return (int) $cache + // @access public + // @see $cache + // @since 1.001 - 2003/05/30 + //------------------------------------------------- + function getCache() { + return (int) $this->cache; + } // end function + + //------------------------------------------------- + // Adds another rss item to the object + //------------------------------------------------- + // @desc Adds another rss item to the object + // @param (string) $about URL + // @param (string) $title + // @param (string) $link URL + // @param (string) $description (optional) + // @param (string) $subject some sort of category (optional dc value - only shows up if DC data has been set before) + // @param (string) $date format: 2003-05-29T00:03:07+0200 (optional dc value - only shows up if DC data has been set before) + // @return (void) + // @access public + // @see $items + // @uses RSSItem + //------------------------------------------------- + function addItem($about = '', + $title = '', + $link = '', + $description = '', + $subject = '', + $date = '', + $author = '', + $comments = '') + { + $item = new RSSItem($about, + $title, + $link, + $description, + $subject, + $date, + $author = '', + $comments = ''); + $this->items[] = $item; + } // end function + + //------------------------------------------------- + // Deletes a rss item from the array + //------------------------------------------------- + // @desc Deletes a rss item from the array + // @param (int) $id id of the element in the $items array + // @return (boolean) true if item was deleted + // @access public + // @see $items + //------------------------------------------------- + function deleteItem($id = -1) { + if (array_key_exists($id, $this->items)) { + unset($this->items[$id]); + return (boolean) true; + } else { + return (boolean) false; + } // end if + } // end function + + //------------------------------------------------- + // Returns an array with all the keys of the $items array + //------------------------------------------------- + // @desc Returns an array with all the keys of the $items array + // @return (array) array with all the keys of the $items array + // @access public + // @see $items + //------------------------------------------------- + function getItemList() { + return (array) array_keys($this->items); + } // end function + + //------------------------------------------------- + // Returns the $items array + //------------------------------------------------- + // @desc Returns the $items array + // @return (array) $items + // @access public + //------------------------------------------------- + function getItems() { + return (array) $this->items; + } // end function + + //------------------------------------------------- + // Returns a single rss item by ID + //------------------------------------------------- + // @desc Returns a single rss item by ID + // @param (int) $id id of the element in the $items array + // @return (mixed) RSSItem or false + // @access public + // @see RSSItem + //------------------------------------------------- + function getItem($id = -1) { + if (array_key_exists($id, $this->items)) { + return (object) $this->items[$id]; + } else { + return (boolean) false; + } // end if + } // end function + + //------------------------------------------------- + // creates the output based on the 0.91 rss version + //------------------------------------------------- + // @desc creates the output based on the 0.91 rss version + // @return (void) + // @access private + // @see $output + //------------------------------------------------- + function createOutputV090() { + // not implemented + $this->createOutputV100(); + } // end function + + //------------------------------------------------- + // creates the output based on the 0.91 rss version + //------------------------------------------------- + // @desc creates the output based on the 0.91 rss version + // @return (void) + // @access private + // @see $output + // @since 1.001 - 2003/05/30 + //------------------------------------------------- + function createOutputV091() { + $this->output = (string) '' . "\n"; + $this->output .= (string) '' . "\n"; + $this->output .= (string) '' . "\n"; + + if (strlen($this->rights) > 0) { + $this->output .= (string) '' . $this->rights . '' . "\n"; + } // end if + + if (strlen($this->date) > 0) { + $this->output .= (string) '' .$this->date . '' . "\n"; + $this->output .= (string) '' .$this->date . '' . "\n"; + } // end if + + if (strlen($this->about) > 0) { + $this->output .= (string) '' . $this->about . '' . "\n"; + } // end if + + if (strlen($this->description) > 0) { + $this->output .= (string) '' . $this->description . '' . "\n"; + } // end if + + if (strlen($this->about) > 0) { + $this->output .= (string) '' . $this->about . '' . "\n"; + } // end if + + if (strlen($this->title) > 0) { + $this->output .= (string) '' . $this->title . '' . "\n"; + } // end if + + if (strlen($this->image_link) > 0) { + $this->output .= (string) '' . "\n"; + $this->output .= (string) '' . $this->title . '' . "\n"; + $this->output .= (string) '' . $this->image_link . '' . "\n"; + $this->output .= (string) '' . $this->about . '' . "\n"; + if (strlen($this->description) > 0) { + $this->output .= (string) '' . $this->description . '' . "\n"; + } // end if + $this->output .= (string) '' . "\n"; + } // end if + + if (strlen($this->publisher) > 0) { + $this->output .= (string) '' . $this->publisher . '' . "\n"; + } // end if + + if (strlen($this->creator) > 0) { + $this->output .= (string) '' . $this->creator . '' . "\n"; + } // end if + + if (strlen($this->language) > 0) { + $this->output .= (string) '' . $this->language . '' . "\n"; + } // end if + + if (count($this->getItemList()) > 0) { + foreach ($this->getItemList() AS $id) { + $item =& $this->items[$id]; + + if (strlen($item->getTitle()) > 0 && strlen($item->getLink()) > 0) { + $this->output .= (string) '' . "\n"; + $this->output .= (string) '' . $item->getTitle() . '' . "\n"; + $this->output .= (string) '' . $item->getLink() . '' . "\n"; + if (strlen($item->getDescription()) > 0) { + $this->output .= (string) '' . $item->getDescription() . '' . "\n"; + } // end if + $this->output .= (string) '' . "\n"; + } // end if + } // end foreach + } // end if + + $this->output .= (string) '' . "\n"; + $this->output .= (string) '' . "\n"; + } // end function + + //------------------------------------------------- + // creates the output based on the 1.0 rss version + //------------------------------------------------- + // @desc creates the output based on the 1.0 rss version + // @return (void) + // @access private + // @see $output + //------------------------------------------------- + function createOutputV100() { + $this->output = (string) 'use_dc_data === true) { + $this->output .= (string) 'xmlns:dc="http://purl.org/dc/elements/1.1/" '; + } // end if + + if ($this->use_sy_data === true) { + $this->output .= (string) 'xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" '; + } // end if + + $this->output .= (string) 'xmlns="http://purl.org/rss/1.0/">' . "\n"; + + if (strlen($this->about) > 0) { + $this->output .= (string) '' . "\n"; + } else { + $this->output .= (string) '' . "\n"; + } // end if + + if (strlen($this->title) > 0) { + $this->output .= (string) '' . $this->title . '' . "\n"; + } // end if + + if (strlen($this->about) > 0) { + $this->output .= (string) '' . $this->about . '' . "\n"; + } // end if + + if (strlen($this->description) > 0) { + $this->output .= (string) '' . $this->description . '' . "\n"; + } // end if + + // additional dc data + if (strlen($this->publisher) > 0) { + $this->output .= (string) '' . $this->publisher . '' . "\n"; + } // end if + + if (strlen($this->creator) > 0) { + $this->output .= (string) '' . $this->creator . '' . "\n"; + } // end if + + if (strlen($this->date) > 0) { + $this->output .= (string) '' .$this->date . '' . "\n"; + } // end if + + if (strlen($this->language) > 0) { + $this->output .= (string) '' . $this->language . '' . "\n"; + } // end if + + if (strlen($this->rights) > 0) { + $this->output .= (string) '' . $this->rights . '' . "\n"; + } // end if + + if (strlen($this->coverage) > 0) { + $this->output .= (string) '' . $this->coverage . '' . "\n"; + } // end if + + if (strlen($this->contributor) > 0) { + $this->output .= (string) '' . $this->contributor . '' . "\n"; + } // end if + + // additional SY data + if (strlen($this->period) > 0) { + $this->output .= (string) '' . $this->period . '' . "\n"; + } // end if + + if (strlen($this->frequency) > 0) { + $this->output .= (string) '' . $this->frequency . '' . "\n"; + } // end if + + if (strlen($this->base) > 0) { + $this->output .= (string) '' . $this->base . '' . "\n"; + } // end if + + if (strlen($this->image_link) > 0) { + $this->output .= (string) '' . "\n"; + } // end if + + if (strlen($this->image_link) > 0) { + $this->output .= (string) '' . "\n"; + $this->output .= (string) '' . $this->title . '' . "\n"; + $this->output .= (string) '' . $this->image_link . '' . "\n"; + $this->output .= (string) '' . $this->about . '' . "\n"; + if (strlen($this->description) > 0) { + $this->output .= (string) '' . $this->description . '' . "\n"; + } // end if + $this->output .= (string) '' . "\n"; + } // end if + + if (count($this->getItemList()) > 0) { + $this->output .= (string) '' . "\n"; + foreach ($this->getItemList() as $id) { + $item =& $this->items[$id]; + if (strlen($item->getAbout()) > 0) { + $this->output .= (string) ' ' . "\n"; + } // end if + } // end foreach + $this->output .= (string) '' . "\n"; + } // end if + $this->output .= (string) '' . "\n"; + + if (count($this->getItemList()) > 0) { + foreach ($this->getItemList() as $id) { + $item =& $this->items[$id]; + + if (strlen($item->getTitle()) > 0 && strlen($item->getLink()) > 0) { + if (strlen($item->getAbout()) > 0) { + $this->output .= (string) '' . "\n"; + } else { + $this->output .= (string) '' . "\n"; + } // end if + + $this->output .= (string) '' . $item->getTitle() . '' . "\n"; + $this->output .= (string) '' . $item->getLink() . '' . "\n"; + + if (strlen($item->getDescription()) > 0) { + $this->output .= (string) '' . $item->getDescription() . '' . "\n"; + } // end if + + if ($this->use_dc_data === true && strlen($item->getSubject()) > 0) { + $this->output .= (string) '' . $item->getSubject() . '' . "\n"; + } // end if + + if ($this->use_dc_data === true && strlen($item->getDate()) > 0) { + $this->output .= (string) '' . $item->getDate() . '' . "\n"; + } // end if + + $this->output .= (string) '' . "\n"; + } // end if + } // end foreach + } // end if + + $this->output .= (string) ''; + } // end function + + //------------------------------------------------- + // creates the output based on the 2.0 rss draft + //------------------------------------------------- + // @desc creates the output based on the 0.91 rss draft + // @return (void) + // @access private + // @see $output + // @since 1.001 - 2003/05/30 + //------------------------------------------------- + function createOutputV200() { + // not implemented + $this->createOutputV100(); + //--------------------- + $this->output = (string) '' . "\n"; + $this->output .= (string) '' . "\n"; + + if (strlen($this->rights) > 0) { + $this->output .= (string) '' . $this->rights . '' . "\n"; + } // end if + + if (strlen($this->date) > 0) { + $this->output .= (string) '' .$this->date . '' . "\n"; + //xuanyan 2007.5.8 edit + //$this->output .= (string) '' .$this->date . '' . "\n"; + } // end if + + if (strlen($this->about) > 0) { + $this->output .= (string) '' . $this->about . '' . "\n"; + } // end if + + if (strlen($this->description) > 0) { + $this->output .= (string) '' . $this->description . '' . "\n"; + } // end if + + if (strlen($this->about) > 0) { + $this->output .= (string) '' . $this->about . '' . "\n"; + } // end if + + if (strlen($this->title) > 0) { + $this->output .= (string) '' . $this->title . '' . "\n"; + } // end if + + if (strlen($this->image_link) > 0) { + $this->output .= (string) '' . "\n"; + $this->output .= (string) '' . $this->title . '' . "\n"; + $this->output .= (string) '' . $this->image_link . '' . "\n"; + $this->output .= (string) '' . $this->about . '' . "\n"; + if (strlen($this->description) > 0) { + $this->output .= (string) '' . $this->description . '' . "\n"; + } // end if + $this->output .= (string) '' . "\n"; + } // end if + + if (strlen($this->publisher) > 0) { + $this->output .= (string) '' . $this->publisher . '' . "\n"; + } // end if + + if (strlen($this->creator) > 0) { + //xuanyan 2007.5.8 edit + //$this->output .= (string) '' . $this->creator . '' . "\n"; + $this->output .= (string) '' . $this->creator . '' . "\n"; + } // end if + + if (strlen($this->language) > 0) { + $this->output .= (string) '' . $this->language . '' . "\n"; + } // end if + + if (strlen($this->category) > 0) { + $this->output .= (string) '' . $this->category . '' . "\n"; + } // end if + + if (strlen($this->cache) > 0) { + $this->output .= (string) '' . $this->cache . '' . "\n"; + } // end if + + if (count($this->getItemList()) > 0) { + foreach ($this->getItemList() as $id) { + $item =& $this->items[$id]; + + if (strlen($item->getTitle()) > 0 && strlen($item->getLink()) > 0) { + $this->output .= (string) '' . "\n"; + $this->output .= (string) '' . $item->getTitle() . '' . "\n"; + $this->output .= (string) '' . $item->getLink() . '' . "\n"; + + if (strlen($item->getDescription()) > 0) { + $this->output .= (string) '' . $item->getDescription() . '' . "\n"; + } // end if + + if ($this->use_dc_data === true && strlen($item->getSubject()) > 0) { + $this->output .= (string) '' . $item->getSubject() . '' . "\n"; + } // end if + + if ($this->use_dc_data === true && strlen($item->getDate()) > 0) { + $this->output .= (string) '' . $item->getDate() . '' . "\n"; + } // end if + + if (strlen($item->getAbout()) > 0) { + $this->output .= (string) '' . $item->getAbout() . '' . "\n"; + } // end if + + if (strlen($item->getAuthor()) > 0) { + $this->output .= (string) '' . $item->getAuthor() . '' . "\n"; + } // end if + + if (strlen($item->getComments()) > 0) { + $this->output .= (string) '' . $item->getComments() . '' . "\n"; + } // end if + + $this->output .= (string) '' . "\n"; + } // end if + } // end foreach + } // end if + + $this->output .= (string) '' . "\n"; + $this->output .= (string) '' . "\n"; + } // end function + + //------------------------------------------------- + // creates the output + //------------------------------------------------- + // @desc creates the output + // @return (void) + // @access private + // @uses createOutputV100() + //------------------------------------------------- + function createOutput($version = '') { + if (strlen(trim($version)) === 0) { + $version = (string) '1.0'; + } // end if + + switch ($version) { + case '0.9': + $this->createOutputV090(); + break; + case '0.91': + $this->createOutputV091(); + break; + case '2.00': + $this->createOutputV200(); + break; + case '1.0': + default: + $this->createOutputV100(); + break; + } // end switch + } // end function + + //------------------------------------------------- + // echos the output + //------------------------------------------------- + // use this function if you want to directly output the rss stream + //------------------------------------------------- + // @desc echos the output + // @return (void) + // @access public + // @uses createOutput() + //------------------------------------------------- + function outputRSS($version = '') { + if (!isset($this->output)) { + $this->createOutput($version); + } // end if +// header('Content-Disposition: inline; filename=rss_' . str_replace(' ', '', $this->title) . '.xml'); + $this->output = '<' . '?xml version="1.0" encoding="' . $this->encoding . '"?' .'>' . "\n" . + '' . "\n" . $this->output; + echo $this->output; + } // end function + + //------------------------------------------------- + // returns the output + //------------------------------------------------- + // use this function if you want to have the output stream as a string (for example to write it in a cache file) + //------------------------------------------------- + // @desc returns the output + // @return (void) + // @access public + // @uses createOutput() + //------------------------------------------------- + function getRSSOutput($version = '') { + if (!isset($this->output)) { + $this->createOutput($version); + } // end if + + return (string) '<' . '?xml version="1.0" encoding="' . $this->encoding . '"?' . '>' . "\n" . + ' ' . "\n" . $this->output; + } // end function +} // end class RSSBuilder + +//--------------------------------------------------------------------------- + +/*-----------------------------------------------------------------------*/ +// single rss item object +//------------------------------------------------- +// Tested with WAMP (XP-SP1/1.3.24/4.0.12/4.3.0) +// Last change: 2003-05-30 +//------------------------------------------------- +// @desc single rss item object +// @access private +// @author Michael Wimmer +// @copyright Michael Wimmer +// @link http://www.flaimo.com/ +// @package RSSBuilder +// @category FLP +// @version 1.001 +/*-----------------------------------------------------------------------*/ +class RSSItem extends RSSBase +{ + /*-----------------------------------------------------------------------*/ + /* V A R I A B L E S */ + /*-----------------------------------------------------------------------*/ + + //------------------------------------------------- + // URL + //------------------------------------------------- + // @desc URL + // @var string + // @access private + //------------------------------------------------- + var $about; + + //------------------------------------------------- + // headline + //------------------------------------------------- + // @desc headline + // @var string + // @access private + //------------------------------------------------- + var $title; + + //------------------------------------------------- + // URL to the full item + //------------------------------------------------- + // @desc URL to the full item + // @var string + // @access private + //------------------------------------------------- + var $link; + + //------------------------------------------------- + // optional description + //------------------------------------------------- + // @desc optional description + // @var string + // @access private + //------------------------------------------------- + var $description; + + //------------------------------------------------- + // optional subject (category) + //------------------------------------------------- + // @desc optional subject (category) + // @var string + // @access private + //------------------------------------------------- + var $subject; + + //------------------------------------------------- + // optional date + //------------------------------------------------- + // @desc optional date + // @var string + // @access private + //------------------------------------------------- + var $date; + + //------------------------------------------------- + // author of item + //------------------------------------------------- + // @desc author of item + // @var string + // @access private + // @since 1.001 - 2003/05/30 + //------------------------------------------------- + var $author; + + //------------------------------------------------- + // url to comments page (rss 2.0) + //------------------------------------------------- + // @desc url to comments page (rss 2.0) + // @var string + // @access private + // @since 1.001 - 2003/05/30 + //------------------------------------------------- + var $comments; + + /*-----------------------*/ + /* C O N S T R U C T O R */ + /*-----------------------*/ + + //------------------------------------------------- + // Constructor + //------------------------------------------------- + // @desc Constructor + // @param (string) $about URL + // @param (string) $title + // @param (string) $link URL + // @param (string) $description (optional) + // @param (string) $subject some sort of category (optional) + // @param (string) $date format: 2003-05-29T00:03:07+0200 (optional) + // @return (void) + // @uses setAbout(), setTitle(), setLink(), setDescription(), setSubject(), setDate(), setAuthor(), setComments() + // @access private + //------------------------------------------------- + function RSSItem($about = '', + $title = '', + $link = '', + $description = '', + $subject = '', + $date = '', + $author = '', + $comments = '') { + $this->setAbout($about); + $this->setTitle($title); + $this->setLink($link); + $this->setDescription($description); + $this->setSubject($subject); + $this->setDate($date); + $this->setAuthor($author); + $this->setComments($comments); + } // end constructor + + //------------------------------------------------- + // Sets $about variable + //------------------------------------------------- + // @desc Sets $about variable + // @param (string) $about + // @return (void) + // @access private + // @see $about + //------------------------------------------------- + function setAbout($about = '') { + if (!isset($this->about) && strlen(trim($about)) > 0) { + $this->about = (string) trim($about); + } // end if + } // end function + + //------------------------------------------------- + // Sets $title variable + //------------------------------------------------- + // @desc Sets $title variable + // @param (string) $title + // @return (void) + // @access private + // @see $title + //------------------------------------------------- + function setTitle($title = '') { + if (!isset($this->title) && strlen(trim($title)) > 0) { + $this->title = (string) trim($title); + } // end if + } // end function + + //------------------------------------------------- + // Sets $link variable + //------------------------------------------------- + // @desc Sets $link variable + // @param (string) $link + // @return (void) + // @access private + // @see $link + //------------------------------------------------- + function setLink($link = '') { + if (!isset($this->link) && strlen(trim($link)) > 0) { + $this->link = (string) trim($link); + } // end if + } // end function + + //------------------------------------------------- + // Sets $description variable + //------------------------------------------------- + // @desc Sets $description variable + // @param (string) $description + // @return (void) + // @access private + // @see $description + //------------------------------------------------- + function setDescription($description = '') { + if (!isset($this->description) && strlen(trim($description)) > 0) { + $this->description = (string) trim($description); + } // end if + } // end function + + //------------------------------------------------- + // Sets $subject variable + //------------------------------------------------- + // @desc Sets $subject variable + // @param (string) $subject + // @return (void) + // @access private + // @see $subject + //------------------------------------------------- + function setSubject($subject = '') { + if (!isset($this->subject) && strlen(trim($subject)) > 0) { + $this->subject = (string) trim($subject); + } // end if + } // end function + + //------------------------------------------------- + // Sets $date variable + //------------------------------------------------- + // @desc Sets $date variable + // @param (string) $date + // @return (void) + // @access private + // @see $date + //------------------------------------------------- + function setDate($date = '') { + if (!isset($this->date) && strlen(trim($date)) > 0) { + $this->date = (string) trim($date); + } // end if + } // end function + + //------------------------------------------------- + // Sets $author variable + //------------------------------------------------- + // @desc Sets $author variable + // @param (string) $author + // @return (void) + // @access private + // @see $author + // @since 1.001 - 2003/05/30 + //------------------------------------------------- + function setAuthor($author = '') { + if (!isset($this->author) && strlen(trim($author)) > 0) { + $this->author = (string) trim($author); + } // end if + } // end function + + //------------------------------------------------- + // Sets $comments variable + //------------------------------------------------- + // @desc Sets $comments variable + // @param (string) $comments + // @return (void) + // @access private + // @see $comments + // @since 1.001 - 2003/05/30 + //------------------------------------------------- + function setComments($comments = '') { + if (!isset($this->comments) && strlen(trim($comments)) > 0) { + $this->comments = (string) trim($comments); + } // end if + } // end function + + //------------------------------------------------- + // Returns $about variable + //------------------------------------------------- + // @desc Returns $about variable + // @return (string) $about + // @access public + // @see $about + //------------------------------------------------- + function getAbout() { + return (string) $this->about; + } // end function + + //------------------------------------------------- + // Returns $title variable + //------------------------------------------------- + // @desc Returns $title variable + // @return (string) $title + // @access public + // @see $title + //------------------------------------------------- + function getTitle() { + return (string) $this->title; + } // end function + + //------------------------------------------------- + // Returns $link variable + //------------------------------------------------- + // @desc Returns $link variable + // @return (string) $link + // @access public + // @see $link + //------------------------------------------------- + function getLink() { + return (string) $this->link; + } // end function + + //------------------------------------------------- + // Returns $description variable + //------------------------------------------------- + // @desc Returns $description variable + // @return (string) $description + // @access public + // @see $description + //------------------------------------------------- + function getDescription() { + return (string) $this->description; + } // end function + + //------------------------------------------------- + // Returns $subject variable + //------------------------------------------------- + // @desc Returns $subject variable + // @return (string) $subject + // @access public + // @see $subject + //------------------------------------------------- + function getSubject() { + return (string) $this->subject; + } // end function + + //------------------------------------------------- + // Returns $date variable + //------------------------------------------------- + // @desc Returns $date variable + // @return (string) $date + // @access public + // @see $date + //------------------------------------------------- + function getDate() { + return (string) $this->date; + } // end function + + //------------------------------------------------- + // Returns $author variable + //------------------------------------------------- + // @desc Returns $author variable + // @return (string) $author + // @access public + // @see $author + // @since 1.001 - 2003/05/30 + //------------------------------------------------- + function getAuthor() { + return (string) $this->author; + } // end function + + //------------------------------------------------- + // Returns $comments variable + //------------------------------------------------- + // @desc Returns $comments variable + // @return (string) $comments + // @access public + // @see $comments + // @since 1.001 - 2003/05/30 + //------------------------------------------------- + function getComments() { + return (string) $this->comments; + } // end function +} // end class RSSItem + +?> \ No newline at end of file diff --git a/includes/cls_session.php b/includes/cls_session.php new file mode 100644 index 0000000..ebea9e7 --- /dev/null +++ b/includes/cls_session.php @@ -0,0 +1,290 @@ +cls_session($db, $session_table, $session_data_table, $session_name, $session_id); + } + + function cls_session(&$db, $session_table, $session_data_table, $session_name = 'ECS_ID', $session_id = '') + { + $GLOBALS['_SESSION'] = array(); + + if (!empty($GLOBALS['cookie_path'])) + { + $this->session_cookie_path = $GLOBALS['cookie_path']; + } + else + { + $this->session_cookie_path = '/'; + } + + if (!empty($GLOBALS['cookie_domain'])) + { + $this->session_cookie_domain = $GLOBALS['cookie_domain']; + } + else + { + $this->session_cookie_domain = ''; + } + + if (!empty($GLOBALS['cookie_secure'])) + { + $this->session_cookie_secure = $GLOBALS['cookie_secure']; + } + else + { + $this->session_cookie_secure = false; + } + + $this->session_name = $session_name; + $this->session_table = $session_table; + $this->session_data_table = $session_data_table; + + $this->db = &$db; + $this->_ip = real_ip(); + + if ($session_id == '' && !empty($_COOKIE[$this->session_name])) + { + $this->session_id = $_COOKIE[$this->session_name]; + } + else + { + $this->session_id = $session_id; + } + + if ($this->session_id) + { + $tmp_session_id = substr($this->session_id, 0, 32); + if ($this->gen_session_key($tmp_session_id) == substr($this->session_id, 32)) + { + $this->session_id = $tmp_session_id; + } + else + { + $this->session_id = ''; + } + } + + $this->_time = time(); + + if ($this->session_id) + { + $this->load_session(); + } + else + { + $this->gen_session_id(); + + setcookie($this->session_name, $this->session_id . $this->gen_session_key($this->session_id), 0, $this->session_cookie_path, $this->session_cookie_domain, $this->session_cookie_secure); + } + + register_shutdown_function(array(&$this, 'close_session')); + } + + function gen_session_id() + { + $this->session_id = md5(uniqid(mt_rand(), true)); + + return $this->insert_session(); + } + + function gen_session_key($session_id) + { + static $ip = ''; + + if ($ip == '') + { + $ip = substr($this->_ip, 0, strrpos($this->_ip, '.')); + } + + return sprintf('%08x', crc32(ROOT_PATH . $ip . $session_id)); + } + + function insert_session() + { + return $this->db->query('INSERT INTO ' . $this->session_table . " (sesskey, expiry, ip, data) VALUES ('" . $this->session_id . "', '". $this->_time ."', '". $this->_ip ."', 'a:0:{}')"); + } + + function load_session() + { + $session = $this->db->getRow('SELECT userid, adminid, user_name, user_rank, discount, email, data, expiry FROM ' . $this->session_table . " WHERE sesskey = '" . $this->session_id . "'"); + if (empty($session)) + { + $this->insert_session(); + + $this->session_expiry = 0; + $this->session_md5 = '40cd750bba9870f18aada2478b24840a'; + $GLOBALS['_SESSION'] = array(); + } + else + { + if (!empty($session['data']) && $this->_time - $session['expiry'] <= $this->max_life_time) + { + $this->session_expiry = $session['expiry']; + $this->session_md5 = md5($session['data']); + $GLOBALS['_SESSION'] = unserialize($session['data']); + $GLOBALS['_SESSION']['user_id'] = $session['userid']; + $GLOBALS['_SESSION']['admin_id'] = $session['adminid']; + $GLOBALS['_SESSION']['user_name'] = $session['user_name']; + $GLOBALS['_SESSION']['user_rank'] = $session['user_rank']; + $GLOBALS['_SESSION']['discount'] = $session['discount']; + $GLOBALS['_SESSION']['email'] = $session['email']; + } + else + { + $session_data = $this->db->getRow('SELECT data, expiry FROM ' . $this->session_data_table . " WHERE sesskey = '" . $this->session_id . "'"); + if (!empty($session_data['data']) && $this->_time - $session_data['expiry'] <= $this->max_life_time) + { + $this->session_expiry = $session_data['expiry']; + $this->session_md5 = md5($session_data['data']); + $GLOBALS['_SESSION'] = unserialize($session_data['data']); + $GLOBALS['_SESSION']['user_id'] = $session['userid']; + $GLOBALS['_SESSION']['admin_id'] = $session['adminid']; + $GLOBALS['_SESSION']['user_name'] = $session['user_name']; + $GLOBALS['_SESSION']['user_rank'] = $session['user_rank']; + $GLOBALS['_SESSION']['discount'] = $session['discount']; + $GLOBALS['_SESSION']['email'] = $session['email']; + } + else + { + $this->session_expiry = 0; + $this->session_md5 = '40cd750bba9870f18aada2478b24840a'; + $GLOBALS['_SESSION'] = array(); + } + } + } + } + + function update_session() + { + $adminid = !empty($GLOBALS['_SESSION']['admin_id']) ? intval($GLOBALS['_SESSION']['admin_id']) : 0; + $userid = !empty($GLOBALS['_SESSION']['user_id']) ? intval($GLOBALS['_SESSION']['user_id']) : 0; + $user_name = !empty($GLOBALS['_SESSION']['user_name']) ? trim($GLOBALS['_SESSION']['user_name']) : 0; + $user_rank = !empty($GLOBALS['_SESSION']['user_rank']) ? intval($GLOBALS['_SESSION']['user_rank']) : 0; + $discount = !empty($GLOBALS['_SESSION']['discount']) ? round($GLOBALS['_SESSION']['discount'], 2) : 0; + $email = !empty($GLOBALS['_SESSION']['email']) ? trim($GLOBALS['_SESSION']['email']) : 0; + unset($GLOBALS['_SESSION']['admin_id']); + unset($GLOBALS['_SESSION']['user_id']); + unset($GLOBALS['_SESSION']['user_name']); + unset($GLOBALS['_SESSION']['user_rank']); + unset($GLOBALS['_SESSION']['discount']); + unset($GLOBALS['_SESSION']['email']); + + $data = serialize($GLOBALS['_SESSION']); + $this->_time = time(); + + if ($this->session_md5 == md5($data) && $this->_time < $this->session_expiry + 10) + { + return true; + } + + $data = addslashes($data); + + if (isset($data{255})) + { + $this->db->autoReplace($this->session_data_table, array('sesskey' => $this->session_id, 'expiry' => $this->_time, 'data' => $data), array('expiry' => $this->_time,'data' => $data)); + + $data = ''; + } + + return $this->db->query('UPDATE ' . $this->session_table . " SET expiry = '" . $this->_time . "', ip = '" . $this->_ip . "', userid = '" . $userid . "', adminid = '" . $adminid . "', user_name='" . $user_name . "', user_rank='" . $user_rank . "', discount='" . $discount . "', email='" . $email . "', data = '$data' WHERE sesskey = '" . $this->session_id . "' LIMIT 1"); + } + + function close_session() + { + $this->update_session(); + + /* 闅忔満瀵 sessions_data 鐨勫簱杩涜?鍒犻櫎鎿嶄綔 */ + if (mt_rand(0, 2) == 2) + { + $this->db->query('DELETE FROM ' . $this->session_data_table . ' WHERE expiry < ' . ($this->_time - $this->max_life_time)); + } + + if ((time() % 2) == 0) + { + return $this->db->query('DELETE FROM ' . $this->session_table . ' WHERE expiry < ' . ($this->_time - $this->max_life_time)); + } + + return true; + } + + function delete_spec_admin_session($adminid) + { + if (!empty($GLOBALS['_SESSION']['admin_id']) && $adminid) + { + return $this->db->query('DELETE FROM ' . $this->session_table . " WHERE adminid = '$adminid'"); + } + else + { + return false; + } + } + + function destroy_session() + { + $GLOBALS['_SESSION'] = array(); + + setcookie($this->session_name, $this->session_id, 1, $this->session_cookie_path, $this->session_cookie_domain, $this->session_cookie_secure); + + /* ECSHOP 鑷?畾涔夋墽琛岄儴鍒 */ + if (!empty($GLOBALS['ecs'])) + { + $this->db->query('DELETE FROM ' . $GLOBALS['ecs']->table('cart') . " WHERE session_id = '$this->session_id'"); + } + /* ECSHOP 鑷?畾涔夋墽琛岄儴鍒 */ + + $this->db->query('DELETE FROM ' . $this->session_data_table . " WHERE sesskey = '" . $this->session_id . "' LIMIT 1"); + + return $this->db->query('DELETE FROM ' . $this->session_table . " WHERE sesskey = '" . $this->session_id . "' LIMIT 1"); + } + + function get_session_id() + { + return $this->session_id; + } + + function get_users_count() + { + return $this->db->getOne('SELECT count(*) FROM ' . $this->session_table); + } +} + +?> \ No newline at end of file diff --git a/includes/cls_sms.php b/includes/cls_sms.php new file mode 100644 index 0000000..5f35365 --- /dev/null +++ b/includes/cls_sms.php @@ -0,0 +1,397 @@ + 'http://api.sms.shopex.cn', + 'send' => 'http://api.sms.shopex.cn', + 'servertime' => 'http://webapi.sms.shopex.cn' + + ); + /** + * 存放MYSQL对象 + * + * @access private + * @var object $db + */ + var $db = null; + + /** + * 存放ECS对象 + * + * @access private + * @var object $ecs + */ + var $ecs = null; + + /** + * 存放transport对象 + * + * @access private + * @var object $t + */ + var $t = null; + + /** + * 存放程序执行过程中的错误信息,这样做的一个好处是:程序可以支持多语言。 + * 程序在执行相关的操作时,error_no值将被改变,可能被赋为空或大等0的数字. + * 为空或0表示动作成功;大于0的数字表示动作失败,该数字代表错误号。 + * + * @access public + * @var array $errors + */ + var $errors = array('api_errors' => array('error_no' => -1, 'error_msg' => ''), + 'server_errors' => array('error_no' => -1, 'error_msg' => '')); + + /** + * 构造函数 + * + * @access public + * @return void + */ + function __construct() + { + $this->sms(); + } + + /** + * 构造函数 + * + * @access public + * @return void + */ + function sms() + { + /* 由于要包含init.php,所以这两个对象一定是存在的,因此直接赋值 */ + $this->db = $GLOBALS['db']; + $this->ecs = $GLOBALS['ecs']; + + /* 此处最好不要从$GLOBALS数组里引用,防止出错 */ + $this->t = new transport(-1, -1, -1, false); + $this->json = new Services_JSON; + } + + /* 发送短消息 + * + * @access public + * @param string $phone 要发送到哪些个手机号码,传的值是一个数组 + * @param string $msg 发送的消息内容 + */ + function send($phones,$msg,$send_date = '', $send_num = 1,$sms_type='',$version='1.0') + { + + /* 检查发送信息的合法性 */ + $contents=$this->get_contents($phones, $msg); + if(!$contents) + { + $this->errors['server_errors']['error_no'] = 3;//发送的信息有误 + return false; + } + + $login_info = $this->getSmsInfo(); + if (!$login_info) + { + $this->errors['server_errors']['error_no'] = 5;//无效的身份信息 + + return false; + } + else + { + if($login_info['info']['account_info']['active']!='1') + { + $this->errors['server_errors']['error_no'] = 11;//短信功能没有激活 + return false; + } + + } + /* 获取API URL */ + $sms_url = $this->get_url('send'); + + if (!$sms_url) + { + $this->errors['server_errors']['error_no'] = 6;//URL不对 + + return false; + } + + $send_str['contents']= $this->json->encode($contents); + $send_str['certi_app']='sms.send'; + $send_str['entId']=$GLOBALS['_CFG']['ent_id']; + $send_str['entPwd']=$GLOBALS['_CFG']['ent_ac']; + $send_str['license']=$GLOBALS['_CFG']['certificate_id']; + $send_str['source']=SOURCE_ID; + $send_str['sendType'] = 'notice'; + $send_str['use_backlist'] = '1'; + $send_str['version'] = $version; + $send_str['format']='json'; + $send_str['timestamp'] = $this->getTime(); + $send_str['certi_ac']=$this->make_shopex_ac($send_str,SOURCE_TOKEN); + $sms_url= $this->get_url('send'); + /* 发送HTTP请求 */ + $response = $this->t->request($sms_url, $send_str,'POST'); + $result = $this->json->decode($response['body'], true); + + if($result['res'] == 'succ') + { + return true; + } + elseif($result['res'] == 'fail') + { + return false; + } + + } + + + + + /** + * 检测启用短信服务需要的信息 + * + * @access private + * @param string $email 邮箱 + * @param string $password 密码 + * @return boolean 如果启用信息格式合法就返回true,否则返回false。 + */ + function check_enable_info($email, $password) + { + if (empty($email) || empty($password)) + { + return false; + } + + return true; + } + + //查询是否已有通行证 + function has_registered() + { + $sql = 'SELECT `value` + FROM ' . $this->ecs->table('shop_config') . " + WHERE `code` = 'ent_id'"; + + $result = $this->db->getOne($sql); + + if (empty($result)) + { + return false; + } + + return true; + } + function get_site_info() + { + /* 获得当前处于会话状态的管理员的邮箱 */ + $email = $this->get_admin_email(); + $email = $email ? $email : ''; + /* 获得当前网店的域名 */ + $domain = $this->ecs->get_domain(); + $domain = $domain ? $domain : ''; + /* 赋给smarty模板 */ + $sms_site_info['email'] = $email; + $sms_site_info['domain'] = $domain; + + return $sms_site_info; + } + function get_site_url() + { + $url = $this->ecs->url(); + $url = $url ? $url : ''; + return $url; + } + /** + * 获得当前处于会话状态的管理员的邮箱 + * + * @access private + * @return string or boolean 成功返回管理员的邮箱,否则返回false。 + */ + function get_admin_email() + { + $sql = 'SELECT `email` FROM ' . $this->ecs->table('admin_user') . " WHERE `user_id` = '" . $_SESSION['admin_id'] . "'"; + $email = $this->db->getOne($sql); + + if (empty($email)) + { + return false; + } + + return $email; + } + //用户短信账户信息获取 + function getSmsInfo($certi_app='sms.info',$version='1.0', $format='json'){ + $send_str['certi_app'] = $certi_app; + $send_str['entId'] = $GLOBALS['_CFG']['ent_id']; + $send_str['entPwd'] = $GLOBALS['_CFG']['ent_ac']; + $send_str['source'] = SOURCE_ID; + $send_str['version'] = $version; + $send_str['format'] = $format; + $send_str['timestamp'] = $this->getTime(); + $send_str['certi_ac'] = $this->make_shopex_ac($send_str,SOURCE_TOKEN); + $sms_url = $this->get_url('info'); + $response = $this->t->request($sms_url, $send_str,'POST'); + $result = $this->json->decode($response['body'],true); + if($result['res'] == 'succ') + { + return $result; + } + elseif($result['res'] == 'fail') + { + return false; + } + } + + //检查手机号和发送的内容并生成生成短信队列 + function get_contents($phones,$msg) + { + if (empty($phones) || empty($msg)) + { + return false; + } + $phone_key=0; + + $phones=explode(',',$phones); + foreach($phones as $key => $value) + { + if($i<200) + { + $i++; + } + else + { + $i=0; + $phone_key++; + } + if($this->is_moblie($value)) + { + $phone[$phone_key][]=$value; + } + else + { + $i--; + } + } + if(!empty($phone)) + { + foreach($phone as $phone_key => $val) + { + if (EC_CHARSET != 'utf-8') + { + $phone_array[$phone_key]['phones']=implode(',',$val); + $phone_array[$phone_key]['content']=iconv('gb2312','utf-8',$msg); + } + else + { + $phone_array[$phone_key]['phones']=implode(',',$val); + $phone_array[$phone_key]['content']=$msg; + } + + } + return $phone_array; + } + else + { + return false; + } + + } + + //获得服务器时间 + function getTime(){ + $Tsend_str['certi_app'] = 'sms.servertime'; + $Tsend_str['version'] = '1.0' ; + $Tsend_str['format'] = 'json' ; + $Tsend_str['certi_ac'] = $this->make_shopex_ac($Tsend_str,'SMS_TIME'); + $sms_url = $this->get_url('servertime'); + $response = $this->t->request($sms_url, $Tsend_str,'POST'); + + $result = $this->json->decode($response['body'], true); + return $result['info']; + + } + /** + * 返回指定键名的URL + * + * @access public + * @param string $key URL的名字,即数组的键名 + * @return string or boolean 如果由形参指定的键名对应的URL值存在就返回该URL,否则返回false。 + */ + function get_url($key) + { + $url = $this->api_urls[$key]; + + if (empty($url)) + { + return false; + } + + return $url; + } + /** + * 检测手机号码是否正确 + * + */ + function is_moblie($moblie) + { + return preg_match("/^0?1((3|8)[0-9]|5[0-35-9]|4[57])\d{8}$/", $moblie); + } + + //加密算法 + function make_shopex_ac($temp_arr,$token) + { + ksort($temp_arr); + $str = ''; + foreach($temp_arr as $key=>$value) + { + if($key!=' certi_ac') + { + $str.= $value; + } + } + return strtolower(md5($str.strtolower(md5($token)))); + } + function base_encode($str) + { + $str = base64_encode($str); + return strtr($str, $this->pattern()); + } + function pattern() + { + return array( + '+'=>'_1_', + '/'=>'_2_', + '='=>'_3_', + ); + } + +} + +?> \ No newline at end of file diff --git a/includes/cls_smtp.php b/includes/cls_smtp.php new file mode 100644 index 0000000..aa3b879 --- /dev/null +++ b/includes/cls_smtp.php @@ -0,0 +1,346 @@ +timeout = 10; + $this->status = SMTP_STATUS_NOT_CONNECTED; + $this->host = 'localhost'; + $this->port = 25; + $this->auth = false; + $this->user = ''; + $this->pass = ''; + $this->errors = array(); + + foreach ($params AS $key => $value) + { + $this->$key = $value; + } + + $this->helo = $this->host; + + // 如果没有设置用户名则不验证 + $this->auth = ('' == $this->user) ? false : true; + } + + function connect($params = array()) + { + if (!isset($this->status)) + { + $obj = new smtp($params); + + if ($obj->connect()) + { + $obj->status = SMTP_STATUS_CONNECTED; + } + + return $obj; + } + else + { + if (!empty($GLOBALS['_CFG']['smtp_ssl'])) + { + $this->host = "ssl://" . $this->host; + } + $this->connection = @fsockopen($this->host, $this->port, $errno, $errstr, $this->timeout); + + if ($this->connection === false) + { + $this->errors[] = 'Access is denied.'; + + return false; + } + + @socket_set_timeout($this->connection, 0, 250000); + + $greeting = $this->get_data(); + + if (is_resource($this->connection)) + { + $this->status = 2; + + return $this->auth ? $this->ehlo() : $this->helo(); + } + else + { + log_write($errstr, __FILE__, __LINE__); + $this->errors[] = 'Failed to connect to server: ' . $errstr; + + return false; + } + } + } + + /** + * 参数为数组 + * recipients 接收人的数组 + * from 发件人的地址,也将作为回复地址 + * headers 头部信息的数组 + * body 邮件的主体 + */ + + function send($params = array()) + { + foreach ($params AS $key => $value) + { + $this->$key = $value; + } + + if ($this->is_connected()) + { + // 服务器是否需要验证 + if ($this->auth) + { + if (!$this->auth()) + { + return false; + } + } + + $this->mail($this->from); + + if (is_array($this->recipients)) + { + foreach ($this->recipients AS $value) + { + $this->rcpt($value); + } + } + else + { + $this->rcpt($this->recipients); + } + + if (!$this->data()) + { + return false; + } + + $headers = str_replace(CRLF . '.', CRLF . '..', trim(implode(CRLF, $this->headers))); + $body = str_replace(CRLF . '.', CRLF . '..', $this->body); + $body = substr($body, 0, 1) == '.' ? '.' . $body : $body; + + $this->send_data($headers); + $this->send_data(''); + $this->send_data($body); + $this->send_data('.'); + + return (substr($this->get_data(), 0, 3) === '250'); + } + else + { + $this->errors[] = 'Not connected!'; + + return false; + } + } + + function helo() + { + if (is_resource($this->connection) + AND $this->send_data('HELO ' . $this->helo) + AND substr($error = $this->get_data(), 0, 3) === '250' ) + { + return true; + } + else + { + $this->errors[] = 'HELO command failed, output: ' . trim(substr($error, 3)); + + return false; + } + } + + function ehlo() + { + if (is_resource($this->connection) + AND $this->send_data('EHLO ' . $this->helo) + AND substr($error = $this->get_data(), 0, 3) === '250' ) + { + return true; + } + else + { + $this->errors[] = 'EHLO command failed, output: ' . trim(substr($error, 3)); + + return false; + } + } + + function auth() + { + if (is_resource($this->connection) + AND $this->send_data('AUTH LOGIN') + AND substr($error = $this->get_data(), 0, 3) === '334' + AND $this->send_data(base64_encode($this->user)) // Send username + AND substr($error = $this->get_data(),0,3) === '334' + AND $this->send_data(base64_encode($this->pass)) // Send password + AND substr($error = $this->get_data(),0,3) === '235' ) + { + return true; + } + else + { + $this->errors[] = 'AUTH command failed: ' . trim(substr($error, 3)); + + return false; + } + } + + function mail($from) + { + if ($this->is_connected() + AND $this->send_data('MAIL FROM:<' . $from . '>') + AND substr($this->get_data(), 0, 2) === '250' ) + { + return true; + } + else + { + return false; + } + } + + function rcpt($to) + { + if ($this->is_connected() + AND $this->send_data('RCPT TO:<' . $to . '>') + AND substr($error = $this->get_data(), 0, 2) === '25') + { + return true; + } + else + { + $this->errors[] = trim(substr($error, 3)); + + return false; + } + } + + function data() + { + if ($this->is_connected() + AND $this->send_data('DATA') + AND substr($error = $this->get_data(), 0, 3) === '354' ) + { + return true; + } + else + { + $this->errors[] = trim(substr($error, 3)); + + return false; + } + } + + function is_connected() + { + return (is_resource($this->connection) AND ($this->status === SMTP_STATUS_CONNECTED)); + } + + function send_data($data) + { + if (is_resource($this->connection)) + { + return fwrite($this->connection, $data . CRLF, strlen($data) + 2); + } + else + { + return false; + } + } + + function get_data() + { + $return = ''; + $line = ''; + + if (is_resource($this->connection)) + { + while (strpos($return, CRLF) === false OR $line{3} !== ' ') + { + $line = fgets($this->connection, 512); + $return .= $line; + } + + return trim($return); + } + else + { + return ''; + } + } + + /** + * 获得最后一个错误信息 + * + * @access public + * @return string + */ + function error_msg() + { + if (!empty($this->errors)) + { + $len = count($this->errors) - 1; + return $this->errors[$len]; + } + else + { + return ''; + } + } +} + +?> \ No newline at end of file diff --git a/includes/cls_sql_executor.php b/includes/cls_sql_executor.php new file mode 100644 index 0000000..4f88c74 --- /dev/null +++ b/includes/cls_sql_executor.php @@ -0,0 +1,912 @@ +sql_executor($db, $charset, $sprefix, $tprefix, $log_path, $auto_match, $ignored_errors); + } + + /** + * 构造函数 + * + * @access public + * @param mysql $db mysql类对象 + * @param string $charset 字符集 + * @param string $sprefix 替换前表前缀 + * @param string $tprefix 替换后表前缀 + * @param string $log_path 日志路径 + * @param boolean $auto_match 是否进行智能化查询 + * @param array $ignored_errors 忽略的错误号数组 + * @return void + */ + function sql_executor($db, $charset = 'gbk', $sprefix = 'ecs_', $tprefix = 'ecs_', $log_path = '', $auto_match = false, $ignored_errors = array()) + { + $this->db = $db; + $this->db_charset = $charset; + $this->source_prefix = $sprefix; + $this->target_prefix = $tprefix; + $this->log_path = $log_path; + $this->auto_match = $auto_match; + $this->ignored_errors = $ignored_errors; + } + + /** + * 执行所有SQL文件中所有的SQL语句 + * + * @access public + * @param array $sql_files 文件绝对路径组成的一维数组 + * @return boolean 执行成功返回true,失败返回false。 + */ + function run_all($sql_files) + { + /* 如果传入参数不是数组,程序直接返回 */ + if (!is_array($sql_files)) + { + return false; + } + + foreach ($sql_files AS $sql_file) + { + $query_items = $this->parse_sql_file($sql_file); + + /* 如果解析失败,则跳过 */ + if (!$query_items) + { + continue; + } + + foreach ($query_items AS $query_item) + { + /* 如果查询项为空,则跳过 */ + if (!$query_item) + { + continue; + } + + if (!$this->query($query_item)) + { + return false; + } + } + } + + return true; + } + + /** + * 获得分散的查询项 + * + * @access public + * @param string $file_path 文件的绝对路径 + * @return mixed 解析成功返回分散的查询项数组,失败返回false。 + */ + function parse_sql_file($file_path) + { + /* 如果SQL文件不存在则返回false */ + if (!file_exists($file_path)) + { + return false; + } + + /* 记录当前正在运行的SQL文件 */ + $this->current_file = $file_path; + + /* 读取SQL文件 */ + $sql = implode('', file($file_path)); + + /* 删除SQL注释,由于执行的是replace操作,所以不需要进行检测。下同。 */ + $sql = $this->remove_comment($sql); + + /* 删除SQL串首尾的空白符 */ + $sql = trim($sql); + + /* 如果SQL文件中没有查询语句则返回false */ + if (!$sql) + { + return false; + } + + /* 替换表前缀 */ + $sql = $this->replace_prefix($sql); + + /* 解析查询项 */ + $sql = str_replace("\r", '', $sql); + $query_items = explode(";\n", $sql); + + return $query_items; + } + + /** + * 执行某一个查询项 + * + * @access public + * @param string $query_item 查询项 + * @return boolean 成功返回true,失败返回false。 + */ + function query($query_item) + { + /* 删除查询项首尾的空白符 */ + $query_item = trim($query_item); + + /* 如果查询项为空则返回false */ + if (!$query_item) + { + return false; + } + + /* 处理建表操作 */ + if (preg_match('/^\s*CREATE\s+TABLE\s*/i', $query_item)) + { + if (!$this->create_table($query_item)) + { + return false; + } + } + /* 处理ALTER TABLE语句,此时程序将对表的结构进行修改 */ + elseif ($this->auto_match && preg_match('/^\s*ALTER\s+TABLE\s*/i', $query_item)) + { + if (!$this->alter_table($query_item)) + { + return false; + } + } + /* 处理其它修改操作,如数据添加、更新、删除等 */ + else + { + if (!$this->do_other($query_item)) + { + return false; + } + } + + return true; + } + + /** + * 过滤SQL查询串中的注释。该方法只过滤SQL文件中独占一行或一块的那些注释。 + * + * @access public + * @param string $sql SQL查询串 + * @return string 返回已过滤掉注释的SQL查询串。 + */ + function remove_comment($sql) + { + /* 删除SQL行注释,行注释不匹配换行符 */ + $sql = preg_replace('/^\s*(?:--|#).*/m', '', $sql); + + /* 删除SQL块注释,匹配换行符,且为非贪婪匹配 */ + //$sql = preg_replace('/^\s*\/\*(?:.|\n)*\*\//m', '', $sql); + $sql = preg_replace('/^\s*\/\*.*?\*\//ms', '', $sql); + + return $sql; + } + + /** + * 替换查询串中数据表的前缀。该方法只对下列查询有效:CREATE TABLE, + * DROP TABLE, ALTER TABLE, UPDATE, REPLACE INTO, INSERT INTO + * + * @access public + * @param string $sql SQL查询串 + * @return string 返回已替换掉前缀的SQL查询串。 + */ + function replace_prefix($sql) + { + $keywords = 'CREATE\s+TABLE(?:\s+IF\s+NOT\s+EXISTS)?|' + . 'DROP\s+TABLE(?:\s+IF\s+EXISTS)?|' + . 'ALTER\s+TABLE|' + . 'UPDATE|' + . 'REPLACE\s+INTO|' + . 'DELETE\s+FROM|' + . 'INSERT\s+INTO'; + + $pattern = '/(' . $keywords . ')(\s*)`?' . $this->source_prefix . '(\w+)`?(\s*)/i'; + $replacement = '\1\2`' . $this->target_prefix . '\3`\4'; + $sql = preg_replace($pattern, $replacement, $sql); + + $pattern = '/(UPDATE.*?WHERE)(\s*)`?' . $this->source_prefix . '(\w+)`?(\s*\.)/i'; + $replacement = '\1\2`' . $this->target_prefix . '\3`\4'; + $sql = preg_replace($pattern, $replacement, $sql); + + return $sql; + } + + /** + * 获取表的名字。该方法只对下列查询有效:CREATE TABLE, + * DROP TABLE, ALTER TABLE, UPDATE, REPLACE INTO, INSERT INTO + * + * @access public + * @param string $query_item SQL查询项 + * @param string $query_type 查询类型 + * @return mixed 成功返回表的名字,失败返回false。 + */ + function get_table_name($query_item, $query_type = '') + { + $pattern = ''; + $matches = array(); + $table_name = ''; + + /* 如果没指定$query_type,则自动获取 */ + if (!$query_type && preg_match('/^\s*(\w+)/', $query_item, $matches)) + { + $query_type = $matches[1]; + } + + /* 获取相应的正则表达式 */ + $query_type = strtoupper($query_type); + switch ($query_type) + { + case 'ALTER' : + $pattern = '/^\s*ALTER\s+TABLE\s*`?(\w+)/i'; + break; + case 'CREATE' : + $pattern = '/^\s*CREATE\s+TABLE(?:\s+IF\s+NOT\s+EXISTS)?\s*`?(\w+)/i'; + break; + case 'DROP' : + $pattern = '/^\s*DROP\s+TABLE(?:\s+IF\s+EXISTS)?\s*`?(\w+)/i'; + break; + case 'INSERT' : + $pattern = '/^\s*INSERT\s+INTO\s*`?(\w+)/i'; + break; + case 'REPLACE' : + $pattern = '/^\s*REPLACE\s+INTO\s*`?(\w+)/i'; + break; + case 'UPDATE' : + $pattern = '/^\s*UPDATE\s*`?(\w+)/i'; + break; + default : + return false; + } + + if (!preg_match($pattern, $query_item, $matches)) + { + return false; + } + $table_name = $matches[1]; + + return $table_name; + } + + /** + * 获得SQL文件中指定的查询项 + * + * @access public + * @param string $file_path SQL查询项 + * @param int $pos 查询项的索引号 + * @return mixed 成功返回该查询项,失败返回false。 + */ + function get_spec_query_item($file_path, $pos) + { + $query_items = $this->parse_sql_file($file_path); + + if (empty($query_items) + || empty($query_items[$pos])) + { + return false; + } + + return $query_items[$pos]; + } + + /** + * 概据MYSQL版本,创建数据表 + * + * @access public + * @param string $query_item SQL查询项 + * @return boolean 成功返回true,失败返回false。 + */ + function create_table($query_item) + { + /* 获取建表主体串以及表属性声明串,不区分大小写,匹配换行符,且为贪婪匹配 */ + $pattern = '/^\s*(CREATE\s+TABLE[^(]+\(.*\))(.*)$/is'; + if (!preg_match($pattern, $query_item, $matches)) + { + return false; + } + $main = $matches[1]; + $postfix = $matches[2]; + + /* 从表属性声明串中查找表的类型 */ + $pattern = '/.*(?:ENGINE|TYPE)\s*=\s*([a-z]+).*$/is'; + $type = preg_match($pattern, $postfix, $matches) ? $matches[1] : 'MYISAM'; + + /* 从表属性声明串中查找自增语句 */ + $pattern = '/.*(AUTO_INCREMENT\s*=\s*\d+).*$/is'; + $auto_incr = preg_match($pattern, $postfix, $matches) ? $matches[1] : ''; + + /* 重新设置表属性声明串 */ + $postfix = $this->db->version() > '4.1' ? " ENGINE=$type DEFAULT CHARACTER SET " . $this->db_charset + : " TYPE=$type"; + $postfix .= ' ' . $auto_incr; + + /* 重新构造建表语句 */ + $sql = $main . $postfix; + + /* 开始创建表 */ + if (!$this->db->query($sql, 'SILENT')) + { + $this->handle_error($sql); + return false; + } + + return true; + } + + /** + * 修改数据表的方法。算法设计思路: + * 1. 先进行字段修改操作。CHANGE + * 2. 然后进行字段移除操作。DROP [COLUMN] + * 3. 接着进行字段添加操作。ADD [COLUMN] + * 4. 进行索引移除操作。DROP INDEX + * 5. 进行索引添加操作。ADD INDEX + * 6. 最后进行其它操作。 + * + * @access public + * @param string $query_item SQL查询项 + * @return boolean 修改成功返回true,否则返回false + */ + function alter_table($query_item) + { + /* 获取表名 */ + $table_name = $this->get_table_name($query_item, 'ALTER'); + if (!$table_name) + { + return false; + } + + /* 先把CHANGE操作提取出来执行,再过滤掉它们 */ + $result = $this->parse_change_query($query_item, $table_name); + if ($result[0] && !$this->db->query($result[0], 'SILENT')) + { + $this->handle_error($result[0]); + return false; + } + if (!$result[1]) + { + return true; + } + + /* 把DROP [COLUMN]提取出来执行,再过滤掉它们 */ + $result = $this->parse_drop_column_query($result[1], $table_name); + if ($result[0] && !$this->db->query($result[0], 'SILENT')) + { + $this->handle_error($result[0]); + return false; + } + if (!$result[1]) + { + return true; + } + + /* 把ADD [COLUMN]提取出来执行,再过滤掉它们 */ + $result = $this->parse_add_column_query($result[1], $table_name); + if ($result[0] && !$this->db->query($result[0], 'SILENT')) + { + $this->handle_error($result[0]); + return false; + } + if (!$result[1]) + { + return true; + } + + /* 把DROP INDEX提取出来执行,再过滤掉它们 */ + $result = $this->parse_drop_index_query($result[1], $table_name); + if ($result[0] && !$this->db->query($result[0], 'SILENT')) + { + $this->handle_error($result[0]); + return false; + } + if (!$result[1]) + { + return true; + } + + /* 把ADD INDEX提取出来执行,再过滤掉它们 */ + $result = $this->parse_add_index_query($result[1], $table_name); + if ($result[0] && !$this->db->query($result[0], 'SILENT')) + { + $this->handle_error($result[0]); + return false; + } + /* 执行其它的修改操作 */ + if ($result[1] && !$this->db->query($result[1], 'SILENT')) + { + $this->handle_error($result[1]); + return false; + } + + return true; + } + + /** + * 解析出CHANGE操作 + * + * @access public + * @param string $query_item SQL查询项 + * @param string $table_name 表名 + * @return array 返回一个以CHANGE操作串和其它操作串组成的数组 + */ + function parse_change_query($query_item, $table_name = '') + { + $result = array('', $query_item); + + if (!$table_name) + { + $table_name = $this->get_table_name($query_item, 'ALTER'); + } + + $matches = array(); + /* 第1个子模式匹配old_col_name,第2个子模式匹配column_definition,第3个子模式匹配new_col_name */ + $pattern = '/\s*CHANGE\s*`?(\w+)`?\s*`?(\w+)`?([^,(]+\([^,]+?(?:,[^,)]+)*\)[^,]+|[^,;]+)\s*,?/i'; + if (preg_match_all($pattern, $query_item, $matches, PREG_SET_ORDER)) + { + $fields = $this->get_fields($table_name); + $num = count($matches); + $sql = ''; + for ($i = 0; $i < $num; $i++) + { + /* 如果表中存在原列名 */ + if (in_array($matches[$i][1], $fields)) + { + $sql .= $matches[$i][0]; + } + /* 如果表中存在新列名 */ + elseif (in_array($matches[$i][2], $fields)) + { + $sql .= 'CHANGE ' . $matches[$i][2] . ' ' . $matches[$i][2] . ' ' . $matches[$i][3] . ','; + } + else /* 如果两个列名都不存在 */ + { + $sql .= 'ADD ' . $matches[$i][2] . ' ' . $matches[$i][3] . ','; + $sql = preg_replace('/(\s+AUTO_INCREMENT)/i', '\1 PRIMARY KEY', $sql); + } + } + $sql = 'ALTER TABLE ' . $table_name . ' ' . $sql; + $result[0] = preg_replace('/\s*,\s*$/', '', $sql);//存储CHANGE操作,已过滤末尾的逗号 + $result[0] = $this->insert_charset($result[0]);//加入字符集设置 + $result[1] = preg_replace($pattern, '', $query_item);//存储其它操作 + $result[1] = $this->has_other_query($result[1]) ? $result[1]: ''; + } + + return $result; + } + + /** + * 解析出DROP COLUMN操作 + * + * @access public + * @param string $query_item SQL查询项 + * @param string $table_name 表名 + * @return array 返回一个以DROP COLUMN操作和其它操作组成的数组 + */ + function parse_drop_column_query($query_item, $table_name = '') + { + $result = array('', $query_item); + + if (!$table_name) + { + $table_name = $this->get_table_name($query_item, 'ALTER'); + } + + $matches = array(); + /* 子模式存储列名 */ + $pattern = '/\s*DROP(?:\s+COLUMN)?(?!\s+(?:INDEX|PRIMARY))\s*`?(\w+)`?\s*,?/i'; + if (preg_match_all($pattern, $query_item, $matches, PREG_SET_ORDER)) + { + $fields = $this->get_fields($table_name); + $num = count($matches); + $sql = ''; + for ($i = 0; $i < $num; $i++) + { + if (in_array($matches[$i][1], $fields)) + { + $sql .= 'DROP ' . $matches[$i][1] . ','; + } + } + if ($sql) + { + $sql = 'ALTER TABLE ' . $table_name . ' ' . $sql; + $result[0] = preg_replace('/\s*,\s*$/', '', $sql);//过滤末尾的逗号 + } + $result[1] = preg_replace($pattern, '', $query_item);//过滤DROP COLUMN操作 + $result[1] = $this->has_other_query($result[1]) ? $result[1] : ''; + } + + return $result; + } + + /** + * 解析出ADD [COLUMN]操作 + * + * @access public + * @param string $query_item SQL查询项 + * @param string $table_name 表名 + * @return array 返回一个以ADD [COLUMN]操作和其它操作组成的数组 + */ + function parse_add_column_query($query_item, $table_name = '') + { + $result = array('', $query_item); + + if (!$table_name) + { + $table_name = $this->get_table_name($query_item, 'ALTER'); + } + + $matches = array(); + /* 第1个子模式存储列定义,第2个子模式存储列名 */ + $pattern = '/\s*ADD(?:\s+COLUMN)?(?!\s+(?:INDEX|UNIQUE|PRIMARY))\s*(`?(\w+)`?(?:[^,(]+\([^,]+?(?:,[^,)]+)*\)[^,]+|[^,;]+))\s*,?/i'; + if (preg_match_all($pattern, $query_item, $matches, PREG_SET_ORDER)) + { + $fields = $this->get_fields($table_name); + $mysql_ver = $this->db->version(); + $num = count($matches); + $sql = ''; + for ($i = 0; $i < $num; $i++) + { + if (in_array($matches[$i][2], $fields)) + { + /* 如果为低版本MYSQL,则把非法关键字过滤掉 */ + if ($mysql_ver < '4.0.1' ) + { + $matches[$i][1] = preg_replace('/\s*(?:AFTER|FIRST)\s*.*$/i', '', $matches[$i][1]); + } + $sql .= 'CHANGE ' . $matches[$i][2] . ' ' . $matches[$i][1] . ','; + } + else + { + $sql .= 'ADD ' . $matches[$i][1] . ','; + } + } + $sql = 'ALTER TABLE ' . $table_name . ' ' . $sql; + $result[0] = preg_replace('/\s*,\s*$/', '', $sql);//过滤末尾的逗号 + $result[0] = $this->insert_charset($result[0]);//加入字符集设置 + $result[1] = preg_replace($pattern, '', $query_item);//过滤ADD COLUMN操作 + $result[1] = $this->has_other_query($result[1]) ? $result[1] : ''; + } + + return $result; + } + + /** + * 解析出DROP INDEX操作 + * + * @access public + * @param string $query_item SQL查询项 + * @param string $table_name 表名 + * @return array 返回一个以DROP INDEX操作和其它操作组成的数组 + */ + function parse_drop_index_query($query_item, $table_name = '') + { + $result = array('', $query_item); + + if (!$table_name) + { + $table_name = $this->get_table_name($query_item, 'ALTER'); + } + + /* 子模式存储键名 */ + $pattern = '/\s*DROP\s+(?:PRIMARY\s+KEY|INDEX\s*`?(\w+)`?)\s*,?/i'; + if (preg_match_all($pattern, $query_item, $matches, PREG_SET_ORDER)) + { + $indexes = $this->get_indexes($table_name); + $num = count($matches); + $sql = ''; + for ($i = 0; $i < $num; $i++) + { + /* 如果子模式为空,删除主键 */ + if (empty($matches[$i][1])) + { + $sql .= 'DROP PRIMARY KEY,'; + } + /* 否则删除索引 */ + elseif (in_array($matches[$i][1], $indexes)) + { + $sql .= 'DROP INDEX ' . $matches[$i][1] . ','; + } + } + if ($sql) + { + $sql = 'ALTER TABLE ' . $table_name . ' ' . $sql; + $result[0] = preg_replace('/\s*,\s*$/', '', $sql);//存储DROP INDEX操作,已过滤末尾的逗号 + } + $result[1] = preg_replace($pattern, '', $query_item);//存储其它操作 + $result[1] = $this->has_other_query($result[1]) ? $result[1] : ''; + } + + return $result; + } + + /** + * 解析出ADD INDEX操作 + * + * @access public + * @param string $query_item SQL查询项 + * @param string $table_name 表名 + * @return array 返回一个以ADD INDEX操作和其它操作组成的数组 + */ + function parse_add_index_query($query_item, $table_name = '') + { + $result = array('', $query_item); + + if (!$table_name) + { + $table_name = $this->get_table_name($query_item, 'ALTER'); + } + + /* 第1个子模式存储索引定义,第2个子模式存储"PRIMARY KEY",第3个子模式存储键名,第4个子模式存储列名 */ + $pattern = '/\s*ADD\s+((?:INDEX|UNIQUE|(PRIMARY\s+KEY))\s*(?:`?(\w+)`?)?\s*\(\s*`?(\w+)`?\s*(?:,[^,)]+)*\))\s*,?/i'; + if (preg_match_all($pattern, $query_item, $matches, PREG_SET_ORDER)) + { + $indexes = $this->get_indexes($table_name); + $num = count($matches); + $sql = ''; + for ($i = 0; $i < $num; $i++) + { + $index = !empty($matches[$i][3]) ? $matches[$i][3] : $matches[$i][4]; + if (!empty($matches[$i][2]) && in_array('PRIMARY', $indexes)) + { + $sql .= 'DROP PRIMARY KEY,'; + } + elseif (in_array($index, $indexes)) + { + $sql .= 'DROP INDEX ' . $index . ','; + } + $sql .= 'ADD ' . $matches[$i][1] . ','; + } + $sql = 'ALTER TABLE ' . $table_name . ' ' . $sql; + $result[0] = preg_replace('/\s*,\s*$/', '', $sql);//存储ADD INDEX操作,已过滤末尾的逗号 + $result[1] = preg_replace($pattern, '', $query_item);//存储其它的操作 + $result[1] = $this->has_other_query($result[1]) ? $result[1] : ''; + } + + return $result; + } + + /** + * 获取所有的indexes + * + * @access public + * @param string $table_name 数据表名 + * @return array + */ + function get_indexes($table_name) + { + $indexes = array(); + + $result = $this->db->query("SHOW INDEX FROM $table_name", 'SILENT'); + + if ($result) + { + while ($row = $this->db->fetchRow($result)) + { + $indexes[] = $row['Key_name']; + } + } + + return $indexes; + } + + /** + * 获取所有的fields + * + * @access public + * @param string $table_name 数据表名 + * @return array + */ + function get_fields($table_name) + { + $fields = array(); + + $result = $this->db->query("SHOW FIELDS FROM $table_name", 'SILENT'); + + if ($result) + { + while ($row = $this->db->fetchRow($result)) + { + $fields[] = $row['Field']; + } + } + + return $fields; + } + + /** + * 判断是否还有其它的查询 + * + * @access private + * @param string $sql_string SQL查询串 + * @return boolean 有返回true,否则返回false + */ + function has_other_query($sql_string) + { + return preg_match('/^\s*ALTER\s+TABLE\s*`\w+`\s*\w+/i', $sql_string); + } + + /** + * 在查询串中加入字符集设置 + * + * @access private + * @param string $sql_string SQL查询串 + * @return string 含有字符集设置的SQL查询串 + */ + function insert_charset($sql_string) + { + if ($this->db->version() > '4.1') + { + $sql_string = preg_replace('/(TEXT|CHAR\(.*?\)|VARCHAR\(.*?\))\s+/i', + '\1 CHARACTER SET ' . $this->db_charset . ' ', + $sql_string); + } + + return $sql_string; + } + + /** + * 处理其它的数据库操作 + * + * @access private + * @param string $query_item SQL查询项 + * @return boolean 成功返回true,失败返回false。 + */ + function do_other($query_item) + { + if (!$this->db->query($query_item, 'SILENT')) + { + $this->handle_error($query_item); + return false; + } + + return true; + } + + /** + * 处理错误信息 + * + * @access private + * @param string $query_item SQL查询项 + * @return boolean 成功返回true,失败返回false。 + */ + function handle_error($query_item) + { + $mysql_error = 'ERROR NO: ' . $this->db->errno() + . "\r\nERROR MSG: " . $this->db->error(); + + $error_str = "SQL Error:\r\n " . $mysql_error + . "\r\n\r\n" + . "Query String:\r\n ". $query_item + . "\r\n\r\n" + . "File Path:\r\n ". $this->current_file + . "\r\n\r\n\r\n\r\n"; + + /* 过滤一些错误 */ + if (!in_array($this->db->errno(), $this->ignored_errors)) + { + $this->error = $error_str; + } + + if ($this->log_path) + { + $f = @fopen($this->log_path, 'ab+'); + if (!$f) + { + return false; + } + if (!@fwrite($f, $error_str)) + { + return false; + } + } + + return true; + } +} + +?> \ No newline at end of file diff --git a/includes/cls_template.php b/includes/cls_template.php new file mode 100644 index 0000000..f6970c3 --- /dev/null +++ b/includes/cls_template.php @@ -0,0 +1,1423 @@ +cls_template(); + } + + function cls_template() + { + $this->_errorlevel = error_reporting(); + $this->_nowtime = time(); + if (defined('EC_CHARSET')) + { + $charset = EC_CHARSET; + } + else + { + $charset = 'utf-8'; + } + header('Content-type: text/html; charset='.$charset); + } + + /** + * 注册变量 + * + * @access public + * @param mix $tpl_var + * @param mix $value + * + * @return void + */ + function assign($tpl_var, $value = '') + { + if (is_array($tpl_var)) + { + foreach ($tpl_var AS $key => $val) + { + if ($key != '') + { + $this->_var[$key] = $val; + } + } + } + else + { + if ($tpl_var != '') + { + $this->_var[$tpl_var] = $value; + } + } + } + + /** + * 显示页面函数 + * + * @access public + * @param string $filename + * @param sting $cache_id + * + * @return void + */ + function display($filename, $cache_id = '') + { + $this->_seterror++; + error_reporting(E_ALL ^ E_NOTICE); + + $this->_checkfile = false; + $out = $this->fetch($filename, $cache_id); + + if (strpos($out, $this->_echash) !== false) + { + $k = explode($this->_echash, $out); + foreach ($k AS $key => $val) + { + if (($key % 2) == 1) + { + $k[$key] = $this->insert_mod($val); + } + } + $out = implode('', $k); + } + error_reporting($this->_errorlevel); + $this->_seterror--; + + echo $out; + } + + /** + * 处理模板文件 + * + * @access public + * @param string $filename + * @param sting $cache_id + * + * @return sring + */ + function fetch($filename, $cache_id = '') + { + if (!$this->_seterror) + { + error_reporting(E_ALL ^ E_NOTICE); + } + $this->_seterror++; + + if (strncmp($filename,'str:', 4) == 0) + { + $out = $this->_eval($this->fetch_str(substr($filename, 4))); + } + else + { + if ($this->_checkfile) + { + if (!file_exists($filename)) + { + $filename = $this->template_dir . '/' . $filename; + } + } + else + { + $filename = $this->template_dir . '/' . $filename; + } + + if ($this->direct_output) + { + $this->_current_file = $filename; + + $out = $this->_eval($this->fetch_str(file_get_contents($filename))); + } + else + { + if ($cache_id && $this->caching) + { + $out = $this->template_out; + } + else + { + if (!in_array($filename, $this->template)) + { + $this->template[] = $filename; + } + + $out = $this->make_compiled($filename); + + if ($cache_id) + { + $cachename = basename($filename, strrchr($filename, '.')) . '_' . $cache_id; + $data = serialize(array('template' => $this->template, 'expires' => $this->_nowtime + $this->cache_lifetime, 'maketime' => $this->_nowtime)); + $out = str_replace("\r", '', $out); + + while (strpos($out, "\n\n") !== false) + { + $out = str_replace("\n\n", "\n", $out); + } + + $hash_dir = $this->cache_dir . '/' . substr(md5($cachename), 0, 1); + if (!is_dir($hash_dir)) + { + mkdir($hash_dir); + } + if (file_put_contents($hash_dir . '/' . $cachename . '.php', '' . $data . $out, LOCK_EX) === false) + { + trigger_error('can\'t write:' . $hash_dir . '/' . $cachename . '.php'); + } + $this->template = array(); + } + } + } + } + + $this->_seterror--; + if (!$this->_seterror) + { + error_reporting($this->_errorlevel); + } + + return $out; // 返回html数据 + } + + /** + * 编译模板函数 + * + * @access public + * @param string $filename + * + * @return sring 编译后文件地址 + */ + function make_compiled($filename) + { + $name = $this->compile_dir . '/' . basename($filename) . '.php'; + if ($this->_expires) + { + $expires = $this->_expires - $this->cache_lifetime; + } + else + { + $filestat = @stat($name); + $expires = $filestat['mtime']; + } + + $filestat = @stat($filename); + + if ($filestat['mtime'] <= $expires && !$this->force_compile) + { + if (file_exists($name)) + { + $source = $this->_require($name); + if ($source == '') + { + $expires = 0; + } + } + else + { + $source = ''; + $expires = 0; + } + } + + if ($this->force_compile || $filestat['mtime'] > $expires) + { + $this->_current_file = $filename; + $source = $this->fetch_str(file_get_contents($filename)); + + if (file_put_contents($name, $source, LOCK_EX) === false) + { + trigger_error('can\'t write:' . $name); + } + + $source = $this->_eval($source); + } + + return $source; + } + + /** + * 处理字符串函数 + * + * @access public + * @param string $source + * + * @return sring + */ + function fetch_str($source) + { + if (!defined('ECS_ADMIN')) + { + $source = $this->smarty_prefilter_preCompile($source); + } + + return preg_replace("/{([^\}\{\n]*)}/e", "\$this->select('\\1');", $source); + } + + /** + * 判断是否缓存 + * + * @access public + * @param string $filename + * @param sting $cache_id + * + * @return bool + */ + function is_cached($filename, $cache_id = '') + { + $cachename = basename($filename, strrchr($filename, '.')) . '_' . $cache_id; + if ($this->caching == true && $this->direct_output == false) + { + $hash_dir = $this->cache_dir . '/' . substr(md5($cachename), 0, 1); + if ($data = @file_get_contents($hash_dir . '/' . $cachename . '.php')) + { + $data = substr($data, 13); + $pos = strpos($data, '<'); + $paradata = substr($data, 0, $pos); + $para = @unserialize($paradata); + if ($para === false || $this->_nowtime > $para['expires']) + { + $this->caching = false; + + return false; + } + $this->_expires = $para['expires']; + + $this->template_out = substr($data, $pos); + + foreach ($para['template'] AS $val) + { + $stat = @stat($val); + if ($para['maketime'] < $stat['mtime']) + { + $this->caching = false; + + return false; + } + } + } + else + { + $this->caching = false; + + return false; + } + + return true; + } + else + { + return false; + } + } + + /** + * 处理{}标签 + * + * @access public + * @param string $tag + * + * @return sring + */ + function select($tag) + { + $tag = stripslashes(trim($tag)); + + if (empty($tag)) + { + return '{}'; + } + elseif ($tag{0} == '*' && substr($tag, -1) == '*') // 注释部分 + { + return ''; + } + elseif ($tag{0} == '$') // 变量 + { + return 'get_val(substr($tag, 1)) . '; ?>'; + } + elseif ($tag{0} == '/') // 结束 tag + { + switch (substr($tag, 1)) + { + case 'if': + return ''; + break; + + case 'foreach': + if ($this->_foreachmark == 'foreachelse') + { + $output = ''; + } + else + { + array_pop($this->_patchstack); + $output = ''; + } + $output .= "pop_vars();; ?>"; + + return $output; + break; + + case 'literal': + return ''; + break; + + default: + return '{'. $tag .'}'; + break; + } + } + else + { + $tag_sel = array_shift(explode(' ', $tag)); + switch ($tag_sel) + { + case 'if': + + return $this->_compile_if_tag(substr($tag, 3)); + break; + + case 'else': + + return ''; + break; + + case 'elseif': + + return $this->_compile_if_tag(substr($tag, 7), true); + break; + + case 'foreachelse': + $this->_foreachmark = 'foreachelse'; + + return ''; + break; + + case 'foreach': + $this->_foreachmark = 'foreach'; + if(!isset($this->_patchstack)) + { + $this->_patchstack = array(); + } + return $this->_compile_foreach_start(substr($tag, 8)); + break; + + case 'assign': + $t = $this->get_para(substr($tag, 7),0); + + if ($t['value']{0} == '$') + { + /* 如果传进来的值是变量,就不用用引号 */ + $tmp = '$this->assign(\'' . $t['var'] . '\',' . $t['value'] . ');'; + } + else + { + $tmp = '$this->assign(\'' . $t['var'] . '\',\'' . addcslashes($t['value'], "'") . '\');'; + } + // $tmp = $this->assign($t['var'], $t['value']); + + return ''; + break; + + case 'include': + $t = $this->get_para(substr($tag, 8), 0); + + return 'fetch(' . "'$t[file]'" . '); ?>'; + break; + + case 'insert_scripts': + $t = $this->get_para(substr($tag, 15), 0); + + return 'smarty_insert_scripts(' . $this->make_array($t) . '); ?>'; + break; + + case 'create_pages': + $t = $this->get_para(substr($tag, 13), 0); + + return 'smarty_create_pages(' . $this->make_array($t) . '); ?>'; + break; + + case 'insert' : + $t = $this->get_para(substr($tag, 7), false); + + $out = "_echash . $k[\'name\'] . \'|\' . serialize($k) . $this->_echash;' . "\n?>"; + + return $out; + break; + + case 'literal': + return ''; + break; + + case 'cycle' : + $t = $this->get_para(substr($tag, 6), 0); + + return 'cycle(' . $this->make_array($t) . '); ?>'; + break; + + case 'html_options': + $t = $this->get_para(substr($tag, 13), 0); + + return 'html_options(' . $this->make_array($t) . '); ?>'; + break; + + case 'html_select_date': + $t = $this->get_para(substr($tag, 17), 0); + + return 'html_select_date(' . $this->make_array($t) . '); ?>'; + break; + + case 'html_radios': + $t = $this->get_para(substr($tag, 12), 0); + + return 'html_radios(' . $this->make_array($t) . '); ?>'; + break; + + case 'html_select_time': + $t = $this->get_para(substr($tag, 12), 0); + + return 'html_select_time(' . $this->make_array($t) . '); ?>'; + break; + + default: + return '{' . $tag . '}'; + break; + } + } + } + + /** + * 处理smarty标签中的变量标签 + * + * @access public + * @param string $val + * + * @return bool + */ + function get_val($val) + { + if (strrpos($val, '[') !== false) + { + $val = preg_replace("/\[([^\[\]]*)\]/eis", "'.'.str_replace('$','\$','\\1')", $val); + } + + if (strrpos($val, '|') !== false) + { + $moddb = explode('|', $val); + $val = array_shift($moddb); + } + + if (empty($val)) + { + return ''; + } + + if (strpos($val, '.$') !== false) + { + $all = explode('.$', $val); + + foreach ($all AS $key => $val) + { + $all[$key] = $key == 0 ? $this->make_var($val) : '['. $this->make_var($val) . ']'; + } + $p = implode('', $all); + } + else + { + $p = $this->make_var($val); + } + + if (!empty($moddb)) + { + foreach ($moddb AS $key => $mod) + { + $s = explode(':', $mod); + switch ($s[0]) + { + case 'escape': + $s[1] = trim($s[1], '"'); + if ($s[1] == 'html') + { + $p = 'htmlspecialchars(' . $p . ')'; + } + elseif ($s[1] == 'url') + { + $p = 'urlencode(' . $p . ')'; + } + elseif ($s[1] == 'decode_url') + { + $p = 'urldecode(' . $p . ')'; + } + elseif ($s[1] == 'quotes') + { + $p = 'addslashes(' . $p . ')'; + } + elseif ($s[1] == 'u8_url') + { + if (EC_CHARSET != 'utf-8') + { + $p = 'urlencode(ecs_iconv("' . EC_CHARSET . '", "utf-8",' . $p . '))'; + } + else + { + $p = 'urlencode(' . $p . ')'; + } + } + else + { + $p = 'htmlspecialchars(' . $p . ')'; + } + break; + + case 'nl2br': + $p = 'nl2br(' . $p . ')'; + break; + + case 'default': + $s[1] = $s[1]{0} == '$' ? $this->get_val(substr($s[1], 1)) : "'$s[1]'"; + $p = 'empty(' . $p . ') ? ' . $s[1] . ' : ' . $p; + break; + + case 'truncate': + $p = 'sub_str(' . $p . ",$s[1])"; + break; + + case 'strip_tags': + $p = 'strip_tags(' . $p . ')'; + break; + + default: + # code... + break; + } + } + } + + return $p; + } + + /** + * 处理去掉$的字符串 + * + * @access public + * @param string $val + * + * @return bool + */ + function make_var($val) + { + if (strrpos($val, '.') === false) + { + if (isset($this->_var[$val]) && isset($this->_patchstack[$val])) + { + $val = $this->_patchstack[$val]; + } + $p = '$this->_var[\'' . $val . '\']'; + } + else + { + $t = explode('.', $val); + $_var_name = array_shift($t); + if (isset($this->_var[$_var_name]) && isset($this->_patchstack[$_var_name])) + { + $_var_name = $this->_patchstack[$_var_name]; + } + if ($_var_name == 'smarty') + { + $p = $this->_compile_smarty_ref($t); + } + else + { + $p = '$this->_var[\'' . $_var_name . '\']'; + } + foreach ($t AS $val) + { + $p.= '[\'' . $val . '\']'; + } + } + + return $p; + } + + /** + * 处理insert外部函数/需要include运行的函数的调用数据 + * + * @access public + * @param string $val + * @param int $type + * + * @return array + */ + function get_para($val, $type = 1) // 处理insert外部函数/需要include运行的函数的调用数据 + { + $pa = $this->str_trim($val); + foreach ($pa AS $value) + { + if (strrpos($value, '=')) + { + list($a, $b) = explode('=', str_replace(array(' ', '"', "'", '"'), '', $value)); + if ($b{0} == '$') + { + if ($type) + { + eval('$para[\'' . $a . '\']=' . $this->get_val(substr($b, 1)) . ';'); + } + else + { + $para[$a] = $this->get_val(substr($b, 1)); + } + } + else + { + $para[$a] = $b; + } + } + } + + return $para; + } + + /** + * 判断变量是否被注册并返回值 + * + * @access public + * @param string $name + * + * @return mix + */ + function &get_template_vars($name = null) + { + if (empty($name)) + { + return $this->_var; + } + elseif (!empty($this->_var[$name])) + { + return $this->_var[$name]; + } + else + { + $_tmp = null; + + return $_tmp; + } + } + + /** + * 处理if标签 + * + * @access public + * @param string $tag_args + * @param bool $elseif + * + * @return string + */ + function _compile_if_tag($tag_args, $elseif = false) + { + preg_match_all('/\-?\d+[\.\d]+|\'[^\'|\s]*\'|"[^"|\s]*"|[\$\w\.]+|!==|===|==|!=|<>|<<|>>|<=|>=|&&|\|\||\(|\)|,|\!|\^|=|&|<|>|~|\||\%|\+|\-|\/|\*|\@|\S/', $tag_args, $match); + + $tokens = $match[0]; + // make sure we have balanced parenthesis + $token_count = array_count_values($tokens); + if (!empty($token_count['(']) && $token_count['('] != $token_count[')']) + { + // $this->_syntax_error('unbalanced parenthesis in if statement', E_USER_ERROR, __FILE__, __LINE__); + } + + for ($i = 0, $count = count($tokens); $i < $count; $i++) + { + $token = &$tokens[$i]; + switch (strtolower($token)) + { + case 'eq': + $token = '=='; + break; + + case 'ne': + case 'neq': + $token = '!='; + break; + + case 'lt': + $token = '<'; + break; + + case 'le': + case 'lte': + $token = '<='; + break; + + case 'gt': + $token = '>'; + break; + + case 'ge': + case 'gte': + $token = '>='; + break; + + case 'and': + $token = '&&'; + break; + + case 'or': + $token = '||'; + break; + + case 'not': + $token = '!'; + break; + + case 'mod': + $token = '%'; + break; + + default: + if ($token[0] == '$') + { + $token = $this->get_val(substr($token, 1)); + } + break; + } + } + + if ($elseif) + { + return ''; + } + else + { + return ''; + } + } + + /** + * 处理foreach标签 + * + * @access public + * @param string $tag_args + * + * @return string + */ + function _compile_foreach_start($tag_args) + { + $attrs = $this->get_para($tag_args, 0); + $arg_list = array(); + $from = $attrs['from']; + if(isset($this->_var[$attrs['item']]) && !isset($this->_patchstack[$attrs['item']])) + { + $this->_patchstack[$attrs['item']] = $attrs['item'] . '_' . str_replace(array(' ', '.'), '_', microtime()); + $attrs['item'] = $this->_patchstack[$attrs['item']]; + } + else + { + $this->_patchstack[$attrs['item']] = $attrs['item']; + } + $item = $this->get_val($attrs['item']); + + if (!empty($attrs['key'])) + { + $key = $attrs['key']; + $key_part = $this->get_val($key).' => '; + } + else + { + $key = null; + $key_part = ''; + } + + if (!empty($attrs['name'])) + { + $name = $attrs['name']; + } + else + { + $name = null; + } + + $output = 'push_vars('$attrs[key]', '$attrs[item]');"; + + if (!empty($name)) + { + $foreach_props = "\$this->_foreach['$name']"; + $output .= "{$foreach_props} = array('total' => count(\$_from), 'iteration' => 0);\n"; + $output .= "if ({$foreach_props}['total'] > 0):\n"; + $output .= " foreach (\$_from AS $key_part$item):\n"; + $output .= " {$foreach_props}['iteration']++;\n"; + } + else + { + $output .= "if (count(\$_from)):\n"; + $output .= " foreach (\$_from AS $key_part$item):\n"; + } + return $output . '?>'; + } + + /** + * 将 foreach 的 key, item 放入临时数组 + * + * @param mixed $key + * @param mixed $val + * + * @return void + */ + function push_vars($key, $val) + { + if (!empty($key)) + { + array_push($this->_temp_key, "\$this->_vars['$key']='" .$this->_vars[$key] . "';"); + } + if (!empty($val)) + { + array_push($this->_temp_val, "\$this->_vars['$val']='" .$this->_vars[$val] ."';"); + } + } + + /** + * 弹出临时数组的最后一个 + * + * @return void + */ + function pop_vars() + { + $key = array_pop($this->_temp_key); + $val = array_pop($this->_temp_val); + + if (!empty($key)) + { + eval($key); + } + } + + /** + * 处理smarty开头的预定义变量 + * + * @access public + * @param array $indexes + * + * @return string + */ + function _compile_smarty_ref(&$indexes) + { + /* Extract the reference name. */ + $_ref = $indexes[0]; + + switch ($_ref) + { + case 'now': + $compiled_ref = 'time()'; + break; + + case 'foreach': + array_shift($indexes); + $_var = $indexes[0]; + $_propname = $indexes[1]; + switch ($_propname) + { + case 'index': + array_shift($indexes); + $compiled_ref = "(\$this->_foreach['$_var']['iteration'] - 1)"; + break; + + case 'first': + array_shift($indexes); + $compiled_ref = "(\$this->_foreach['$_var']['iteration'] <= 1)"; + break; + + case 'last': + array_shift($indexes); + $compiled_ref = "(\$this->_foreach['$_var']['iteration'] == \$this->_foreach['$_var']['total'])"; + break; + + case 'show': + array_shift($indexes); + $compiled_ref = "(\$this->_foreach['$_var']['total'] > 0)"; + break; + + default: + $compiled_ref = "\$this->_foreach['$_var']"; + break; + } + break; + + case 'get': + $compiled_ref = '$_GET'; + break; + + case 'post': + $compiled_ref = '$_POST'; + break; + + case 'cookies': + $compiled_ref = '$_COOKIE'; + break; + + case 'env': + $compiled_ref = '$_ENV'; + break; + + case 'server': + $compiled_ref = '$_SERVER'; + break; + + case 'request': + $compiled_ref = '$_REQUEST'; + break; + + case 'session': + $compiled_ref = '$_SESSION'; + break; + + default: + // $this->_syntax_error('$smarty.' . $_ref . ' is an unknown reference', E_USER_ERROR, __FILE__, __LINE__); + break; + } + array_shift($indexes); + + return $compiled_ref; + } + + function smarty_insert_scripts($args) + { + static $scripts = array(); + + $arr = explode(',', str_replace(' ', '', $args['files'])); + + $str = ''; + foreach ($arr AS $val) + { + if (in_array($val, $scripts) == false) + { + $scripts[] = $val; + if ($val{0} == '.') + { + $str .= ''; + } + else + { + $str .= ''; + } + } + } + + return $str; + } + + function smarty_prefilter_preCompile($source) + { + $file_type = strtolower(strrchr($this->_current_file, '.')); + $tmp_dir = 'themes/' . $GLOBALS['_CFG']['template'] . '/'; // 模板所在路径 + + /** + * 处理模板文件 + */ + if ($file_type == '.dwt') + { + /* 将模板中所有library替换为链接 */ + $pattern = '/.*?/se'; + $replacement = "'{include file='.strtolower('\\1'). '}'"; + $source = preg_replace($pattern, $replacement, $source); + + /* 检查有无动态库文件,如果有为其赋值 */ + $dyna_libs = get_dyna_libs($GLOBALS['_CFG']['template'], $this->_current_file); + if ($dyna_libs) + { + foreach ($dyna_libs AS $region => $libs) + { + $pattern = '/(.*?)/s'; + + if (preg_match($pattern, $source, $reg_match)) + { + $reg_content = $reg_match[1]; + /* 生成匹配字串 */ + $keys = array_keys($libs); + $lib_pattern = ''; + foreach ($keys AS $lib) + { + $lib_pattern .= '|' . str_replace('/', '\/', substr($lib, 1)); + } + $lib_pattern = '/{include\sfile=(' . substr($lib_pattern, 1) . ')}/'; + /* 修改$reg_content中的内容 */ + $GLOBALS['libs'] = $libs; + $reg_content = preg_replace_callback($lib_pattern, 'dyna_libs_replace', $reg_content); + + /* 用修改过的内容替换原来当前区域中内容 */ + $source = preg_replace($pattern, $reg_content, $source); + } + } + } + + /* 在头部加入版本信息 */ + $source = preg_replace('//i', "\r\n", $source); + + /* 修正css路径 */ + $source = preg_replace('/(<\/script>)/', '\1' . $tmp_dir . '\2', $source); + + /* 更换编译模板的编码类型 */ + $source = preg_replace('/]*?>\r?\n?/i', '' . "\n", $source); + + } + + /** + * 处理库文件 + */ + elseif ($file_type == '.lbi') + { + /* 去除meta */ + $source = preg_replace('/\r?\n?/i', '', $source); + } + + /* 替换文件编码头部 */ + if (strpos($source, "\xEF\xBB\xBF") !== FALSE) + { + $source = str_replace("\xEF\xBB\xBF", '', $source); + } + + $pattern = array( + '//', // 替换smarty注释 + '//', // 替换不换行的html注释 + '/(href=["|\'])\.\.\/(.*?)(["|\'])/i', // 替换相对链接 + '/((?:background|src)\s*=\s*["|\'])(?:\.\/|\.\.\/)?(images\/.*?["|\'])/is', // 在images前加上 $tmp_dir + '/((?:background|background-image):\s*?url\()(?:\.\/|\.\.\/)?(images\/)/is', // 在images前加上 $tmp_dir + '/([\'|"])\.\.\//is', // 以../开头的路径全部修正为空 + ); + $replace = array( + '\1', + '', + '\1\2\3', + '\1' . $tmp_dir . '\2', + '\1' . $tmp_dir . '\2', + '\1' + ); + return preg_replace($pattern, $replace, $source); + } + + function insert_mod($name) // 处理动态内容 + { + list($fun, $para) = explode('|', $name); + $para = unserialize($para); + $fun = 'insert_' . $fun; + + return $fun($para); + } + + function str_trim($str) + { + /* 处理'a=b c=d k = f '类字符串,返回数组 */ + while (strpos($str, '= ') != 0) + { + $str = str_replace('= ', '=', $str); + } + while (strpos($str, ' =') != 0) + { + $str = str_replace(' =', '=', $str); + } + + return explode(' ', trim($str)); + } + + function _eval($content) + { + ob_start(); + eval('?' . '>' . trim($content)); + $content = ob_get_contents(); + ob_end_clean(); + + return $content; + } + + function _require($filename) + { + ob_start(); + include $filename; + $content = ob_get_contents(); + ob_end_clean(); + + return $content; + } + + function html_options($arr) + { + $selected = $arr['selected']; + + if ($arr['options']) + { + $options = (array)$arr['options']; + } + elseif ($arr['output']) + { + if ($arr['values']) + { + foreach ($arr['output'] AS $key => $val) + { + $options["{$arr[values][$key]}"] = $val; + } + } + else + { + $options = array_values((array)$arr['output']); + } + } + if ($options) + { + foreach ($options AS $key => $val) + { + $out .= $key == $selected ? "" : ""; + } + } + + return $out; + } + + function html_select_date($arr) + { + $pre = $arr['prefix']; + if (isset($arr['time'])) + { + if (intval($arr['time']) > 10000) + { + $arr['time'] = gmdate('Y-m-d', $arr['time'] + 8*3600); + } + $t = explode('-', $arr['time']); + $year = strval($t[0]); + $month = strval($t[1]); + $day = strval($t[2]); + } + $now = gmdate('Y', $this->_nowtime); + if (isset($arr['start_year'])) + { + if (abs($arr['start_year']) == $arr['start_year']) + { + $startyear = $arr['start_year']; + } + else + { + $startyear = $arr['start_year'] + $now; + } + } + else + { + $startyear = $now - 3; + } + + if (isset($arr['end_year'])) + { + if (strlen(abs($arr['end_year'])) == strlen($arr['end_year'])) + { + $endyear = $arr['end_year']; + } + else + { + $endyear = $arr['end_year'] + $now; + } + } + else + { + $endyear = $now + 3; + } + + $out = "  '; + } + + function html_radios($arr) + { + $name = $arr['name']; + $checked = $arr['checked']; + $options = $arr['options']; + + $out = ''; + foreach ($options AS $key => $val) + { + $out .= $key == $checked ? " {$val} " + : " {$val} "; + } + + return $out; + } + + function html_select_time($arr) + { + $pre = $arr['prefix']; + if (isset($arr['time'])) + { + $arr['time'] = gmdate('H-i-s', $arr['time'] + 8*3600); + $t = explode('-', $arr['time']); + $hour = strval($t[0]); + $minute = strval($t[1]); + $second = strval($t[2]); + } + $out = ''; + if (!isset($arr['display_hours'])) + { + $out .= " "; + } + if (!isset($arr['display_minutes'])) + { + $out .= " "; + } + if (!isset($arr['display_seconds'])) + { + $out .= " "; + } + + return $out; + } + function cycle($arr) + { + static $k, $old; + + $value = explode(',', $arr['values']); + if ($old != $value) + { + $old = $value; + $k = 0; + } + else + { + $k++; + if (!isset($old[$k])) + { + $k = 0; + } + } + + echo $old[$k]; + } + + function make_array($arr) + { + $out = ''; + foreach ($arr AS $key => $val) + { + if ($val{0} == '$') + { + $out .= $out ? ",'$key'=>$val" : "array('$key'=>$val"; + } + else + { + $out .= $out ? ",'$key'=>'$val'" : "array('$key'=>'$val'"; + } + } + + return $out . ')'; + } + + function smarty_create_pages($params) + { + extract($params); + + if (empty($page)) + { + $page = 1; + } + + if (!empty($count)) + { + $str = ""; + $min = min($count - 1, $page + 3); + for ($i = $page - 3 ; $i <= $min ; $i++) + { + if ($i < 2) + { + continue; + } + $str .= "
';var A=FCKDocumentProcessor_CreateFakeImage('FCK__PageBreak',e);var B=new FCKDomRange(FCK.EditorWindow);B.MoveToSelection();var C=B.SplitBlock();B.InsertNode(A);FCK.Events.FireEvent('OnSelectionChange');};FCKPageBreakCommand.prototype.GetState=function(){if (FCK.EditMode!=0) return -1;return 0;};var FCKUnlinkCommand=function(){this.Name='Unlink';};FCKUnlinkCommand.prototype.Execute=function(){FCKUndo.SaveUndoStep();if (FCKBrowserInfo.IsGeckoLike){var A=FCK.Selection.MoveToAncestorNode('A');if (A) FCKTools.RemoveOuterTags(A);return;};FCK.ExecuteNamedCommand(this.Name);};FCKUnlinkCommand.prototype.GetState=function(){if (FCK.EditMode!=0) return -1;var A=FCK.GetNamedCommandState(this.Name);if (A==0&&FCK.EditMode==0){var B=FCKSelection.MoveToAncestorNode('A');var C=(B&&B.name.length>0&&B.href.length==0);if (C) A=-1;};return A;};FCKVisitLinkCommand=function(){this.Name='VisitLink';};FCKVisitLinkCommand.prototype={GetState:function(){if (FCK.EditMode!=0) return -1;var A=FCK.GetNamedCommandState('Unlink');if (A==0){var B=FCKSelection.MoveToAncestorNode('A');if (!B.href) A=-1;};return A;},Execute:function(){var A=FCKSelection.MoveToAncestorNode('A');var B=A.getAttribute('_fcksavedurl')||A.getAttribute('href',2);if (!/:\/\//.test(B)){var C=FCKConfig.BaseHref;var D=FCK.GetInstanceObject('parent');if (!C){C=D.document.location.href;C=C.substring(0,C.lastIndexOf('/')+1);};if (/^\//.test(B)){try{C=C.match(/^.*:\/\/+[^\/]+/)[0];}catch (e){C=D.document.location.protocol+'://'+D.parent.document.location.host;}};B=C+B;};if (!window.open(B,'_blank')) alert(FCKLang.VisitLinkBlocked);}};var FCKSelectAllCommand=function(){this.Name='SelectAll';};FCKSelectAllCommand.prototype.Execute=function(){if (FCK.EditMode==0){FCK.ExecuteNamedCommand('SelectAll');}else{var A=FCK.EditingArea.Textarea;if (FCKBrowserInfo.IsIE){A.createTextRange().execCommand('SelectAll');}else{A.selectionStart=0;A.selectionEnd=A.value.length;};A.focus();}};FCKSelectAllCommand.prototype.GetState=function(){if (FCK.EditMode!=0) return -1;return 0;};var FCKPasteCommand=function(){this.Name='Paste';};FCKPasteCommand.prototype={Execute:function(){if (FCKBrowserInfo.IsIE) FCK.Paste();else FCK.ExecuteNamedCommand('Paste');},GetState:function(){if (FCK.EditMode!=0) return -1;return FCK.GetNamedCommandState('Paste');}};var FCKRuleCommand=function(){this.Name='Rule';};FCKRuleCommand.prototype={Execute:function(){FCKUndo.SaveUndoStep();FCK.InsertElement('hr');},GetState:function(){if (FCK.EditMode!=0) return -1;return FCK.GetNamedCommandState('InsertHorizontalRule');}};var FCKCutCopyCommand=function(A){this.Name=A?'Cut':'Copy';};FCKCutCopyCommand.prototype={Execute:function(){var A=false;if (FCKBrowserInfo.IsIE){var B=function(){A=true;};var C='on'+this.Name.toLowerCase();FCK.EditorDocument.body.attachEvent(C,B);FCK.ExecuteNamedCommand(this.Name);FCK.EditorDocument.body.detachEvent(C,B);}else{try{FCK.ExecuteNamedCommand(this.Name);A=true;}catch(e){}};if (!A) alert(FCKLang['PasteError'+this.Name]);},GetState:function(){return FCK.EditMode!=0?-1:FCK.GetNamedCommandState('Cut');}};var FCKAnchorDeleteCommand=function(){this.Name='AnchorDelete';};FCKAnchorDeleteCommand.prototype={Execute:function(){if (FCK.Selection.GetType()=='Control'){FCK.Selection.Delete();}else{var A=FCK.Selection.GetSelectedElement();if (A){if (A.tagName=='IMG'&&A.getAttribute('_fckanchor')) oAnchor=FCK.GetRealElement(A);else A=null;};if (!A){oAnchor=FCK.Selection.MoveToAncestorNode('A');if (oAnchor) FCK.Selection.SelectNode(oAnchor);};if (oAnchor.href.length!=0){oAnchor.removeAttribute('name');if (FCKBrowserInfo.IsIE) oAnchor.className=oAnchor.className.replace(FCKRegexLib.FCK_Class,'');return;};if (A){A.parentNode.removeChild(A);return;};if (oAnchor.innerHTML.length==0){oAnchor.parentNode.removeChild(oAnchor);return;};FCKTools.RemoveOuterTags(oAnchor);};if (FCKBrowserInfo.IsGecko) FCK.Selection.Collapse(true);},GetState:function(){if (FCK.EditMode!=0) return -1;return FCK.GetNamedCommandState('Unlink');}};var FCKDeleteDivCommand=function(){};FCKDeleteDivCommand.prototype={GetState:function(){if (FCK.EditMode!=0) return -1;var A=FCKSelection.GetParentElement();var B=new FCKElementPath(A);return B.BlockLimit&&B.BlockLimit.nodeName.IEquals('div')?0:-1;},Execute:function(){FCKUndo.SaveUndoStep();var A=FCKDomTools.GetSelectedDivContainers();var B=new FCKDomRange(FCK.EditorWindow);B.MoveToSelection();var C=B.CreateBookmark();for (var i=0;i\n \n
\n '+FCKLang.ColorAutomatic+'\n \n ';FCKTools.AddEventListenerEx(C,'click',FCKTextColorCommand_AutoOnClick,this);if (!FCKBrowserInfo.IsIE) C.style.width='96%';var G=FCKConfig.FontColors.toString().split(',');var H=0;while (H
';if (H>=G.length) C.style.visibility='hidden';else FCKTools.AddEventListenerEx(C,'click',FCKTextColorCommand_OnClick,[this,L]);}};if (FCKConfig.EnableMoreFontColors){E=D.insertRow(-1).insertCell(-1);E.colSpan=8;C=E.appendChild(CreateSelectionDiv());C.innerHTML='
'+FCKLang.ColorMoreColors+'
';FCKTools.AddEventListenerEx(C,'click',FCKTextColorCommand_MoreOnClick,this);};if (!FCKBrowserInfo.IsIE) C.style.width='96%';}; +var FCKPastePlainTextCommand=function(){this.Name='PasteText';};FCKPastePlainTextCommand.prototype.Execute=function(){FCK.PasteAsPlainText();};FCKPastePlainTextCommand.prototype.GetState=function(){if (FCK.EditMode!=0) return -1;return FCK.GetNamedCommandState('Paste');}; +var FCKPasteWordCommand=function(){this.Name='PasteWord';};FCKPasteWordCommand.prototype.Execute=function(){FCK.PasteFromWord();};FCKPasteWordCommand.prototype.GetState=function(){if (FCK.EditMode!=0||FCKConfig.ForcePasteAsPlainText) return -1;else return FCK.GetNamedCommandState('Paste');}; +var FCKTableCommand=function(A){this.Name=A;};FCKTableCommand.prototype.Execute=function(){FCKUndo.SaveUndoStep();if (!FCKBrowserInfo.IsGecko){switch (this.Name){case 'TableMergeRight':return FCKTableHandler.MergeRight();case 'TableMergeDown':return FCKTableHandler.MergeDown();}};switch (this.Name){case 'TableInsertRowAfter':return FCKTableHandler.InsertRow(false);case 'TableInsertRowBefore':return FCKTableHandler.InsertRow(true);case 'TableDeleteRows':return FCKTableHandler.DeleteRows();case 'TableInsertColumnAfter':return FCKTableHandler.InsertColumn(false);case 'TableInsertColumnBefore':return FCKTableHandler.InsertColumn(true);case 'TableDeleteColumns':return FCKTableHandler.DeleteColumns();case 'TableInsertCellAfter':return FCKTableHandler.InsertCell(null,false);case 'TableInsertCellBefore':return FCKTableHandler.InsertCell(null,true);case 'TableDeleteCells':return FCKTableHandler.DeleteCells();case 'TableMergeCells':return FCKTableHandler.MergeCells();case 'TableHorizontalSplitCell':return FCKTableHandler.HorizontalSplitCell();case 'TableVerticalSplitCell':return FCKTableHandler.VerticalSplitCell();case 'TableDelete':return FCKTableHandler.DeleteTable();default:return alert(FCKLang.UnknownCommand.replace(/%1/g,this.Name));}};FCKTableCommand.prototype.GetState=function(){if (FCK.EditorDocument!=null&&FCKSelection.HasAncestorNode('TABLE')){switch (this.Name){case 'TableHorizontalSplitCell':case 'TableVerticalSplitCell':if (FCKTableHandler.GetSelectedCells().length==1) return 0;else return -1;case 'TableMergeCells':if (FCKTableHandler.CheckIsSelectionRectangular()&&FCKTableHandler.GetSelectedCells().length>1) return 0;else return -1;case 'TableMergeRight':return FCKTableHandler.GetMergeRightTarget()?0:-1;case 'TableMergeDown':return FCKTableHandler.GetMergeDownTarget()?0:-1;default:return 0;}}else return -1;}; +var FCKFitWindow=function(){this.Name='FitWindow';};FCKFitWindow.prototype.Execute=function(){var A=window.frameElement;var B=A.style;var C=parent;var D=C.document.documentElement;var E=C.document.body;var F=E.style;var G;var H=new FCKDomRange(FCK.EditorWindow);H.MoveToSelection();var I=FCKTools.GetScrollPosition(FCK.EditorWindow);if (!this.IsMaximized){if(FCKBrowserInfo.IsIE) C.attachEvent('onresize',FCKFitWindow_Resize);else C.addEventListener('resize',FCKFitWindow_Resize,true);this._ScrollPos=FCKTools.GetScrollPosition(C);G=A;while((G=G.parentNode)){if (G.nodeType==1){G._fckSavedStyles=FCKTools.SaveStyles(G);G.style.zIndex=FCKConfig.FloatingPanelsZIndex-1;}};if (FCKBrowserInfo.IsIE){this.documentElementOverflow=D.style.overflow;D.style.overflow='hidden';F.overflow='hidden';}else{F.overflow='hidden';F.width='0px';F.height='0px';};this._EditorFrameStyles=FCKTools.SaveStyles(A);var J=FCKTools.GetViewPaneSize(C);B.position="absolute";A.offsetLeft;B.zIndex=FCKConfig.FloatingPanelsZIndex-1;B.left="0px";B.top="0px";B.width=J.Width+"px";B.height=J.Height+"px";if (!FCKBrowserInfo.IsIE){B.borderRight=B.borderBottom="9999px solid white";B.backgroundColor="white";};C.scrollTo(0,0);var K=FCKTools.GetWindowPosition(C,A);if (K.x!=0) B.left=(-1*K.x)+"px";if (K.y!=0) B.top=(-1*K.y)+"px";this.IsMaximized=true;}else{if(FCKBrowserInfo.IsIE) C.detachEvent("onresize",FCKFitWindow_Resize);else C.removeEventListener("resize",FCKFitWindow_Resize,true);G=A;while((G=G.parentNode)){if (G._fckSavedStyles){FCKTools.RestoreStyles(G,G._fckSavedStyles);G._fckSavedStyles=null;}};if (FCKBrowserInfo.IsIE) D.style.overflow=this.documentElementOverflow;FCKTools.RestoreStyles(A,this._EditorFrameStyles);C.scrollTo(this._ScrollPos.X,this._ScrollPos.Y);this.IsMaximized=false;};FCKToolbarItems.GetItem('FitWindow').RefreshState();if (FCK.EditMode==0) FCK.EditingArea.MakeEditable();FCK.Focus();H.Select();FCK.EditorWindow.scrollTo(I.X,I.Y);};FCKFitWindow.prototype.GetState=function(){if (FCKConfig.ToolbarLocation!='In') return -1;else return (this.IsMaximized?1:0);};function FCKFitWindow_Resize(){var A=FCKTools.GetViewPaneSize(parent);var B=window.frameElement.style;B.width=A.Width+'px';B.height=A.Height+'px';}; +var FCKListCommand=function(A,B){this.Name=A;this.TagName=B;};FCKListCommand.prototype={GetState:function(){if (FCK.EditMode!=0||!FCK.EditorWindow) return -1;var A=FCKSelection.GetBoundaryParentElement(true);var B=A;while (B){if (B.nodeName.IEquals(['ul','ol'])) break;B=B.parentNode;};if (B&&B.nodeName.IEquals(this.TagName)) return 1;else return 0;},Execute:function(){FCKUndo.SaveUndoStep();var A=FCK.EditorDocument;var B=new FCKDomRange(FCK.EditorWindow);B.MoveToSelection();var C=this.GetState();if (C==0){FCKDomTools.TrimNode(A.body);if (!A.body.firstChild){var D=A.createElement('p');A.body.appendChild(D);B.MoveToNodeContents(D);}};var E=B.CreateBookmark();var F=[];var G={};var H=new FCKDomRangeIterator(B);var I;H.ForceBrBreak=(C==0);var J=true;var K=null;while (J){while ((I=H.GetNextParagraph())){var L=new FCKElementPath(I);var M=null;var N=false;var O=L.BlockLimit;for (var i=L.Elements.length-1;i>=0;i--){var P=L.Elements[i];if (P.nodeName.IEquals(['ol','ul'])){if (O._FCK_ListGroupObject) O._FCK_ListGroupObject=null;var Q=P._FCK_ListGroupObject;if (Q) Q.contents.push(I);else{Q={ 'root':P,'contents':[I] };F.push(Q);FCKDomTools.SetElementMarker(G,P,'_FCK_ListGroupObject',Q);};N=true;break;}};if (N) continue;var R=O;if (R._FCK_ListGroupObject) R._FCK_ListGroupObject.contents.push(I);else{var Q={ 'root':R,'contents':[I] };FCKDomTools.SetElementMarker(G,R,'_FCK_ListGroupObject',Q);F.push(Q);}};if (FCKBrowserInfo.IsIE) J=false;else{if (K==null){K=[];var T=FCKSelection.GetSelection();if (T&&F.length==0) K.push(T.getRangeAt(0));for (var i=1;T&&i0){var Q=F.shift();if (C==0){if (Q.root.nodeName.IEquals(['ul','ol'])) this._ChangeListType(Q,G,W);else this._CreateList(Q,W);}else if (C==1&&Q.root.nodeName.IEquals(['ul','ol'])) this._RemoveList(Q,G);};for (var i=0;iC[i-1].indent+1){var H=C[i-1].indent+1-C[i].indent;var I=C[i].indent;while (C[i]&&C[i].indent>=I){C[i].indent+=H;i++;};i--;}};var J=FCKDomTools.ArrayToList(C,B);if (A.root.nextSibling==null||A.root.nextSibling.nodeName.IEquals('br')){if (J.listNode.lastChild.nodeName.IEquals('br')) J.listNode.removeChild(J.listNode.lastChild);};A.root.parentNode.replaceChild(J.listNode,A.root);}}; +var FCKJustifyCommand=function(A){this.AlignValue=A;var B=FCKConfig.ContentLangDirection.toLowerCase();this.IsDefaultAlign=(A=='left'&&B=='ltr')||(A=='right'&&B=='rtl');var C=this._CssClassName=(function(){var D=FCKConfig.JustifyClasses;if (D){switch (A){case 'left':return D[0]||null;case 'center':return D[1]||null;case 'right':return D[2]||null;case 'justify':return D[3]||null;}};return null;})();if (C&&C.length>0) this._CssClassRegex=new RegExp('(?:^|\\s+)'+C+'(?=$|\\s)');};FCKJustifyCommand._GetClassNameRegex=function(){var A=FCKJustifyCommand._ClassRegex;if (A!=undefined) return A;var B=[];var C=FCKConfig.JustifyClasses;if (C){for (var i=0;i<4;i++){var D=C[i];if (D&&D.length>0) B.push(D);}};if (B.length>0) A=new RegExp('(?:^|\\s+)(?:'+B.join('|')+')(?=$|\\s)');else A=null;return FCKJustifyCommand._ClassRegex=A;};FCKJustifyCommand.prototype={Execute:function(){FCKUndo.SaveUndoStep();var A=new FCKDomRange(FCK.EditorWindow);A.MoveToSelection();var B=this.GetState();if (B==-1) return;var C=A.CreateBookmark();var D=this._CssClassName;var E=new FCKDomRangeIterator(A);var F;while ((F=E.GetNextParagraph())){F.removeAttribute('align');if (D){var G=F.className.replace(FCKJustifyCommand._GetClassNameRegex(),'');if (B==0){if (G.length>0) G+=' ';F.className=G+D;}else if (G.length==0) FCKDomTools.RemoveAttribute(F,'class');}else{var H=F.style;if (B==0) H.textAlign=this.AlignValue;else{H.textAlign='';if (H.cssText.length==0) F.removeAttribute('style');}}};A.MoveToBookmark(C);A.Select();FCK.Focus();FCK.Events.FireEvent('OnSelectionChange');},GetState:function(){if (FCK.EditMode!=0||!FCK.EditorWindow) return -1;var A=new FCKElementPath(FCKSelection.GetBoundaryParentElement(true));var B=A.Block||A.BlockLimit;if (!B||B.nodeName.toLowerCase()=='body') return 0;var C;if (FCKBrowserInfo.IsIE) C=B.currentStyle.textAlign;else C=FCK.EditorWindow.getComputedStyle(B,'').getPropertyValue('text-align');C=C.replace(/(-moz-|-webkit-|start|auto)/i,'');if ((!C&&this.IsDefaultAlign)||C==this.AlignValue) return 1;return 0;}}; +var FCKIndentCommand=function(A,B){this.Name=A;this.Offset=B;this.IndentCSSProperty=FCKConfig.ContentLangDirection.IEquals('ltr')?'marginLeft':'marginRight';};FCKIndentCommand._InitIndentModeParameters=function(){if (FCKConfig.IndentClasses&&FCKConfig.IndentClasses.length>0){this._UseIndentClasses=true;this._IndentClassMap={};for (var i=0;i0?H+' ':'')+FCKConfig.IndentClasses[G-1];}else{var I=parseInt(E.style[this.IndentCSSProperty],10);if (isNaN(I)) I=0;I+=this.Offset;I=Math.max(I,0);I=Math.ceil(I/this.Offset)*this.Offset;E.style[this.IndentCSSProperty]=I?I+FCKConfig.IndentUnit:'';if (E.getAttribute('style')=='') E.removeAttribute('style');}}},_IndentList:function(A,B){var C=A.StartContainer;var D=A.EndContainer;while (C&&C.parentNode!=B) C=C.parentNode;while (D&&D.parentNode!=B) D=D.parentNode;if (!C||!D) return;var E=C;var F=[];var G=false;while (G==false){if (E==D) G=true;F.push(E);E=E.nextSibling;};if (F.length<1) return;var H=FCKDomTools.GetParents(B);for (var i=0;iN;i++) M[i].indent+=I;var O=FCKDomTools.ArrayToList(M);if (O) B.parentNode.replaceChild(O.listNode,B);FCKDomTools.ClearAllMarkers(L);}}; +var FCKBlockQuoteCommand=function(){};FCKBlockQuoteCommand.prototype={Execute:function(){FCKUndo.SaveUndoStep();var A=this.GetState();var B=new FCKDomRange(FCK.EditorWindow);B.MoveToSelection();var C=B.CreateBookmark();if (FCKBrowserInfo.IsIE){var D=B.GetBookmarkNode(C,true);var E=B.GetBookmarkNode(C,false);var F;if (D&&D.parentNode.nodeName.IEquals('blockquote')&&!D.previousSibling){F=D;while ((F=F.nextSibling)){if (FCKListsLib.BlockElements[F.nodeName.toLowerCase()]) FCKDomTools.MoveNode(D,F,true);}};if (E&&E.parentNode.nodeName.IEquals('blockquote')&&!E.previousSibling){F=E;while ((F=F.nextSibling)){if (FCKListsLib.BlockElements[F.nodeName.toLowerCase()]){if (F.firstChild==D) FCKDomTools.InsertAfterNode(D,E);else FCKDomTools.MoveNode(E,F,true);}}}};var G=new FCKDomRangeIterator(B);var H;if (A==0){G.EnforceRealBlocks=true;var I=[];while ((H=G.GetNextParagraph())) I.push(H);if (I.length<1){para=B.Window.document.createElement(FCKConfig.EnterMode.IEquals('p')?'p':'div');B.InsertNode(para);para.appendChild(B.Window.document.createTextNode('\ufeff'));B.MoveToBookmark(C);B.MoveToNodeContents(para);B.Collapse(true);C=B.CreateBookmark();I.push(para);};var J=I[0].parentNode;var K=[];for (var i=0;i0){H=I.shift();while (H.parentNode!=J) H=H.parentNode;if (H!=L) K.push(H);L=H;}while (K.length>0){H=K.shift();if (H.nodeName.IEquals('blockquote')){var M=FCKTools.GetElementDocument(H).createDocumentFragment();while (H.firstChild){M.appendChild(H.removeChild(H.firstChild));I.push(M.lastChild);};H.parentNode.replaceChild(M,H);}else I.push(H);};var N=B.Window.document.createElement('blockquote');J.insertBefore(N,I[0]);while (I.length>0){H=I.shift();N.appendChild(H);}}else if (A==1){var O=[];while ((H=G.GetNextParagraph())){var P=null;var Q=null;while (H.parentNode){if (H.parentNode.nodeName.IEquals('blockquote')){P=H.parentNode;Q=H;break;};H=H.parentNode;};if (P&&Q) O.push(Q);};var R=[];while (O.length>0){var S=O.shift();var N=S.parentNode;if (S==S.parentNode.firstChild){N.parentNode.insertBefore(N.removeChild(S),N);if (!N.firstChild) N.parentNode.removeChild(N);}else if (S==S.parentNode.lastChild){N.parentNode.insertBefore(N.removeChild(S),N.nextSibling);if (!N.firstChild) N.parentNode.removeChild(N);}else FCKDomTools.BreakParent(S,S.parentNode,B);R.push(S);};if (FCKConfig.EnterMode.IEquals('br')){while (R.length){var S=R.shift();var W=true;if (S.nodeName.IEquals('div')){var M=FCKTools.GetElementDocument(S).createDocumentFragment();var Y=W&&S.previousSibling&&!FCKListsLib.BlockBoundaries[S.previousSibling.nodeName.toLowerCase()];if (W&&Y) M.appendChild(FCKTools.GetElementDocument(S).createElement('br'));var Z=S.nextSibling&&!FCKListsLib.BlockBoundaries[S.nextSibling.nodeName.toLowerCase()];while (S.firstChild) M.appendChild(S.removeChild(S.firstChild));if (Z) M.appendChild(FCKTools.GetElementDocument(S).createElement('br'));S.parentNode.replaceChild(M,S);W=false;}}}};B.MoveToBookmark(C);B.Select();FCK.Focus();FCK.Events.FireEvent('OnSelectionChange');},GetState:function(){if (FCK.EditMode!=0||!FCK.EditorWindow) return -1;var A=new FCKElementPath(FCKSelection.GetBoundaryParentElement(true));var B=A.Block||A.BlockLimit;if (!B||B.nodeName.toLowerCase()=='body') return 0;for (var i=0;i';B.open();B.write(''+F+'<\/head><\/body><\/html>');B.close();if(FCKBrowserInfo.IsAIR) FCKAdobeAIR.Panel_Contructor(B,window.document.location);FCKTools.AddEventListenerEx(E,'focus',FCKPanel_Window_OnFocus,this);FCKTools.AddEventListenerEx(E,'blur',FCKPanel_Window_OnBlur,this);};B.dir=FCKLang.Dir;FCKTools.AddEventListener(B,'contextmenu',FCKTools.CancelEvent);this.MainNode=B.body.appendChild(B.createElement('DIV'));this.MainNode.style.cssFloat=this.IsRTL?'right':'left';};FCKPanel.prototype.AppendStyleSheet=function(A){FCKTools.AppendStyleSheet(this.Document,A);};FCKPanel.prototype.Preload=function(x,y,A){if (this._Popup) this._Popup.show(x,y,0,0,A);};FCKPanel.prototype.Show=function(x,y,A,B,C){var D;var E=this.MainNode;if (this._Popup){this._Popup.show(x,y,0,0,A);FCKDomTools.SetElementStyles(E,{B:B?B+'px':'',C:C?C+'px':''});D=E.offsetWidth;if (this.IsRTL){if (this.IsContextMenu) x=x-D+1;else if (A) x=(x*-1)+A.offsetWidth-D;};this._Popup.show(x,y,D,E.offsetHeight,A);if (this.OnHide){if (this._Timer) CheckPopupOnHide.call(this,true);this._Timer=FCKTools.SetInterval(CheckPopupOnHide,100,this);}}else{if (typeof(FCK.ToolbarSet.CurrentInstance.FocusManager)!='undefined') FCK.ToolbarSet.CurrentInstance.FocusManager.Lock();if (this.ParentPanel){this.ParentPanel.Lock();FCKPanel_Window_OnBlur(null,this.ParentPanel);};if (FCKBrowserInfo.IsGecko&&FCKBrowserInfo.IsMac){this._IFrame.scrolling='';FCKTools.RunFunction(function(){ this._IFrame.scrolling='no';},this);};if (FCK.ToolbarSet.CurrentInstance.GetInstanceObject('FCKPanel')._OpenedPanel&&FCK.ToolbarSet.CurrentInstance.GetInstanceObject('FCKPanel')._OpenedPanel!=this) FCK.ToolbarSet.CurrentInstance.GetInstanceObject('FCKPanel')._OpenedPanel.Hide(false,true);FCKDomTools.SetElementStyles(E,{B:B?B+'px':'',C:C?C+'px':''});D=E.offsetWidth;if (!B) this._IFrame.width=1;if (!C) this._IFrame.height=1;D=E.offsetWidth||E.firstChild.offsetWidth;var F=FCKTools.GetDocumentPosition(this._Window,A.nodeType==9?(FCKTools.IsStrictMode(A)?A.documentElement:A.body):A);var G=FCKDomTools.GetPositionedAncestor(this._IFrame.parentNode);if (G){var H=FCKTools.GetDocumentPosition(FCKTools.GetElementWindow(G),G);F.x-=H.x;F.y-=H.y;};if (this.IsRTL&&!this.IsContextMenu) x=(x*-1);x+=F.x;y+=F.y;if (this.IsRTL){if (this.IsContextMenu) x=x-D+1;else if (A) x=x+A.offsetWidth-D;}else{var I=FCKTools.GetViewPaneSize(this._Window);var J=FCKTools.GetScrollPosition(this._Window);var K=I.Height+J.Y;var L=I.Width+J.X;if ((x+D)>L) x-=x+D-L;if ((y+E.offsetHeight)>K) y-=y+E.offsetHeight-K;};FCKDomTools.SetElementStyles(this._IFrame,{left:x+'px',top:y+'px'});this._IFrame.contentWindow.focus();this._IsOpened=true;var M=this;this._resizeTimer=setTimeout(function(){var N=E.offsetWidth||E.firstChild.offsetWidth;var O=E.offsetHeight;M._IFrame.style.width=N+'px';M._IFrame.style.height=O+'px';},0);FCK.ToolbarSet.CurrentInstance.GetInstanceObject('FCKPanel')._OpenedPanel=this;};FCKTools.RunFunction(this.OnShow,this);};FCKPanel.prototype.Hide=function(A,B){if (this._Popup) this._Popup.hide();else{if (!this._IsOpened||this._LockCounter>0) return;if (typeof(FCKFocusManager)!='undefined'&&!B) FCKFocusManager.Unlock();this._IFrame.style.width=this._IFrame.style.height='0px';this._IsOpened=false;if (this._resizeTimer){clearTimeout(this._resizeTimer);this._resizeTimer=null;};if (this.ParentPanel) this.ParentPanel.Unlock();if (!A) FCKTools.RunFunction(this.OnHide,this);}};FCKPanel.prototype.CheckIsOpened=function(){if (this._Popup) return this._Popup.isOpen;else return this._IsOpened;};FCKPanel.prototype.CreateChildPanel=function(){var A=this._Popup?FCKTools.GetDocumentWindow(this.Document):this._Window;var B=new FCKPanel(A);B.ParentPanel=this;return B;};FCKPanel.prototype.Lock=function(){this._LockCounter++;};FCKPanel.prototype.Unlock=function(){if (--this._LockCounter==0&&!this.HasFocus) this.Hide();};function FCKPanel_Window_OnFocus(e,A){A.HasFocus=true;};function FCKPanel_Window_OnBlur(e,A){A.HasFocus=false;if (A._LockCounter==0) FCKTools.RunFunction(A.Hide,A);};function CheckPopupOnHide(A){if (A||!this._Popup.isOpen){window.clearInterval(this._Timer);this._Timer=null;FCKTools.RunFunction(this.OnHide,this);}};function FCKPanel_Cleanup(){this._Popup=null;this._Window=null;this.Document=null;this.MainNode=null;}; +var FCKIcon=function(A){var B=A?typeof(A):'undefined';switch (B){case 'number':this.Path=FCKConfig.SkinPath+'fck_strip.gif';this.Size=16;this.Position=A;break;case 'undefined':this.Path=FCK_SPACER_PATH;break;case 'string':this.Path=A;break;default:this.Path=A[0];this.Size=A[1];this.Position=A[2];}};FCKIcon.prototype.CreateIconElement=function(A){var B,eIconImage;if (this.Position){var C='-'+((this.Position-1)*this.Size)+'px';if (FCKBrowserInfo.IsIE){B=A.createElement('DIV');eIconImage=B.appendChild(A.createElement('IMG'));eIconImage.src=this.Path;eIconImage.style.top=C;}else{B=A.createElement('IMG');B.src=FCK_SPACER_PATH;B.style.backgroundPosition='0px '+C;B.style.backgroundImage='url("'+this.Path+'")';}}else{if (FCKBrowserInfo.IsIE){B=A.createElement('DIV');eIconImage=B.appendChild(A.createElement('IMG'));eIconImage.src=this.Path?this.Path:FCK_SPACER_PATH;}else{B=A.createElement('IMG');B.src=this.Path?this.Path:FCK_SPACER_PATH;}};B.className='TB_Button_Image';return B;}; +var FCKToolbarButtonUI=function(A,B,C,D,E,F){this.Name=A;this.Label=B||A;this.Tooltip=C||this.Label;this.Style=E||0;this.State=F||0;this.Icon=new FCKIcon(D);if (FCK.IECleanup) FCK.IECleanup.AddItem(this,FCKToolbarButtonUI_Cleanup);};FCKToolbarButtonUI.prototype._CreatePaddingElement=function(A){var B=A.createElement('IMG');B.className='TB_Button_Padding';B.src=FCK_SPACER_PATH;return B;};FCKToolbarButtonUI.prototype.Create=function(A){var B=FCKTools.GetElementDocument(A);var C=this.MainElement=B.createElement('DIV');C.title=this.Tooltip;if (FCKBrowserInfo.IsGecko) C.onmousedown=FCKTools.CancelEvent;FCKTools.AddEventListenerEx(C,'mouseover',FCKToolbarButtonUI_OnMouseOver,this);FCKTools.AddEventListenerEx(C,'mouseout',FCKToolbarButtonUI_OnMouseOut,this);FCKTools.AddEventListenerEx(C,'click',FCKToolbarButtonUI_OnClick,this);this.ChangeState(this.State,true);if (this.Style==0&&!this.ShowArrow){C.appendChild(this.Icon.CreateIconElement(B));}else{var D=C.appendChild(B.createElement('TABLE'));D.cellPadding=0;D.cellSpacing=0;var E=D.insertRow(-1);var F=E.insertCell(-1);if (this.Style==0||this.Style==2) F.appendChild(this.Icon.CreateIconElement(B));else F.appendChild(this._CreatePaddingElement(B));if (this.Style==1||this.Style==2){F=E.insertCell(-1);F.className='TB_Button_Text';F.noWrap=true;F.appendChild(B.createTextNode(this.Label));};if (this.ShowArrow){if (this.Style!=0){E.insertCell(-1).appendChild(this._CreatePaddingElement(B));};F=E.insertCell(-1);var G=F.appendChild(B.createElement('IMG'));G.src=FCKConfig.SkinPath+'images/toolbar.buttonarrow.gif';G.width=5;G.height=3;};F=E.insertCell(-1);F.appendChild(this._CreatePaddingElement(B));};A.appendChild(C);};FCKToolbarButtonUI.prototype.ChangeState=function(A,B){if (!B&&this.State==A) return;var e=this.MainElement;if (!e) return;switch (parseInt(A,10)){case 0:e.className='TB_Button_Off';break;case 1:e.className='TB_Button_On';break;case -1:e.className='TB_Button_Disabled';break;};this.State=A;};function FCKToolbarButtonUI_OnMouseOver(A,B){if (B.State==0) this.className='TB_Button_Off_Over';else if (B.State==1) this.className='TB_Button_On_Over';};function FCKToolbarButtonUI_OnMouseOut(A,B){if (B.State==0) this.className='TB_Button_Off';else if (B.State==1) this.className='TB_Button_On';};function FCKToolbarButtonUI_OnClick(A,B){if (B.OnClick&&B.State!=-1) B.OnClick(B);};function FCKToolbarButtonUI_Cleanup(){this.MainElement=null;}; +var FCKToolbarButton=function(A,B,C,D,E,F,G){this.CommandName=A;this.Label=B;this.Tooltip=C;this.Style=D;this.SourceView=E?true:false;this.ContextSensitive=F?true:false;if (G==null) this.IconPath=FCKConfig.SkinPath+'toolbar/'+A.toLowerCase()+'.gif';else if (typeof(G)=='number') this.IconPath=[FCKConfig.SkinPath+'fck_strip.gif',16,G];else this.IconPath=G;};FCKToolbarButton.prototype.Create=function(A){this._UIButton=new FCKToolbarButtonUI(this.CommandName,this.Label,this.Tooltip,this.IconPath,this.Style);this._UIButton.OnClick=this.Click;this._UIButton._ToolbarButton=this;this._UIButton.Create(A);};FCKToolbarButton.prototype.RefreshState=function(){var A=this._UIButton;if (!A) return;var B=FCK.ToolbarSet.CurrentInstance.Commands.GetCommand(this.CommandName).GetState();if (B==A.State) return;A.ChangeState(B);};FCKToolbarButton.prototype.Click=function(){var A=this._ToolbarButton||this;FCK.ToolbarSet.CurrentInstance.Commands.GetCommand(A.CommandName).Execute();};FCKToolbarButton.prototype.Enable=function(){this.RefreshState();};FCKToolbarButton.prototype.Disable=function(){this._UIButton.ChangeState(-1);}; +var FCKSpecialCombo=function(A,B,C,D,E){this.FieldWidth=B||100;this.PanelWidth=C||150;this.PanelMaxHeight=D||150;this.Label=' ';this.Caption=A;this.Tooltip=A;this.Style=2;this.Enabled=true;this.Items={};this._Panel=new FCKPanel(E||window);this._Panel.AppendStyleSheet(FCKConfig.SkinEditorCSS);this._PanelBox=this._Panel.MainNode.appendChild(this._Panel.Document.createElement('DIV'));this._PanelBox.className='SC_Panel';this._PanelBox.style.width=this.PanelWidth+'px';this._PanelBox.innerHTML='
';this._ItemsHolderEl=this._PanelBox.getElementsByTagName('TD')[0];if (FCK.IECleanup) FCK.IECleanup.AddItem(this,FCKSpecialCombo_Cleanup);};function FCKSpecialCombo_ItemOnMouseOver(){this.className+=' SC_ItemOver';};function FCKSpecialCombo_ItemOnMouseOut(){this.className=this.originalClass;};function FCKSpecialCombo_ItemOnClick(A,B,C){this.className=this.originalClass;B._Panel.Hide();B.SetLabel(this.FCKItemLabel);if (typeof(B.OnSelect)=='function') B.OnSelect(C,this);};FCKSpecialCombo.prototype.ClearItems=function (){if (this.Items) this.Items={};var A=this._ItemsHolderEl;while (A.firstChild) A.removeChild(A.firstChild);};FCKSpecialCombo.prototype.AddItem=function(A,B,C,D){var E=this._ItemsHolderEl.appendChild(this._Panel.Document.createElement('DIV'));E.className=E.originalClass='SC_Item';E.innerHTML=B;E.FCKItemLabel=C||A;E.Selected=false;if (FCKBrowserInfo.IsIE) E.style.width='100%';if (D) E.style.backgroundColor=D;FCKTools.AddEventListenerEx(E,'mouseover',FCKSpecialCombo_ItemOnMouseOver);FCKTools.AddEventListenerEx(E,'mouseout',FCKSpecialCombo_ItemOnMouseOut);FCKTools.AddEventListenerEx(E,'click',FCKSpecialCombo_ItemOnClick,[this,A]);this.Items[A.toString().toLowerCase()]=E;return E;};FCKSpecialCombo.prototype.SelectItem=function(A){if (typeof A=='string') A=this.Items[A.toString().toLowerCase()];if (A){A.className=A.originalClass='SC_ItemSelected';A.Selected=true;}};FCKSpecialCombo.prototype.SelectItemByLabel=function(A,B){for (var C in this.Items){var D=this.Items[C];if (D.FCKItemLabel==A){D.className=D.originalClass='SC_ItemSelected';D.Selected=true;if (B) this.SetLabel(A);}}};FCKSpecialCombo.prototype.DeselectAll=function(A){for (var i in this.Items){if (!this.Items[i]) continue;this.Items[i].className=this.Items[i].originalClass='SC_Item';this.Items[i].Selected=false;};if (A) this.SetLabel('');};FCKSpecialCombo.prototype.SetLabelById=function(A){A=A?A.toString().toLowerCase():'';var B=this.Items[A];this.SetLabel(B?B.FCKItemLabel:'');};FCKSpecialCombo.prototype.SetLabel=function(A){A=(!A||A.length==0)?' ':A;if (A==this.Label) return;this.Label=A;var B=this._LabelEl;if (B){B.innerHTML=A;FCKTools.DisableSelection(B);}};FCKSpecialCombo.prototype.SetEnabled=function(A){this.Enabled=A;if (this._OuterTable) this._OuterTable.className=A?'':'SC_FieldDisabled';};FCKSpecialCombo.prototype.Create=function(A){var B=FCKTools.GetElementDocument(A);var C=this._OuterTable=A.appendChild(B.createElement('TABLE'));C.cellPadding=0;C.cellSpacing=0;C.insertRow(-1);var D;var E;switch (this.Style){case 0:D='TB_ButtonType_Icon';E=false;break;case 1:D='TB_ButtonType_Text';E=false;break;case 2:E=true;break;};if (this.Caption&&this.Caption.length>0&&E){var F=C.rows[0].insertCell(-1);F.innerHTML=this.Caption;F.className='SC_FieldCaption';};var G=FCKTools.AppendElement(C.rows[0].insertCell(-1),'div');if (E){G.className='SC_Field';G.style.width=this.FieldWidth+'px';G.innerHTML='
 
';this._LabelEl=G.getElementsByTagName('label')[0];this._LabelEl.innerHTML=this.Label;}else{G.className='TB_Button_Off';G.innerHTML='
'+this.Caption+'
';};FCKTools.AddEventListenerEx(G,'mouseover',FCKSpecialCombo_OnMouseOver,this);FCKTools.AddEventListenerEx(G,'mouseout',FCKSpecialCombo_OnMouseOut,this);FCKTools.AddEventListenerEx(G,'click',FCKSpecialCombo_OnClick,this);FCKTools.DisableSelection(this._Panel.Document.body);};function FCKSpecialCombo_Cleanup(){this._LabelEl=null;this._OuterTable=null;this._ItemsHolderEl=null;this._PanelBox=null;if (this.Items){for (var A in this.Items) this.Items[A]=null;}};function FCKSpecialCombo_OnMouseOver(A,B){if (B.Enabled){switch (B.Style){case 0:this.className='TB_Button_On_Over';break;case 1:this.className='TB_Button_On_Over';break;case 2:this.className='SC_Field SC_FieldOver';break;}}};function FCKSpecialCombo_OnMouseOut(A,B){switch (B.Style){case 0:this.className='TB_Button_Off';break;case 1:this.className='TB_Button_Off';break;case 2:this.className='SC_Field';break;}};function FCKSpecialCombo_OnClick(e,A){if (A.Enabled){var B=A._Panel;var C=A._PanelBox;var D=A._ItemsHolderEl;var E=A.PanelMaxHeight;if (A.OnBeforeClick) A.OnBeforeClick(A);if (FCKBrowserInfo.IsIE) B.Preload(0,this.offsetHeight,this);if (D.offsetHeight>E) C.style.height=E+'px';else C.style.height='';B.Show(0,this.offsetHeight,this);}}; +var FCKToolbarSpecialCombo=function(){this.SourceView=false;this.ContextSensitive=true;this.FieldWidth=null;this.PanelWidth=null;this.PanelMaxHeight=null;};FCKToolbarSpecialCombo.prototype.DefaultLabel='';function FCKToolbarSpecialCombo_OnSelect(A,B){FCK.ToolbarSet.CurrentInstance.Commands.GetCommand(this.CommandName).Execute(A,B);};FCKToolbarSpecialCombo.prototype.Create=function(A){this._Combo=new FCKSpecialCombo(this.GetLabel(),this.FieldWidth,this.PanelWidth,this.PanelMaxHeight,FCKBrowserInfo.IsIE?window:FCKTools.GetElementWindow(A).parent);this._Combo.Tooltip=this.Tooltip;this._Combo.Style=this.Style;this.CreateItems(this._Combo);this._Combo.Create(A);this._Combo.CommandName=this.CommandName;this._Combo.OnSelect=FCKToolbarSpecialCombo_OnSelect;};function FCKToolbarSpecialCombo_RefreshActiveItems(A,B){A.DeselectAll();A.SelectItem(B);A.SetLabelById(B);};FCKToolbarSpecialCombo.prototype.RefreshState=function(){var A;var B=FCK.ToolbarSet.CurrentInstance.Commands.GetCommand(this.CommandName).GetState();if (B!=-1){A=1;if (this.RefreshActiveItems) this.RefreshActiveItems(this._Combo,B);else{if (this._LastValue!==B){this._LastValue=B;if (!B||B.length==0){this._Combo.DeselectAll();this._Combo.SetLabel(this.DefaultLabel);}else FCKToolbarSpecialCombo_RefreshActiveItems(this._Combo,B);}}}else A=-1;if (A==this.State) return;if (A==-1){this._Combo.DeselectAll();this._Combo.SetLabel('');};this.State=A;this._Combo.SetEnabled(A!=-1);};FCKToolbarSpecialCombo.prototype.Enable=function(){this.RefreshState();};FCKToolbarSpecialCombo.prototype.Disable=function(){this.State=-1;this._Combo.DeselectAll();this._Combo.SetLabel('');this._Combo.SetEnabled(false);}; +var FCKToolbarStyleCombo=function(A,B){if (A===false) return;this.CommandName='Style';this.Label=this.GetLabel();this.Tooltip=A?A:this.Label;this.Style=B?B:2;this.DefaultLabel=FCKConfig.DefaultStyleLabel||'';};FCKToolbarStyleCombo.prototype=new FCKToolbarSpecialCombo;FCKToolbarStyleCombo.prototype.GetLabel=function(){return FCKLang.Style;};FCKToolbarStyleCombo.prototype.GetStyles=function(){var A={};var B=FCK.ToolbarSet.CurrentInstance.Styles.GetStyles();for (var C in B){var D=B[C];if (!D.IsCore) A[C]=D;};return A;};FCKToolbarStyleCombo.prototype.CreateItems=function(A){var B=A._Panel.Document;FCKTools.AppendStyleSheet(B,FCKConfig.ToolbarComboPreviewCSS);FCKTools.AppendStyleString(B,FCKConfig.EditorAreaStyles);B.body.className+=' ForceBaseFont';FCKConfig.ApplyBodyAttributes(B.body);var C=this.GetStyles();for (var D in C){var E=C[D];var F=E.GetType()==2?D:FCKToolbarStyleCombo_BuildPreview(E,E.Label||D);var G=A.AddItem(D,F);G.Style=E;};A.OnBeforeClick=this.StyleCombo_OnBeforeClick;};FCKToolbarStyleCombo.prototype.RefreshActiveItems=function(A){var B=FCK.ToolbarSet.CurrentInstance.Selection.GetBoundaryParentElement(true);if (B){var C=new FCKElementPath(B);var D=C.Elements;for (var e=0;e');var E=A.Element;if (E=='bdo') E='span';D=['<',E];var F=A._StyleDesc.Attributes;if (F){for (var G in F){D.push(' ',G,'="',A.GetFinalAttributeValue(G),'"');}};if (A._GetStyleText().length>0) D.push(' style="',A.GetFinalStyleValue(),'"');D.push('>',B,'');if (C==0) D.push('');return D.join('');}; +var FCKToolbarFontFormatCombo=function(A,B){if (A===false) return;this.CommandName='FontFormat';this.Label=this.GetLabel();this.Tooltip=A?A:this.Label;this.Style=B?B:2;this.NormalLabel='Normal';this.PanelWidth=190;this.DefaultLabel=FCKConfig.DefaultFontFormatLabel||'';};FCKToolbarFontFormatCombo.prototype=new FCKToolbarStyleCombo(false);FCKToolbarFontFormatCombo.prototype.GetLabel=function(){return FCKLang.FontFormat;};FCKToolbarFontFormatCombo.prototype.GetStyles=function(){var A={};var B=FCKLang['FontFormats'].split(';');var C={p:B[0],pre:B[1],address:B[2],h1:B[3],h2:B[4],h3:B[5],h4:B[6],h5:B[7],h6:B[8],div:B[9]||(B[0]+' (DIV)')};var D=FCKConfig.FontFormats.split(';');for (var i=0;i';G.open();G.write(''+H+''+document.getElementById('xToolbarSpace').innerHTML+'');G.close();if(FCKBrowserInfo.IsAIR) FCKAdobeAIR.ToolbarSet_InitOutFrame(G);FCKTools.AddEventListener(G,'contextmenu',FCKTools.CancelEvent);FCKTools.AppendStyleSheet(G,FCKConfig.SkinEditorCSS);B=D.__FCKToolbarSet=new FCKToolbarSet(G);B._IFrame=F;if (FCK.IECleanup) FCK.IECleanup.AddItem(D,FCKToolbarSet_Target_Cleanup);};B.CurrentInstance=FCK;if (!B.ToolbarItems) B.ToolbarItems=FCKToolbarItems;FCK.AttachToOnSelectionChange(B.RefreshItemsState);return B;};function FCK_OnBlur(A){var B=A.ToolbarSet;if (B.CurrentInstance==A) B.Disable();};function FCK_OnFocus(A){var B=A.ToolbarSet;var C=A||FCK;B.CurrentInstance.FocusManager.RemoveWindow(B._IFrame.contentWindow);B.CurrentInstance=C;C.FocusManager.AddWindow(B._IFrame.contentWindow,true);B.Enable();};function FCKToolbarSet_Cleanup(){this._TargetElement=null;this._IFrame=null;};function FCKToolbarSet_Target_Cleanup(){this.__FCKToolbarSet=null;};var FCKToolbarSet=function(A){this._Document=A;this._TargetElement=A.getElementById('xToolbar');var B=A.getElementById('xExpandHandle');var C=A.getElementById('xCollapseHandle');B.title=FCKLang.ToolbarExpand;FCKTools.AddEventListener(B,'click',FCKToolbarSet_Expand_OnClick);C.title=FCKLang.ToolbarCollapse;FCKTools.AddEventListener(C,'click',FCKToolbarSet_Collapse_OnClick);if (!FCKConfig.ToolbarCanCollapse||FCKConfig.ToolbarStartExpanded) this.Expand();else this.Collapse();C.style.display=FCKConfig.ToolbarCanCollapse?'':'none';if (FCKConfig.ToolbarCanCollapse) C.style.display='';else A.getElementById('xTBLeftBorder').style.display='';this.Toolbars=[];this.IsLoaded=false;if (FCK.IECleanup) FCK.IECleanup.AddItem(this,FCKToolbarSet_Cleanup);};function FCKToolbarSet_Expand_OnClick(){FCK.ToolbarSet.Expand();};function FCKToolbarSet_Collapse_OnClick(){FCK.ToolbarSet.Collapse();};FCKToolbarSet.prototype.Expand=function(){this._ChangeVisibility(false);};FCKToolbarSet.prototype.Collapse=function(){this._ChangeVisibility(true);};FCKToolbarSet.prototype._ChangeVisibility=function(A){this._Document.getElementById('xCollapsed').style.display=A?'':'none';this._Document.getElementById('xExpanded').style.display=A?'none':'';if (FCKBrowserInfo.IsGecko){FCKTools.RunFunction(window.onresize);}};FCKToolbarSet.prototype.Load=function(A){this.Name=A;this.Items=[];this.ItemsWysiwygOnly=[];this.ItemsContextSensitive=[];this._TargetElement.innerHTML='';var B=FCKConfig.ToolbarSets[A];if (!B){alert(FCKLang.UnknownToolbarSet.replace(/%1/g,A));return;};this.Toolbars=[];for (var x=0;x0) break;}catch (e){break;};D=D.parent;};var E=D.document;var F=function(){if (!B) B=FCKConfig.FloatingPanelsZIndex+999;return++B;};var G=function(){if (!C) return;var H=FCKTools.IsStrictMode(E)?E.documentElement:E.body;FCKDomTools.SetElementStyles(C,{'width':Math.max(H.scrollWidth,H.clientWidth,E.scrollWidth||0)-1+'px','height':Math.max(H.scrollHeight,H.clientHeight,E.scrollHeight||0)-1+'px'});};return {OpenDialog:function(dialogName,dialogTitle,dialogPage,width,height,customValue,parentWindow,resizable){if (!A) this.DisplayMainCover();var I={Title:dialogTitle,Page:dialogPage,Editor:window,CustomValue:customValue,TopWindow:D};FCK.ToolbarSet.CurrentInstance.Selection.Save();var J=FCKTools.GetViewPaneSize(D);var K={ 'X':0,'Y':0 };var L=FCKBrowserInfo.IsIE&&(!FCKBrowserInfo.IsIE7||!FCKTools.IsStrictMode(D.document));if (L) K=FCKTools.GetScrollPosition(D);var M=Math.max(K.Y+(J.Height-height-20)/2,0);var N=Math.max(K.X+(J.Width-width-20)/2,0);var O=E.createElement('iframe');FCKTools.ResetStyles(O);O.src=FCKConfig.BasePath+'fckdialog.html';O.frameBorder=0;O.allowTransparency=true;FCKDomTools.SetElementStyles(O,{'position':(L)?'absolute':'fixed','top':M+'px','left':N+'px','width':width+'px','height':height+'px','zIndex':F()});O._DialogArguments=I;E.body.appendChild(O);O._ParentDialog=A;A=O;},OnDialogClose:function(dialogWindow){var O=dialogWindow.frameElement;FCKDomTools.RemoveNode(O);if (O._ParentDialog){A=O._ParentDialog;O._ParentDialog.contentWindow.SetEnabled(true);}else{if (!FCKBrowserInfo.IsIE) FCK.Focus();this.HideMainCover();setTimeout(function(){ A=null;},0);FCK.ToolbarSet.CurrentInstance.Selection.Release();}},DisplayMainCover:function(){C=E.createElement('div');FCKTools.ResetStyles(C);FCKDomTools.SetElementStyles(C,{'position':'absolute','zIndex':F(),'top':'0px','left':'0px','backgroundColor':FCKConfig.BackgroundBlockerColor});FCKDomTools.SetOpacity(C,FCKConfig.BackgroundBlockerOpacity);if (FCKBrowserInfo.IsIE&&!FCKBrowserInfo.IsIE7){var Q=E.createElement('iframe');FCKTools.ResetStyles(Q);Q.hideFocus=true;Q.frameBorder=0;Q.src=FCKTools.GetVoidUrl();FCKDomTools.SetElementStyles(Q,{'width':'100%','height':'100%','position':'absolute','left':'0px','top':'0px','filter':'progid:DXImageTransform.Microsoft.Alpha(opacity=0)'});C.appendChild(Q);};FCKTools.AddEventListener(D,'resize',G);G();E.body.appendChild(C);FCKFocusManager.Lock();var R=FCK.ToolbarSet.CurrentInstance.GetInstanceObject('frameElement');R._fck_originalTabIndex=R.tabIndex;R.tabIndex=-1;},HideMainCover:function(){FCKDomTools.RemoveNode(C);FCKFocusManager.Unlock();var R=FCK.ToolbarSet.CurrentInstance.GetInstanceObject('frameElement');R.tabIndex=R._fck_originalTabIndex;FCKDomTools.ClearElementJSProperty(R,'_fck_originalTabIndex');},GetCover:function(){return C;}};})(); +var FCKMenuItem=function(A,B,C,D,E,F){this.Name=B;this.Label=C||B;this.IsDisabled=E;this.Icon=new FCKIcon(D);this.SubMenu=new FCKMenuBlockPanel();this.SubMenu.Parent=A;this.SubMenu.OnClick=FCKTools.CreateEventListener(FCKMenuItem_SubMenu_OnClick,this);this.CustomData=F;if (FCK.IECleanup) FCK.IECleanup.AddItem(this,FCKMenuItem_Cleanup);};FCKMenuItem.prototype.AddItem=function(A,B,C,D,E){this.HasSubMenu=true;return this.SubMenu.AddItem(A,B,C,D,E);};FCKMenuItem.prototype.AddSeparator=function(){this.SubMenu.AddSeparator();};FCKMenuItem.prototype.Create=function(A){var B=this.HasSubMenu;var C=FCKTools.GetElementDocument(A);var r=this.MainElement=A.insertRow(-1);r.className=this.IsDisabled?'MN_Item_Disabled':'MN_Item';if (!this.IsDisabled){FCKTools.AddEventListenerEx(r,'mouseover',FCKMenuItem_OnMouseOver,[this]);FCKTools.AddEventListenerEx(r,'click',FCKMenuItem_OnClick,[this]);if (!B) FCKTools.AddEventListenerEx(r,'mouseout',FCKMenuItem_OnMouseOut,[this]);};var D=r.insertCell(-1);D.className='MN_Icon';D.appendChild(this.Icon.CreateIconElement(C));D=r.insertCell(-1);D.className='MN_Label';D.noWrap=true;D.appendChild(C.createTextNode(this.Label));D=r.insertCell(-1);if (B){D.className='MN_Arrow';var E=D.appendChild(C.createElement('IMG'));E.src=FCK_IMAGES_PATH+'arrow_'+FCKLang.Dir+'.gif';E.width=4;E.height=7;this.SubMenu.Create();this.SubMenu.Panel.OnHide=FCKTools.CreateEventListener(FCKMenuItem_SubMenu_OnHide,this);}};FCKMenuItem.prototype.Activate=function(){this.MainElement.className='MN_Item_Over';if (this.HasSubMenu){this.SubMenu.Show(this.MainElement.offsetWidth+2,-2,this.MainElement);};FCKTools.RunFunction(this.OnActivate,this);};FCKMenuItem.prototype.Deactivate=function(){this.MainElement.className='MN_Item';if (this.HasSubMenu) this.SubMenu.Hide();};function FCKMenuItem_SubMenu_OnClick(A,B){FCKTools.RunFunction(B.OnClick,B,[A]);};function FCKMenuItem_SubMenu_OnHide(A){A.Deactivate();};function FCKMenuItem_OnClick(A,B){if (B.HasSubMenu) B.Activate();else{B.Deactivate();FCKTools.RunFunction(B.OnClick,B,[B]);}};function FCKMenuItem_OnMouseOver(A,B){B.Activate();};function FCKMenuItem_OnMouseOut(A,B){B.Deactivate();};function FCKMenuItem_Cleanup(){this.MainElement=null;}; +var FCKMenuBlock=function(){this._Items=[];};FCKMenuBlock.prototype.Count=function(){return this._Items.length;};FCKMenuBlock.prototype.AddItem=function(A,B,C,D,E){var F=new FCKMenuItem(this,A,B,C,D,E);F.OnClick=FCKTools.CreateEventListener(FCKMenuBlock_Item_OnClick,this);F.OnActivate=FCKTools.CreateEventListener(FCKMenuBlock_Item_OnActivate,this);this._Items.push(F);return F;};FCKMenuBlock.prototype.AddSeparator=function(){this._Items.push(new FCKMenuSeparator());};FCKMenuBlock.prototype.RemoveAllItems=function(){this._Items=[];var A=this._ItemsTable;if (A){while (A.rows.length>0) A.deleteRow(0);}};FCKMenuBlock.prototype.Create=function(A){if (!this._ItemsTable){if (FCK.IECleanup) FCK.IECleanup.AddItem(this,FCKMenuBlock_Cleanup);this._Window=FCKTools.GetElementWindow(A);var B=FCKTools.GetElementDocument(A);var C=A.appendChild(B.createElement('table'));C.cellPadding=0;C.cellSpacing=0;FCKTools.DisableSelection(C);var D=C.insertRow(-1).insertCell(-1);D.className='MN_Menu';var E=this._ItemsTable=D.appendChild(B.createElement('table'));E.cellPadding=0;E.cellSpacing=0;};for (var i=0;i0&&F.href.length==0);if (G) return;menu.AddSeparator();menu.AddItem('VisitLink',FCKLang.VisitLink);menu.AddSeparator();if (E) menu.AddItem('Link',FCKLang.EditLink,34);menu.AddItem('Unlink',FCKLang.RemoveLink,35);}}};case 'Image':return {AddItems:function(menu,tag,tagName){if (tagName=='IMG'&&!tag.getAttribute('_fckfakelement')){menu.AddSeparator();menu.AddItem('Image',FCKLang.ImageProperties,37);}}};case 'Anchor':return {AddItems:function(menu,tag,tagName){var F=FCKSelection.MoveToAncestorNode('A');var G=(F&&F.name.length>0);if (G||(tagName=='IMG'&&tag.getAttribute('_fckanchor'))){menu.AddSeparator();menu.AddItem('Anchor',FCKLang.AnchorProp,36);menu.AddItem('AnchorDelete',FCKLang.AnchorDelete);}}};case 'Flash':return {AddItems:function(menu,tag,tagName){if (tagName=='IMG'&&tag.getAttribute('_fckflash')){menu.AddSeparator();menu.AddItem('Flash',FCKLang.FlashProperties,38);}}};case 'Form':return {AddItems:function(menu,tag,tagName){if (FCKSelection.HasAncestorNode('FORM')){menu.AddSeparator();menu.AddItem('Form',FCKLang.FormProp,48);}}};case 'Checkbox':return {AddItems:function(menu,tag,tagName){if (tagName=='INPUT'&&tag.type=='checkbox'){menu.AddSeparator();menu.AddItem('Checkbox',FCKLang.CheckboxProp,49);}}};case 'Radio':return {AddItems:function(menu,tag,tagName){if (tagName=='INPUT'&&tag.type=='radio'){menu.AddSeparator();menu.AddItem('Radio',FCKLang.RadioButtonProp,50);}}};case 'TextField':return {AddItems:function(menu,tag,tagName){if (tagName=='INPUT'&&(tag.type=='text'||tag.type=='password')){menu.AddSeparator();menu.AddItem('TextField',FCKLang.TextFieldProp,51);}}};case 'HiddenField':return {AddItems:function(menu,tag,tagName){if (tagName=='IMG'&&tag.getAttribute('_fckinputhidden')){menu.AddSeparator();menu.AddItem('HiddenField',FCKLang.HiddenFieldProp,56);}}};case 'ImageButton':return {AddItems:function(menu,tag,tagName){if (tagName=='INPUT'&&tag.type=='image'){menu.AddSeparator();menu.AddItem('ImageButton',FCKLang.ImageButtonProp,55);}}};case 'Button':return {AddItems:function(menu,tag,tagName){if (tagName=='INPUT'&&(tag.type=='button'||tag.type=='submit'||tag.type=='reset')){menu.AddSeparator();menu.AddItem('Button',FCKLang.ButtonProp,54);}}};case 'Select':return {AddItems:function(menu,tag,tagName){if (tagName=='SELECT'){menu.AddSeparator();menu.AddItem('Select',FCKLang.SelectionFieldProp,53);}}};case 'Textarea':return {AddItems:function(menu,tag,tagName){if (tagName=='TEXTAREA'){menu.AddSeparator();menu.AddItem('Textarea',FCKLang.TextareaProp,52);}}};case 'BulletedList':return {AddItems:function(menu,tag,tagName){if (FCKSelection.HasAncestorNode('UL')){menu.AddSeparator();menu.AddItem('BulletedList',FCKLang.BulletedListProp,27);}}};case 'NumberedList':return {AddItems:function(menu,tag,tagName){if (FCKSelection.HasAncestorNode('OL')){menu.AddSeparator();menu.AddItem('NumberedList',FCKLang.NumberedListProp,26);}}};case 'DivContainer':return {AddItems:function(menu,tag,tagName){var J=FCKDomTools.GetSelectedDivContainers();if (J.length>0){menu.AddSeparator();menu.AddItem('EditDiv',FCKLang.EditDiv,75);menu.AddItem('DeleteDiv',FCKLang.DeleteDiv,76);}}};};return null;};function FCK_ContextMenu_OnBeforeOpen(){FCK.Events.FireEvent('OnSelectionChange');var A,sTagName;if ((A=FCKSelection.GetSelectedElement())) sTagName=A.tagName;var B=FCK.ContextMenu._InnerContextMenu;B.RemoveAllItems();var C=FCK.ContextMenu.Listeners;for (var i=0;i0){D=A.substr(0,B.index);this._sourceHtml=A.substr(B.index);}else{C=true;D=B[0];this._sourceHtml=A.substr(B[0].length);}}else{D=A;this._sourceHtml=null;};return { 'isTag':C,'value':D };},Each:function(A){var B;while ((B=this.Next())) A(B.isTag,B.value);}};var FCKHtmlIterator=function(A){this._sourceHtml=A;};FCKHtmlIterator.prototype={Next:function(){var A=this._sourceHtml;if (A==null) return null;var B=FCKRegexLib.HtmlTag.exec(A);var C=false;var D="";if (B){if (B.index>0){D=A.substr(0,B.index);this._sourceHtml=A.substr(B.index);}else{C=true;D=B[0];this._sourceHtml=A.substr(B[0].length);}}else{D=A;this._sourceHtml=null;};return { 'isTag':C,'value':D };},Each:function(A){var B;while ((B=this.Next())) A(B.isTag,B.value);}}; +var FCKPlugin=function(A,B,C){this.Name=A;this.BasePath=C?C:FCKConfig.PluginsPath;this.Path=this.BasePath+A+'/';if (!B||B.length==0) this.AvailableLangs=[];else this.AvailableLangs=B.split(',');};FCKPlugin.prototype.Load=function(){if (this.AvailableLangs.length>0){var A;if (this.AvailableLangs.IndexOf(FCKLanguageManager.ActiveLanguage.Code)>=0) A=FCKLanguageManager.ActiveLanguage.Code;else A=this.AvailableLangs[0];LoadScript(this.Path+'lang/'+A+'.js');};LoadScript(this.Path+'fckplugin.js');}; +var FCKPlugins=FCK.Plugins={};FCKPlugins.ItemsCount=0;FCKPlugins.Items={};FCKPlugins.Load=function(){var A=FCKPlugins.Items;for (var i=0;i", +DlgInfoTab : "Info", +DlgAlertUrl : "Please insert the URL", + +// General Dialogs Labels +DlgGenNotSet : "", +DlgGenId : "Id", +DlgGenLangDir : "Language Direction", +DlgGenLangDirLtr : "Left to Right (LTR)", +DlgGenLangDirRtl : "Right to Left (RTL)", +DlgGenLangCode : "Language Code", +DlgGenAccessKey : "Access Key", +DlgGenName : "Name", +DlgGenTabIndex : "Tab Index", +DlgGenLongDescr : "Long Description URL", +DlgGenClass : "Stylesheet Classes", +DlgGenTitle : "Advisory Title", +DlgGenContType : "Advisory Content Type", +DlgGenLinkCharset : "Linked Resource Charset", +DlgGenStyle : "Style", + +// Image Dialog +DlgImgTitle : "Image Properties", +DlgImgInfoTab : "Image Info", +DlgImgBtnUpload : "Send it to the Server", +DlgImgURL : "URL", +DlgImgUpload : "Upload", +DlgImgAlt : "Alternative Text", +DlgImgWidth : "Width", +DlgImgHeight : "Height", +DlgImgLockRatio : "Lock Ratio", +DlgBtnResetSize : "Reset Size", +DlgImgBorder : "Border", +DlgImgHSpace : "HSpace", +DlgImgVSpace : "VSpace", +DlgImgAlign : "Align", +DlgImgAlignLeft : "Left", +DlgImgAlignAbsBottom: "Abs Bottom", +DlgImgAlignAbsMiddle: "Abs Middle", +DlgImgAlignBaseline : "Baseline", +DlgImgAlignBottom : "Bottom", +DlgImgAlignMiddle : "Middle", +DlgImgAlignRight : "Right", +DlgImgAlignTextTop : "Text Top", +DlgImgAlignTop : "Top", +DlgImgPreview : "Preview", +DlgImgAlertUrl : "Please type the image URL", +DlgImgLinkTab : "Link", + +// Flash Dialog +DlgFlashTitle : "Flash Properties", +DlgFlashChkPlay : "Auto Play", +DlgFlashChkLoop : "Loop", +DlgFlashChkMenu : "Enable Flash Menu", +DlgFlashScale : "Scale", +DlgFlashScaleAll : "Show all", +DlgFlashScaleNoBorder : "No Border", +DlgFlashScaleFit : "Exact Fit", + +// Link Dialog +DlgLnkWindowTitle : "Link", +DlgLnkInfoTab : "Link Info", +DlgLnkTargetTab : "Target", + +DlgLnkType : "Link Type", +DlgLnkTypeURL : "URL", +DlgLnkTypeAnchor : "Link to anchor in the text", +DlgLnkTypeEMail : "E-Mail", +DlgLnkProto : "Protocol", +DlgLnkProtoOther : "", +DlgLnkURL : "URL", +DlgLnkAnchorSel : "Select an Anchor", +DlgLnkAnchorByName : "By Anchor Name", +DlgLnkAnchorById : "By Element Id", +DlgLnkNoAnchors : "(No anchors available in the document)", +DlgLnkEMail : "E-Mail Address", +DlgLnkEMailSubject : "Message Subject", +DlgLnkEMailBody : "Message Body", +DlgLnkUpload : "Upload", +DlgLnkBtnUpload : "Send it to the Server", + +DlgLnkTarget : "Target", +DlgLnkTargetFrame : "", +DlgLnkTargetPopup : "", +DlgLnkTargetBlank : "New Window (_blank)", +DlgLnkTargetParent : "Parent Window (_parent)", +DlgLnkTargetSelf : "Same Window (_self)", +DlgLnkTargetTop : "Topmost Window (_top)", +DlgLnkTargetFrameName : "Target Frame Name", +DlgLnkPopWinName : "Popup Window Name", +DlgLnkPopWinFeat : "Popup Window Features", +DlgLnkPopResize : "Resizable", +DlgLnkPopLocation : "Location Bar", +DlgLnkPopMenu : "Menu Bar", +DlgLnkPopScroll : "Scroll Bars", +DlgLnkPopStatus : "Status Bar", +DlgLnkPopToolbar : "Toolbar", +DlgLnkPopFullScrn : "Full Screen (IE)", +DlgLnkPopDependent : "Dependent (Netscape)", +DlgLnkPopWidth : "Width", +DlgLnkPopHeight : "Height", +DlgLnkPopLeft : "Left Position", +DlgLnkPopTop : "Top Position", + +DlnLnkMsgNoUrl : "Please type the link URL", +DlnLnkMsgNoEMail : "Please type the e-mail address", +DlnLnkMsgNoAnchor : "Please select an anchor", +DlnLnkMsgInvPopName : "The popup name must begin with an alphabetic character and must not contain spaces", + +// Color Dialog +DlgColorTitle : "Select Color", +DlgColorBtnClear : "Clear", +DlgColorHighlight : "Highlight", +DlgColorSelected : "Selected", + +// Smiley Dialog +DlgSmileyTitle : "Insert a Smiley", + +// Special Character Dialog +DlgSpecialCharTitle : "Select Special Character", + +// Table Dialog +DlgTableTitle : "Table Properties", +DlgTableRows : "Rows", +DlgTableColumns : "Columns", +DlgTableBorder : "Border size", +DlgTableAlign : "Alignment", +DlgTableAlignNotSet : "", +DlgTableAlignLeft : "Left", +DlgTableAlignCenter : "Center", +DlgTableAlignRight : "Right", +DlgTableWidth : "Width", +DlgTableWidthPx : "pixels", +DlgTableWidthPc : "percent", +DlgTableHeight : "Height", +DlgTableCellSpace : "Cell spacing", +DlgTableCellPad : "Cell padding", +DlgTableCaption : "Caption", +DlgTableSummary : "Summary", + +// Table Cell Dialog +DlgCellTitle : "Cell Properties", +DlgCellWidth : "Width", +DlgCellWidthPx : "pixels", +DlgCellWidthPc : "percent", +DlgCellHeight : "Height", +DlgCellWordWrap : "Word Wrap", +DlgCellWordWrapNotSet : "", +DlgCellWordWrapYes : "Yes", +DlgCellWordWrapNo : "No", +DlgCellHorAlign : "Horizontal Alignment", +DlgCellHorAlignNotSet : "", +DlgCellHorAlignLeft : "Left", +DlgCellHorAlignCenter : "Center", +DlgCellHorAlignRight: "Right", +DlgCellVerAlign : "Vertical Alignment", +DlgCellVerAlignNotSet : "", +DlgCellVerAlignTop : "Top", +DlgCellVerAlignMiddle : "Middle", +DlgCellVerAlignBottom : "Bottom", +DlgCellVerAlignBaseline : "Baseline", +DlgCellRowSpan : "Rows Span", +DlgCellCollSpan : "Columns Span", +DlgCellBackColor : "Background Color", +DlgCellBorderColor : "Border Color", +DlgCellBtnSelect : "Select...", + +// Find and Replace Dialog +DlgFindAndReplaceTitle : "Find and Replace", + +// Find Dialog +DlgFindTitle : "Find", +DlgFindFindBtn : "Find", +DlgFindNotFoundMsg : "The specified text was not found.", + +// Replace Dialog +DlgReplaceTitle : "Replace", +DlgReplaceFindLbl : "Find what:", +DlgReplaceReplaceLbl : "Replace with:", +DlgReplaceCaseChk : "Match case", +DlgReplaceReplaceBtn : "Replace", +DlgReplaceReplAllBtn : "Replace All", +DlgReplaceWordChk : "Match whole word", + +// Paste Operations / Dialog +PasteErrorCut : "Your browser security settings don't permit the editor to automatically execute cutting operations. Please use the keyboard for that (Ctrl+X).", +PasteErrorCopy : "Your browser security settings don't permit the editor to automatically execute copying operations. Please use the keyboard for that (Ctrl+C).", + +PasteAsText : "Paste as Plain Text", +PasteFromWord : "Paste from Word", + +DlgPasteMsg2 : "Please paste inside the following box using the keyboard (Ctrl+V) and hit OK.", +DlgPasteSec : "Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.", +DlgPasteIgnoreFont : "Ignore Font Face definitions", +DlgPasteRemoveStyles : "Remove Styles definitions", + +// Color Picker +ColorAutomatic : "Automatic", +ColorMoreColors : "More Colors...", + +// Document Properties +DocProps : "Document Properties", + +// Anchor Dialog +DlgAnchorTitle : "Anchor Properties", +DlgAnchorName : "Anchor Name", +DlgAnchorErrorName : "Please type the anchor name", + +// Speller Pages Dialog +DlgSpellNotInDic : "Not in dictionary", +DlgSpellChangeTo : "Change to", +DlgSpellBtnIgnore : "Ignore", +DlgSpellBtnIgnoreAll : "Ignore All", +DlgSpellBtnReplace : "Replace", +DlgSpellBtnReplaceAll : "Replace All", +DlgSpellBtnUndo : "Undo", +DlgSpellNoSuggestions : "- No suggestions -", +DlgSpellProgress : "Spell check in progress...", +DlgSpellNoMispell : "Spell check complete: No misspellings found", +DlgSpellNoChanges : "Spell check complete: No words changed", +DlgSpellOneChange : "Spell check complete: One word changed", +DlgSpellManyChanges : "Spell check complete: %1 words changed", + +IeSpellDownload : "Spell checker not installed. Do you want to download it now?", + +// Button Dialog +DlgButtonText : "Text (Value)", +DlgButtonType : "Type", +DlgButtonTypeBtn : "Button", +DlgButtonTypeSbm : "Submit", +DlgButtonTypeRst : "Reset", + +// Checkbox and Radio Button Dialogs +DlgCheckboxName : "Name", +DlgCheckboxValue : "Value", +DlgCheckboxSelected : "Selected", + +// Form Dialog +DlgFormName : "Name", +DlgFormAction : "Action", +DlgFormMethod : "Method", + +// Select Field Dialog +DlgSelectName : "Name", +DlgSelectValue : "Value", +DlgSelectSize : "Size", +DlgSelectLines : "lines", +DlgSelectChkMulti : "Allow multiple selections", +DlgSelectOpAvail : "Available Options", +DlgSelectOpText : "Text", +DlgSelectOpValue : "Value", +DlgSelectBtnAdd : "Add", +DlgSelectBtnModify : "Modify", +DlgSelectBtnUp : "Up", +DlgSelectBtnDown : "Down", +DlgSelectBtnSetValue : "Set as selected value", +DlgSelectBtnDelete : "Delete", + +// Textarea Dialog +DlgTextareaName : "Name", +DlgTextareaCols : "Columns", +DlgTextareaRows : "Rows", + +// Text Field Dialog +DlgTextName : "Name", +DlgTextValue : "Value", +DlgTextCharWidth : "Character Width", +DlgTextMaxChars : "Maximum Characters", +DlgTextType : "Type", +DlgTextTypeText : "Text", +DlgTextTypePass : "Password", + +// Hidden Field Dialog +DlgHiddenName : "Name", +DlgHiddenValue : "Value", + +// Bulleted List Dialog +BulletedListProp : "Bulleted List Properties", +NumberedListProp : "Numbered List Properties", +DlgLstStart : "Start", +DlgLstType : "Type", +DlgLstTypeCircle : "Circle", +DlgLstTypeDisc : "Disc", +DlgLstTypeSquare : "Square", +DlgLstTypeNumbers : "Numbers (1, 2, 3)", +DlgLstTypeLCase : "Lowercase Letters (a, b, c)", +DlgLstTypeUCase : "Uppercase Letters (A, B, C)", +DlgLstTypeSRoman : "Small Roman Numerals (i, ii, iii)", +DlgLstTypeLRoman : "Large Roman Numerals (I, II, III)", + +// Document Properties Dialog +DlgDocGeneralTab : "General", +DlgDocBackTab : "Background", +DlgDocColorsTab : "Colors and Margins", +DlgDocMetaTab : "Meta Data", + +DlgDocPageTitle : "Page Title", +DlgDocLangDir : "Language Direction", +DlgDocLangDirLTR : "Left to Right (LTR)", +DlgDocLangDirRTL : "Right to Left (RTL)", +DlgDocLangCode : "Language Code", +DlgDocCharSet : "Character Set Encoding", +DlgDocCharSetCE : "Central European", +DlgDocCharSetCT : "Chinese Traditional (Big5)", +DlgDocCharSetCR : "Cyrillic", +DlgDocCharSetGR : "Greek", +DlgDocCharSetJP : "Japanese", +DlgDocCharSetKR : "Korean", +DlgDocCharSetTR : "Turkish", +DlgDocCharSetUN : "Unicode (UTF-8)", +DlgDocCharSetWE : "Western European", +DlgDocCharSetOther : "Other Character Set Encoding", + +DlgDocDocType : "Document Type Heading", +DlgDocDocTypeOther : "Other Document Type Heading", +DlgDocIncXHTML : "Include XHTML Declarations", +DlgDocBgColor : "Background Color", +DlgDocBgImage : "Background Image URL", +DlgDocBgNoScroll : "Nonscrolling Background", +DlgDocCText : "Text", +DlgDocCLink : "Link", +DlgDocCVisited : "Visited Link", +DlgDocCActive : "Active Link", +DlgDocMargins : "Page Margins", +DlgDocMaTop : "Top", +DlgDocMaLeft : "Left", +DlgDocMaRight : "Right", +DlgDocMaBottom : "Bottom", +DlgDocMeIndex : "Document Indexing Keywords (comma separated)", +DlgDocMeDescr : "Document Description", +DlgDocMeAuthor : "Author", +DlgDocMeCopy : "Copyright", +DlgDocPreview : "Preview", + +// Templates Dialog +Templates : "Templates", +DlgTemplatesTitle : "Content Templates", +DlgTemplatesSelMsg : "Please select the template to open in the editor
(the actual contents will be lost):", +DlgTemplatesLoading : "Loading templates list. Please wait...", +DlgTemplatesNoTpl : "(No templates defined)", +DlgTemplatesReplace : "Replace actual contents", + +// About Dialog +DlgAboutAboutTab : "About", +DlgAboutBrowserInfoTab : "Browser Info", +DlgAboutLicenseTab : "License", +DlgAboutVersion : "version", +DlgAboutInfo : "For further information go to", + +// Div Dialog +DlgDivGeneralTab : "General", +DlgDivAdvancedTab : "Advanced", +DlgDivStyle : "Style", +DlgDivInlineStyle : "Inline Style" +}; diff --git a/includes/fckeditor/editor/lang/zh-cn.js b/includes/fckeditor/editor/lang/zh-cn.js new file mode 100644 index 0000000..dc377fd --- /dev/null +++ b/includes/fckeditor/editor/lang/zh-cn.js @@ -0,0 +1,527 @@ +/* + * FCKeditor - The text editor for Internet - http://www.fckeditor.net + * Copyright (C) 2003-2008 Frederico Caldeira Knabben + * + * == BEGIN LICENSE == + * + * Licensed under the terms of any of the following licenses at your + * choice: + * + * - GNU General Public License Version 2 or later (the "GPL") + * http://www.gnu.org/licenses/gpl.html + * + * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") + * http://www.gnu.org/licenses/lgpl.html + * + * - Mozilla Public License Version 1.1 or later (the "MPL") + * http://www.mozilla.org/MPL/MPL-1.1.html + * + * == END LICENSE == + * + * Chinese Simplified language file. + */ + +var FCKLang = +{ +// Language direction : "ltr" (left to right) or "rtl" (right to left). +Dir : "ltr", + +ToolbarCollapse : "折叠工具栏", +ToolbarExpand : "展开工具栏", + +// Toolbar Items and Context Menu +Save : "保存", +NewPage : "新建", +Preview : "预览", +Cut : "剪切", +Copy : "复制", +Paste : "粘贴", +PasteText : "粘贴为无格式文本", +PasteWord : "从 MS Word 粘贴", +Print : "打印", +SelectAll : "全选", +RemoveFormat : "清除格式", +InsertLinkLbl : "超链接", +InsertLink : "插入/编辑超链接", +RemoveLink : "取消超链接", +VisitLink : "打开超链接", +Anchor : "插入/编辑锚点链接", +AnchorDelete : "清除锚点链接", +InsertImageLbl : "图象", +InsertImage : "插入/编辑图象", +InsertFlashLbl : "Flash", +InsertFlash : "插入/编辑 Flash", +UpFileBtn : "上传文件", +InsertTableLbl : "表格", +InsertTable : "插入/编辑表格", +InsertLineLbl : "水平线", +InsertLine : "插入水平线", +InsertSpecialCharLbl: "特殊符号", +InsertSpecialChar : "插入特殊符号", +InsertSmileyLbl : "表情符", +InsertSmiley : "插入表情图标", +About : "关于 FCKeditor", +Bold : "加粗", +Italic : "倾斜", +Underline : "下划线", +StrikeThrough : "删除线", +Subscript : "下标", +Superscript : "上标", +LeftJustify : "左对齐", +CenterJustify : "居中对齐", +RightJustify : "右对齐", +BlockJustify : "两端对齐", +DecreaseIndent : "减少缩进量", +IncreaseIndent : "增加缩进量", +Blockquote : "块引用", +CreateDiv : "新增 Div 标籤", +EditDiv : "更改 Div 标籤", +DeleteDiv : "删除 Div 标籤", +Undo : "撤消", +Redo : "重做", +NumberedListLbl : "编号列表", +NumberedList : "插入/删除编号列表", +BulletedListLbl : "项目列表", +BulletedList : "插入/删除项目列表", +ShowTableBorders : "显示表格边框", +ShowDetails : "显示详细资料", +Style : "样式", +FontFormat : "格式", +Font : "字体", +FontSize : "大小", +TextColor : "文本颜色", +BGColor : "背景颜色", +Source : "源代码", +Find : "查找", +Replace : "替换", +SpellCheck : "拼写检查", +UniversalKeyboard : "软键盘", +PageBreakLbl : "分页符", +PageBreak : "插入分页符", + +Form : "表单", +Checkbox : "复选框", +RadioButton : "单选按钮", +TextField : "单行文本", +Textarea : "多行文本", +HiddenField : "隐藏域", +Button : "按钮", +SelectionField : "列表/菜单", +ImageButton : "图像域", + +FitWindow : "全屏编辑", +ShowBlocks : "显示区块", + +// Context Menu +EditLink : "编辑超链接", +CellCM : "单元格", +RowCM : "行", +ColumnCM : "列", +InsertRowAfter : "下插入行", +InsertRowBefore : "上插入行", +DeleteRows : "删除行", +InsertColumnAfter : "右插入列", +InsertColumnBefore : "左插入列", +DeleteColumns : "删除列", +InsertCellAfter : "右插入单元格", +InsertCellBefore : "左插入单元格", +DeleteCells : "删除单元格", +MergeCells : "合并单元格", +MergeRight : "右合并单元格", +MergeDown : "下合并单元格", +HorizontalSplitCell : "橫拆分单元格", +VerticalSplitCell : "縱拆分单元格", +TableDelete : "删除表格", +CellProperties : "单元格属性", +TableProperties : "表格属性", +ImageProperties : "图象属性", +FlashProperties : "Flash 属性", + +AnchorProp : "锚点链接属性", +ButtonProp : "按钮属性", +CheckboxProp : "复选框属性", +HiddenFieldProp : "隐藏域属性", +RadioButtonProp : "单选按钮属性", +ImageButtonProp : "图像域属性", +TextFieldProp : "单行文本属性", +SelectionFieldProp : "菜单/列表属性", +TextareaProp : "多行文本属性", +FormProp : "表单属性", + +FontFormats : "普通;已编排格式;地址;标题 1;标题 2;标题 3;标题 4;标题 5;标题 6;段落(DIV)", + +// Alerts and Messages +ProcessingXHTML : "正在处理 XHTML,请稍等...", +Done : "完成", +PasteWordConfirm : "您要粘贴的内容好像是来自 MS Word,是否要清除 MS Word 格式后再粘贴?", +NotCompatiblePaste : "该命令需要 Internet Explorer 5.5 或更高版本的支持,是否按常规粘贴进行?", +UnknownToolbarItem : "未知工具栏项目 \"%1\"", +UnknownCommand : "未知命令名称 \"%1\"", +NotImplemented : "命令无法执行", +UnknownToolbarSet : "工具栏设置 \"%1\" 不存在", +NoActiveX : "浏览器安全设置限制了本编辑器的某些功能。您必须启用安全设置中的“运行 ActiveX 控件和插件”,否则将出现某些错误并缺少功能。", +BrowseServerBlocked : "无法打开资源浏览器,请确认是否启用了禁止弹出窗口。", +DialogBlocked : "无法打开对话框窗口,请确认是否启用了禁止弹出窗口或网页对话框(IE)。", +VisitLinkBlocked : "无法打开新窗口,请确认是否启用了禁止弹出窗口或网页对话框(IE)。", + +// Dialogs +DlgBtnOK : "确定", +DlgBtnCancel : "取消", +DlgBtnClose : "关闭", +DlgBtnBrowseServer : "浏览服务器", +DlgAdvancedTag : "高级", +DlgOpOther : "<其它>", +DlgInfoTab : "信息", +DlgAlertUrl : "请插入 URL", + +// General Dialogs Labels +DlgGenNotSet : "<没有设置>", +DlgGenId : "ID", +DlgGenLangDir : "语言方向", +DlgGenLangDirLtr : "从左到右 (LTR)", +DlgGenLangDirRtl : "从右到左 (RTL)", +DlgGenLangCode : "语言代码", +DlgGenAccessKey : "访问键", +DlgGenName : "名称", +DlgGenTabIndex : "Tab 键次序", +DlgGenLongDescr : "详细说明地址", +DlgGenClass : "样式类名称", +DlgGenTitle : "标题", +DlgGenContType : "内容类型", +DlgGenLinkCharset : "字符编码", +DlgGenStyle : "行内样式", + +// Image Dialog +DlgImgTitle : "图象属性", +DlgImgInfoTab : "图象", +DlgImgBtnUpload : "发送到服务器上", +DlgImgURL : "源文件", +DlgImgUpload : "上传", +DlgImgAlt : "替换文本", +DlgImgWidth : "宽度", +DlgImgHeight : "高度", +DlgImgLockRatio : "锁定比例", +DlgBtnResetSize : "恢复尺寸", +DlgImgBorder : "边框大小", +DlgImgHSpace : "水平间距", +DlgImgVSpace : "垂直间距", +DlgImgAlign : "对齐方式", +DlgImgAlignLeft : "左对齐", +DlgImgAlignAbsBottom: "绝对底边", +DlgImgAlignAbsMiddle: "绝对居中", +DlgImgAlignBaseline : "基线", +DlgImgAlignBottom : "底边", +DlgImgAlignMiddle : "居中", +DlgImgAlignRight : "右对齐", +DlgImgAlignTextTop : "文本上方", +DlgImgAlignTop : "顶端", +DlgImgPreview : "预览", +DlgImgAlertUrl : "请输入图象地址", +DlgImgLinkTab : "链接", + +// Flash Dialog +DlgFlashTitle : "Flash 属性", +DlgFlashChkPlay : "自动播放", +DlgFlashChkLoop : "循环", +DlgFlashChkMenu : "启用 Flash 菜单", +DlgFlashScale : "缩放", +DlgFlashScaleAll : "全部显示", +DlgFlashScaleNoBorder : "无边框", +DlgFlashScaleFit : "严格匹配", + +// Link Dialog +DlgLnkWindowTitle : "超链接", +DlgLnkInfoTab : "超链接信息", +DlgLnkTargetTab : "目标", + +DlgLnkType : "超链接类型", +DlgLnkTypeURL : "超链接", +DlgLnkTypeAnchor : "页内锚点链接", +DlgLnkTypeEMail : "电子邮件", +DlgLnkProto : "协议", +DlgLnkProtoOther : "<其它>", +DlgLnkURL : "地址", +DlgLnkAnchorSel : "选择一个锚点", +DlgLnkAnchorByName : "按锚点名称", +DlgLnkAnchorById : "按锚点 ID", +DlgLnkNoAnchors : "(此文档没有可用的锚点)", +DlgLnkEMail : "地址", +DlgLnkEMailSubject : "主题", +DlgLnkEMailBody : "内容", +DlgLnkUpload : "上传", +DlgLnkBtnUpload : "发送到服务器上", + +DlgLnkTarget : "目标", +DlgLnkTargetFrame : "<框架>", +DlgLnkTargetPopup : "<弹出窗口>", +DlgLnkTargetBlank : "新窗口 (_blank)", +DlgLnkTargetParent : "父窗口 (_parent)", +DlgLnkTargetSelf : "本窗口 (_self)", +DlgLnkTargetTop : "整页 (_top)", +DlgLnkTargetFrameName : "目标框架名称", +DlgLnkPopWinName : "弹出窗口名称", +DlgLnkPopWinFeat : "弹出窗口属性", +DlgLnkPopResize : "调整大小", +DlgLnkPopLocation : "地址栏", +DlgLnkPopMenu : "菜单栏", +DlgLnkPopScroll : "滚动条", +DlgLnkPopStatus : "状态栏", +DlgLnkPopToolbar : "工具栏", +DlgLnkPopFullScrn : "全屏 (IE)", +DlgLnkPopDependent : "依附 (NS)", +DlgLnkPopWidth : "宽", +DlgLnkPopHeight : "高", +DlgLnkPopLeft : "左", +DlgLnkPopTop : "右", + +DlnLnkMsgNoUrl : "请输入超链接地址", +DlnLnkMsgNoEMail : "请输入电子邮件地址", +DlnLnkMsgNoAnchor : "请选择一个锚点", +DlnLnkMsgInvPopName : "弹出窗口名称必须以字母开头,并且不能含有空格。", + +// Color Dialog +DlgColorTitle : "选择颜色", +DlgColorBtnClear : "清除", +DlgColorHighlight : "预览", +DlgColorSelected : "选择", + +// Smiley Dialog +DlgSmileyTitle : "插入表情图标", + +// Special Character Dialog +DlgSpecialCharTitle : "选择特殊符号", + +// Table Dialog +DlgTableTitle : "表格属性", +DlgTableRows : "行数", +DlgTableColumns : "列数", +DlgTableBorder : "边框", +DlgTableAlign : "对齐", +DlgTableAlignNotSet : "<没有设置>", +DlgTableAlignLeft : "左对齐", +DlgTableAlignCenter : "居中", +DlgTableAlignRight : "右对齐", +DlgTableWidth : "宽度", +DlgTableWidthPx : "像素", +DlgTableWidthPc : "百分比", +DlgTableHeight : "高度", +DlgTableCellSpace : "间距", +DlgTableCellPad : "边距", +DlgTableCaption : "标题", +DlgTableSummary : "摘要", + +// Table Cell Dialog +DlgCellTitle : "单元格属性", +DlgCellWidth : "宽度", +DlgCellWidthPx : "像素", +DlgCellWidthPc : "百分比", +DlgCellHeight : "高度", +DlgCellWordWrap : "自动换行", +DlgCellWordWrapNotSet : "<没有设置>", +DlgCellWordWrapYes : "是", +DlgCellWordWrapNo : "否", +DlgCellHorAlign : "水平对齐", +DlgCellHorAlignNotSet : "<没有设置>", +DlgCellHorAlignLeft : "左对齐", +DlgCellHorAlignCenter : "居中", +DlgCellHorAlignRight: "右对齐", +DlgCellVerAlign : "垂直对齐", +DlgCellVerAlignNotSet : "<没有设置>", +DlgCellVerAlignTop : "顶端", +DlgCellVerAlignMiddle : "居中", +DlgCellVerAlignBottom : "底部", +DlgCellVerAlignBaseline : "基线", +DlgCellRowSpan : "纵跨行数", +DlgCellCollSpan : "横跨列数", +DlgCellBackColor : "背景颜色", +DlgCellBorderColor : "边框颜色", +DlgCellBtnSelect : "选择...", + +// Find and Replace Dialog +DlgFindAndReplaceTitle : "查找和替换", + +// Find Dialog +DlgFindTitle : "查找", +DlgFindFindBtn : "查找", +DlgFindNotFoundMsg : "指定文本没有找到。", + +// Replace Dialog +DlgReplaceTitle : "替换", +DlgReplaceFindLbl : "查找:", +DlgReplaceReplaceLbl : "替换:", +DlgReplaceCaseChk : "区分大小写", +DlgReplaceReplaceBtn : "替换", +DlgReplaceReplAllBtn : "全部替换", +DlgReplaceWordChk : "全字匹配", + +// Paste Operations / Dialog +PasteErrorCut : "您的浏览器安全设置不允许编辑器自动执行剪切操作,请使用键盘快捷键(Ctrl+X)来完成。", +PasteErrorCopy : "您的浏览器安全设置不允许编辑器自动执行复制操作,请使用键盘快捷键(Ctrl+C)来完成。", + +PasteAsText : "粘贴为无格式文本", +PasteFromWord : "从 MS Word 粘贴", + +DlgPasteMsg2 : "请使用键盘快捷键(Ctrl+V)把内容粘贴到下面的方框里,再按 确定。", +DlgPasteSec : "因为你的浏览器的安全设置原因,本编辑器不能直接访问你的剪贴板内容,你需要在本窗口重新粘贴一次。", +DlgPasteIgnoreFont : "忽略 Font 标签", +DlgPasteRemoveStyles : "清理 CSS 样式", + +// Color Picker +ColorAutomatic : "自动", +ColorMoreColors : "其它颜色...", + +// Document Properties +DocProps : "页面属性", + +// Anchor Dialog +DlgAnchorTitle : "命名锚点", +DlgAnchorName : "锚点名称", +DlgAnchorErrorName : "请输入锚点名称", + +// Speller Pages Dialog +DlgSpellNotInDic : "没有在字典里", +DlgSpellChangeTo : "更改为", +DlgSpellBtnIgnore : "忽略", +DlgSpellBtnIgnoreAll : "全部忽略", +DlgSpellBtnReplace : "替换", +DlgSpellBtnReplaceAll : "全部替换", +DlgSpellBtnUndo : "撤消", +DlgSpellNoSuggestions : "- 没有建议 -", +DlgSpellProgress : "正在进行拼写检查...", +DlgSpellNoMispell : "拼写检查完成:没有发现拼写错误", +DlgSpellNoChanges : "拼写检查完成:没有更改任何单词", +DlgSpellOneChange : "拼写检查完成:更改了一个单词", +DlgSpellManyChanges : "拼写检查完成:更改了 %1 个单词", + +IeSpellDownload : "拼写检查插件还没安装,你是否想现在就下载?", + +// Button Dialog +DlgButtonText : "标签(值)", +DlgButtonType : "类型", +DlgButtonTypeBtn : "按钮", +DlgButtonTypeSbm : "提交", +DlgButtonTypeRst : "重设", + +// Checkbox and Radio Button Dialogs +DlgCheckboxName : "名称", +DlgCheckboxValue : "选定值", +DlgCheckboxSelected : "已勾选", + +// Form Dialog +DlgFormName : "名称", +DlgFormAction : "动作", +DlgFormMethod : "方法", + +// Select Field Dialog +DlgSelectName : "名称", +DlgSelectValue : "选定", +DlgSelectSize : "高度", +DlgSelectLines : "行", +DlgSelectChkMulti : "允许多选", +DlgSelectOpAvail : "列表值", +DlgSelectOpText : "标签", +DlgSelectOpValue : "值", +DlgSelectBtnAdd : "新增", +DlgSelectBtnModify : "修改", +DlgSelectBtnUp : "上移", +DlgSelectBtnDown : "下移", +DlgSelectBtnSetValue : "设为初始化时选定", +DlgSelectBtnDelete : "删除", + +// Textarea Dialog +DlgTextareaName : "名称", +DlgTextareaCols : "字符宽度", +DlgTextareaRows : "行数", + +// Text Field Dialog +DlgTextName : "名称", +DlgTextValue : "初始值", +DlgTextCharWidth : "字符宽度", +DlgTextMaxChars : "最多字符数", +DlgTextType : "类型", +DlgTextTypeText : "文本", +DlgTextTypePass : "密码", + +// Hidden Field Dialog +DlgHiddenName : "名称", +DlgHiddenValue : "初始值", + +// Bulleted List Dialog +BulletedListProp : "项目列表属性", +NumberedListProp : "编号列表属性", +DlgLstStart : "开始序号", +DlgLstType : "列表类型", +DlgLstTypeCircle : "圆圈", +DlgLstTypeDisc : "圆点", +DlgLstTypeSquare : "方块", +DlgLstTypeNumbers : "数字 (1, 2, 3)", +DlgLstTypeLCase : "小写字母 (a, b, c)", +DlgLstTypeUCase : "大写字母 (A, B, C)", +DlgLstTypeSRoman : "小写罗马数字 (i, ii, iii)", +DlgLstTypeLRoman : "大写罗马数字 (I, II, III)", + +// Document Properties Dialog +DlgDocGeneralTab : "常规", +DlgDocBackTab : "背景", +DlgDocColorsTab : "颜色和边距", +DlgDocMetaTab : "Meta 数据", + +DlgDocPageTitle : "页面标题", +DlgDocLangDir : "语言方向", +DlgDocLangDirLTR : "从左到右 (LTR)", +DlgDocLangDirRTL : "从右到左 (RTL)", +DlgDocLangCode : "语言代码", +DlgDocCharSet : "字符编码", +DlgDocCharSetCE : "中欧", +DlgDocCharSetCT : "繁体中文 (Big5)", +DlgDocCharSetCR : "西里尔文", +DlgDocCharSetGR : "希腊文", +DlgDocCharSetJP : "日文", +DlgDocCharSetKR : "韩文", +DlgDocCharSetTR : "土耳其文", +DlgDocCharSetUN : "Unicode (UTF-8)", +DlgDocCharSetWE : "西欧", +DlgDocCharSetOther : "其它字符编码", + +DlgDocDocType : "文档类型", +DlgDocDocTypeOther : "其它文档类型", +DlgDocIncXHTML : "包含 XHTML 声明", +DlgDocBgColor : "背景颜色", +DlgDocBgImage : "背景图像", +DlgDocBgNoScroll : "不滚动背景图像", +DlgDocCText : "文本", +DlgDocCLink : "超链接", +DlgDocCVisited : "已访问的超链接", +DlgDocCActive : "活动超链接", +DlgDocMargins : "页面边距", +DlgDocMaTop : "上", +DlgDocMaLeft : "左", +DlgDocMaRight : "右", +DlgDocMaBottom : "下", +DlgDocMeIndex : "页面索引关键字 (用半角逗号[,]分隔)", +DlgDocMeDescr : "页面说明", +DlgDocMeAuthor : "作者", +DlgDocMeCopy : "版权", +DlgDocPreview : "预览", + +// Templates Dialog +Templates : "模板", +DlgTemplatesTitle : "内容模板", +DlgTemplatesSelMsg : "请选择编辑器内容模板
(当前内容将会被清除替换):", +DlgTemplatesLoading : "正在加载模板列表,请稍等...", +DlgTemplatesNoTpl : "(没有模板)", +DlgTemplatesReplace : "替换当前内容", + +// About Dialog +DlgAboutAboutTab : "关于", +DlgAboutBrowserInfoTab : "浏览器信息", +DlgAboutLicenseTab : "许可证", +DlgAboutVersion : "版本", +DlgAboutInfo : "要获得更多信息请访问 ", + +// Div Dialog +DlgDivGeneralTab : "常规", +DlgDivAdvancedTab : "高级", +DlgDivStyle : "样式", +DlgDivInlineStyle : "CSS 样式" +}; diff --git a/includes/fckeditor/editor/lang/zh.js b/includes/fckeditor/editor/lang/zh.js new file mode 100644 index 0000000..328141e --- /dev/null +++ b/includes/fckeditor/editor/lang/zh.js @@ -0,0 +1,527 @@ +/* + * FCKeditor - The text editor for Internet - http://www.fckeditor.net + * Copyright (C) 2003-2008 Frederico Caldeira Knabben + * + * == BEGIN LICENSE == + * + * Licensed under the terms of any of the following licenses at your + * choice: + * + * - GNU General Public License Version 2 or later (the "GPL") + * http://www.gnu.org/licenses/gpl.html + * + * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") + * http://www.gnu.org/licenses/lgpl.html + * + * - Mozilla Public License Version 1.1 or later (the "MPL") + * http://www.mozilla.org/MPL/MPL-1.1.html + * + * == END LICENSE == + * + * Chinese Traditional language file. + */ + +var FCKLang = +{ +// Language direction : "ltr" (left to right) or "rtl" (right to left). +Dir : "ltr", + +ToolbarCollapse : "隱藏面板", +ToolbarExpand : "顯示面板", + +// Toolbar Items and Context Menu +Save : "儲存", +NewPage : "開新檔案", +Preview : "預覽", +Cut : "剪下", +Copy : "複製", +Paste : "貼上", +PasteText : "貼為純文字格式", +PasteWord : "自 Word 貼上", +Print : "列印", +SelectAll : "全選", +RemoveFormat : "清除格式", +InsertLinkLbl : "超連結", +InsertLink : "插入/編輯超連結", +RemoveLink : "移除超連結", +VisitLink : "開啟超連結", +Anchor : "插入/編輯錨點", +AnchorDelete : "移除錨點", +InsertImageLbl : "影像", +InsertImage : "插入/編輯影像", +InsertFlashLbl : "Flash", +InsertFlash : "插入/編輯 Flash", +UpFileBtn : "上傳文件", +InsertTableLbl : "表格", +InsertTable : "插入/編輯表格", +InsertLineLbl : "水平線", +InsertLine : "插入水平線", +InsertSpecialCharLbl: "特殊符號", +InsertSpecialChar : "插入特殊符號", +InsertSmileyLbl : "表情符號", +InsertSmiley : "插入表情符號", +About : "關於 FCKeditor", +Bold : "粗體", +Italic : "斜體", +Underline : "底線", +StrikeThrough : "刪除線", +Subscript : "下標", +Superscript : "上標", +LeftJustify : "靠左對齊", +CenterJustify : "置中", +RightJustify : "靠右對齊", +BlockJustify : "左右對齊", +DecreaseIndent : "減少縮排", +IncreaseIndent : "增加縮排", +Blockquote : "引用文字", +CreateDiv : "新增 Div 標籤", +EditDiv : "變更 Div 標籤", +DeleteDiv : "移除 Div 標籤", +Undo : "復原", +Redo : "重複", +NumberedListLbl : "編號清單", +NumberedList : "插入/移除編號清單", +BulletedListLbl : "項目清單", +BulletedList : "插入/移除項目清單", +ShowTableBorders : "顯示表格邊框", +ShowDetails : "顯示詳細資料", +Style : "樣式", +FontFormat : "格式", +Font : "字體", +FontSize : "大小", +TextColor : "文字顏色", +BGColor : "背景顏色", +Source : "原始碼", +Find : "尋找", +Replace : "取代", +SpellCheck : "拼字檢查", +UniversalKeyboard : "萬國鍵盤", +PageBreakLbl : "分頁符號", +PageBreak : "插入分頁符號", + +Form : "表單", +Checkbox : "核取方塊", +RadioButton : "選項按鈕", +TextField : "文字方塊", +Textarea : "文字區域", +HiddenField : "隱藏欄位", +Button : "按鈕", +SelectionField : "清單/選單", +ImageButton : "影像按鈕", + +FitWindow : "編輯器最大化", +ShowBlocks : "顯示區塊", + +// Context Menu +EditLink : "編輯超連結", +CellCM : "儲存格", +RowCM : "列", +ColumnCM : "欄", +InsertRowAfter : "向下插入列", +InsertRowBefore : "向上插入列", +DeleteRows : "刪除列", +InsertColumnAfter : "向右插入欄", +InsertColumnBefore : "向左插入欄", +DeleteColumns : "刪除欄", +InsertCellAfter : "向右插入儲存格", +InsertCellBefore : "向左插入儲存格", +DeleteCells : "刪除儲存格", +MergeCells : "合併儲存格", +MergeRight : "向右合併儲存格", +MergeDown : "向下合併儲存格", +HorizontalSplitCell : "橫向分割儲存格", +VerticalSplitCell : "縱向分割儲存格", +TableDelete : "刪除表格", +CellProperties : "儲存格屬性", +TableProperties : "表格屬性", +ImageProperties : "影像屬性", +FlashProperties : "Flash 屬性", + +AnchorProp : "錨點屬性", +ButtonProp : "按鈕屬性", +CheckboxProp : "核取方塊屬性", +HiddenFieldProp : "隱藏欄位屬性", +RadioButtonProp : "選項按鈕屬性", +ImageButtonProp : "影像按鈕屬性", +TextFieldProp : "文字方塊屬性", +SelectionFieldProp : "清單/選單屬性", +TextareaProp : "文字區域屬性", +FormProp : "表單屬性", + +FontFormats : "一般;已格式化;位址;標題 1;標題 2;標題 3;標題 4;標題 5;標題 6;一般 (DIV)", + +// Alerts and Messages +ProcessingXHTML : "處理 XHTML 中,請稍候…", +Done : "完成", +PasteWordConfirm : "您想貼上的文字似乎是自 Word 複製而來,請問您是否要先清除 Word 的格式後再行貼上?", +NotCompatiblePaste : "此指令僅在 Internet Explorer 5.5 或以上的版本有效。請問您是否同意不清除格式即貼上?", +UnknownToolbarItem : "未知工具列項目 \"%1\"", +UnknownCommand : "未知指令名稱 \"%1\"", +NotImplemented : "尚未安裝此指令", +UnknownToolbarSet : "工具列設定 \"%1\" 不存在", +NoActiveX : "瀏覽器的安全性設定限制了本編輯器的某些功能。您必須啟用安全性設定中的「執行ActiveX控制項與外掛程式」項目,否則本編輯器將會出現錯誤並缺少某些功能", +BrowseServerBlocked : "無法開啟資源瀏覽器,請確定所有快顯視窗封鎖程式是否關閉", +DialogBlocked : "無法開啟對話視窗,請確定所有快顯視窗封鎖程式是否關閉", +VisitLinkBlocked : "無法開啟新視窗,請確定所有快顯視窗封鎖程式是否關閉", + +// Dialogs +DlgBtnOK : "確定", +DlgBtnCancel : "取消", +DlgBtnClose : "關閉", +DlgBtnBrowseServer : "瀏覽伺服器端", +DlgAdvancedTag : "進階", +DlgOpOther : "<其他>", +DlgInfoTab : "資訊", +DlgAlertUrl : "請插入 URL", + +// General Dialogs Labels +DlgGenNotSet : "<尚未設定>", +DlgGenId : "ID", +DlgGenLangDir : "語言方向", +DlgGenLangDirLtr : "由左而右 (LTR)", +DlgGenLangDirRtl : "由右而左 (RTL)", +DlgGenLangCode : "語言代碼", +DlgGenAccessKey : "存取鍵", +DlgGenName : "名稱", +DlgGenTabIndex : "定位順序", +DlgGenLongDescr : "詳細 URL", +DlgGenClass : "樣式表類別", +DlgGenTitle : "標題", +DlgGenContType : "內容類型", +DlgGenLinkCharset : "連結資源之編碼", +DlgGenStyle : "樣式", + +// Image Dialog +DlgImgTitle : "影像屬性", +DlgImgInfoTab : "影像資訊", +DlgImgBtnUpload : "上傳至伺服器", +DlgImgURL : "URL", +DlgImgUpload : "上傳", +DlgImgAlt : "替代文字", +DlgImgWidth : "寬度", +DlgImgHeight : "高度", +DlgImgLockRatio : "等比例", +DlgBtnResetSize : "重設為原大小", +DlgImgBorder : "邊框", +DlgImgHSpace : "水平距離", +DlgImgVSpace : "垂直距離", +DlgImgAlign : "對齊", +DlgImgAlignLeft : "靠左對齊", +DlgImgAlignAbsBottom: "絕對下方", +DlgImgAlignAbsMiddle: "絕對中間", +DlgImgAlignBaseline : "基準線", +DlgImgAlignBottom : "靠下對齊", +DlgImgAlignMiddle : "置中對齊", +DlgImgAlignRight : "靠右對齊", +DlgImgAlignTextTop : "文字上方", +DlgImgAlignTop : "靠上對齊", +DlgImgPreview : "預覽", +DlgImgAlertUrl : "請輸入影像 URL", +DlgImgLinkTab : "超連結", + +// Flash Dialog +DlgFlashTitle : "Flash 屬性", +DlgFlashChkPlay : "自動播放", +DlgFlashChkLoop : "重複", +DlgFlashChkMenu : "開啟選單", +DlgFlashScale : "縮放", +DlgFlashScaleAll : "全部顯示", +DlgFlashScaleNoBorder : "無邊框", +DlgFlashScaleFit : "精確符合", + +// Link Dialog +DlgLnkWindowTitle : "超連結", +DlgLnkInfoTab : "超連結資訊", +DlgLnkTargetTab : "目標", + +DlgLnkType : "超連接類型", +DlgLnkTypeURL : "URL", +DlgLnkTypeAnchor : "本頁錨點", +DlgLnkTypeEMail : "電子郵件", +DlgLnkProto : "通訊協定", +DlgLnkProtoOther : "<其他>", +DlgLnkURL : "URL", +DlgLnkAnchorSel : "請選擇錨點", +DlgLnkAnchorByName : "依錨點名稱", +DlgLnkAnchorById : "依元件 ID", +DlgLnkNoAnchors : "(本文件尚無可用之錨點)", +DlgLnkEMail : "電子郵件", +DlgLnkEMailSubject : "郵件主旨", +DlgLnkEMailBody : "郵件內容", +DlgLnkUpload : "上傳", +DlgLnkBtnUpload : "傳送至伺服器", + +DlgLnkTarget : "目標", +DlgLnkTargetFrame : "<框架>", +DlgLnkTargetPopup : "<快顯視窗>", +DlgLnkTargetBlank : "新視窗 (_blank)", +DlgLnkTargetParent : "父視窗 (_parent)", +DlgLnkTargetSelf : "本視窗 (_self)", +DlgLnkTargetTop : "最上層視窗 (_top)", +DlgLnkTargetFrameName : "目標框架名稱", +DlgLnkPopWinName : "快顯視窗名稱", +DlgLnkPopWinFeat : "快顯視窗屬性", +DlgLnkPopResize : "可調整大小", +DlgLnkPopLocation : "網址列", +DlgLnkPopMenu : "選單列", +DlgLnkPopScroll : "捲軸", +DlgLnkPopStatus : "狀態列", +DlgLnkPopToolbar : "工具列", +DlgLnkPopFullScrn : "全螢幕 (IE)", +DlgLnkPopDependent : "從屬 (NS)", +DlgLnkPopWidth : "寬", +DlgLnkPopHeight : "高", +DlgLnkPopLeft : "左", +DlgLnkPopTop : "右", + +DlnLnkMsgNoUrl : "請輸入欲連結的 URL", +DlnLnkMsgNoEMail : "請輸入電子郵件位址", +DlnLnkMsgNoAnchor : "請選擇錨點", +DlnLnkMsgInvPopName : "快顯名稱必須以「英文字母」為開頭,且不得含有空白", + +// Color Dialog +DlgColorTitle : "請選擇顏色", +DlgColorBtnClear : "清除", +DlgColorHighlight : "預覽", +DlgColorSelected : "選擇", + +// Smiley Dialog +DlgSmileyTitle : "插入表情符號", + +// Special Character Dialog +DlgSpecialCharTitle : "請選擇特殊符號", + +// Table Dialog +DlgTableTitle : "表格屬性", +DlgTableRows : "列數", +DlgTableColumns : "欄數", +DlgTableBorder : "邊框", +DlgTableAlign : "對齊", +DlgTableAlignNotSet : "<未設定>", +DlgTableAlignLeft : "靠左對齊", +DlgTableAlignCenter : "置中", +DlgTableAlignRight : "靠右對齊", +DlgTableWidth : "寬度", +DlgTableWidthPx : "像素", +DlgTableWidthPc : "百分比", +DlgTableHeight : "高度", +DlgTableCellSpace : "間距", +DlgTableCellPad : "內距", +DlgTableCaption : "標題", +DlgTableSummary : "摘要", + +// Table Cell Dialog +DlgCellTitle : "儲存格屬性", +DlgCellWidth : "寬度", +DlgCellWidthPx : "像素", +DlgCellWidthPc : "百分比", +DlgCellHeight : "高度", +DlgCellWordWrap : "自動換行", +DlgCellWordWrapNotSet : "<尚未設定>", +DlgCellWordWrapYes : "是", +DlgCellWordWrapNo : "否", +DlgCellHorAlign : "水平對齊", +DlgCellHorAlignNotSet : "<尚未設定>", +DlgCellHorAlignLeft : "靠左對齊", +DlgCellHorAlignCenter : "置中", +DlgCellHorAlignRight: "靠右對齊", +DlgCellVerAlign : "垂直對齊", +DlgCellVerAlignNotSet : "<尚未設定>", +DlgCellVerAlignTop : "靠上對齊", +DlgCellVerAlignMiddle : "置中", +DlgCellVerAlignBottom : "靠下對齊", +DlgCellVerAlignBaseline : "基準線", +DlgCellRowSpan : "合併列數", +DlgCellCollSpan : "合併欄数", +DlgCellBackColor : "背景顏色", +DlgCellBorderColor : "邊框顏色", +DlgCellBtnSelect : "請選擇…", + +// Find and Replace Dialog +DlgFindAndReplaceTitle : "尋找與取代", + +// Find Dialog +DlgFindTitle : "尋找", +DlgFindFindBtn : "尋找", +DlgFindNotFoundMsg : "未找到指定的文字。", + +// Replace Dialog +DlgReplaceTitle : "取代", +DlgReplaceFindLbl : "尋找:", +DlgReplaceReplaceLbl : "取代:", +DlgReplaceCaseChk : "大小寫須相符", +DlgReplaceReplaceBtn : "取代", +DlgReplaceReplAllBtn : "全部取代", +DlgReplaceWordChk : "全字相符", + +// Paste Operations / Dialog +PasteErrorCut : "瀏覽器的安全性設定不允許編輯器自動執行剪下動作。請使用快捷鍵 (Ctrl+X) 剪下。", +PasteErrorCopy : "瀏覽器的安全性設定不允許編輯器自動執行複製動作。請使用快捷鍵 (Ctrl+C) 複製。", + +PasteAsText : "貼為純文字格式", +PasteFromWord : "自 Word 貼上", + +DlgPasteMsg2 : "請使用快捷鍵 (Ctrl+V) 貼到下方區域中並按下 確定", +DlgPasteSec : "因為瀏覽器的安全性設定,本編輯器無法直接存取您的剪貼簿資料,請您自行在本視窗進行貼上動作。", +DlgPasteIgnoreFont : "移除字型設定", +DlgPasteRemoveStyles : "移除樣式設定", + +// Color Picker +ColorAutomatic : "自動", +ColorMoreColors : "更多顏色…", + +// Document Properties +DocProps : "文件屬性", + +// Anchor Dialog +DlgAnchorTitle : "命名錨點", +DlgAnchorName : "錨點名稱", +DlgAnchorErrorName : "請輸入錨點名稱", + +// Speller Pages Dialog +DlgSpellNotInDic : "不在字典中", +DlgSpellChangeTo : "更改為", +DlgSpellBtnIgnore : "忽略", +DlgSpellBtnIgnoreAll : "全部忽略", +DlgSpellBtnReplace : "取代", +DlgSpellBtnReplaceAll : "全部取代", +DlgSpellBtnUndo : "復原", +DlgSpellNoSuggestions : "- 無建議值 -", +DlgSpellProgress : "進行拼字檢查中…", +DlgSpellNoMispell : "拼字檢查完成:未發現拼字錯誤", +DlgSpellNoChanges : "拼字檢查完成:未更改任何單字", +DlgSpellOneChange : "拼字檢查完成:更改了 1 個單字", +DlgSpellManyChanges : "拼字檢查完成:更改了 %1 個單字", + +IeSpellDownload : "尚未安裝拼字檢查元件。您是否想要現在下載?", + +// Button Dialog +DlgButtonText : "顯示文字 (值)", +DlgButtonType : "類型", +DlgButtonTypeBtn : "按鈕 (Button)", +DlgButtonTypeSbm : "送出 (Submit)", +DlgButtonTypeRst : "重設 (Reset)", + +// Checkbox and Radio Button Dialogs +DlgCheckboxName : "名稱", +DlgCheckboxValue : "選取值", +DlgCheckboxSelected : "已選取", + +// Form Dialog +DlgFormName : "名稱", +DlgFormAction : "動作", +DlgFormMethod : "方法", + +// Select Field Dialog +DlgSelectName : "名稱", +DlgSelectValue : "選取值", +DlgSelectSize : "大小", +DlgSelectLines : "行", +DlgSelectChkMulti : "可多選", +DlgSelectOpAvail : "可用選項", +DlgSelectOpText : "顯示文字", +DlgSelectOpValue : "值", +DlgSelectBtnAdd : "新增", +DlgSelectBtnModify : "修改", +DlgSelectBtnUp : "上移", +DlgSelectBtnDown : "下移", +DlgSelectBtnSetValue : "設為預設值", +DlgSelectBtnDelete : "刪除", + +// Textarea Dialog +DlgTextareaName : "名稱", +DlgTextareaCols : "字元寬度", +DlgTextareaRows : "列數", + +// Text Field Dialog +DlgTextName : "名稱", +DlgTextValue : "值", +DlgTextCharWidth : "字元寬度", +DlgTextMaxChars : "最多字元數", +DlgTextType : "類型", +DlgTextTypeText : "文字", +DlgTextTypePass : "密碼", + +// Hidden Field Dialog +DlgHiddenName : "名稱", +DlgHiddenValue : "值", + +// Bulleted List Dialog +BulletedListProp : "項目清單屬性", +NumberedListProp : "編號清單屬性", +DlgLstStart : "起始編號", +DlgLstType : "清單類型", +DlgLstTypeCircle : "圓圈", +DlgLstTypeDisc : "圓點", +DlgLstTypeSquare : "方塊", +DlgLstTypeNumbers : "數字 (1, 2, 3)", +DlgLstTypeLCase : "小寫字母 (a, b, c)", +DlgLstTypeUCase : "大寫字母 (A, B, C)", +DlgLstTypeSRoman : "小寫羅馬數字 (i, ii, iii)", +DlgLstTypeLRoman : "大寫羅馬數字 (I, II, III)", + +// Document Properties Dialog +DlgDocGeneralTab : "一般", +DlgDocBackTab : "背景", +DlgDocColorsTab : "顯色與邊界", +DlgDocMetaTab : "Meta 資料", + +DlgDocPageTitle : "頁面標題", +DlgDocLangDir : "語言方向", +DlgDocLangDirLTR : "由左而右 (LTR)", +DlgDocLangDirRTL : "由右而左 (RTL)", +DlgDocLangCode : "語言代碼", +DlgDocCharSet : "字元編碼", +DlgDocCharSetCE : "中歐語系", +DlgDocCharSetCT : "正體中文 (Big5)", +DlgDocCharSetCR : "斯拉夫文", +DlgDocCharSetGR : "希臘文", +DlgDocCharSetJP : "日文", +DlgDocCharSetKR : "韓文", +DlgDocCharSetTR : "土耳其文", +DlgDocCharSetUN : "Unicode (UTF-8)", +DlgDocCharSetWE : "西歐語系", +DlgDocCharSetOther : "其他字元編碼", + +DlgDocDocType : "文件類型", +DlgDocDocTypeOther : "其他文件類型", +DlgDocIncXHTML : "包含 XHTML 定義", +DlgDocBgColor : "背景顏色", +DlgDocBgImage : "背景影像", +DlgDocBgNoScroll : "浮水印", +DlgDocCText : "文字", +DlgDocCLink : "超連結", +DlgDocCVisited : "已瀏覽過的超連結", +DlgDocCActive : "作用中的超連結", +DlgDocMargins : "頁面邊界", +DlgDocMaTop : "上", +DlgDocMaLeft : "左", +DlgDocMaRight : "右", +DlgDocMaBottom : "下", +DlgDocMeIndex : "文件索引關鍵字 (用半形逗號[,]分隔)", +DlgDocMeDescr : "文件說明", +DlgDocMeAuthor : "作者", +DlgDocMeCopy : "版權所有", +DlgDocPreview : "預覽", + +// Templates Dialog +Templates : "樣版", +DlgTemplatesTitle : "內容樣版", +DlgTemplatesSelMsg : "請選擇欲開啟的樣版
(原有的內容將會被清除):", +DlgTemplatesLoading : "讀取樣版清單中,請稍候…", +DlgTemplatesNoTpl : "(無樣版)", +DlgTemplatesReplace : "取代原有內容", + +// About Dialog +DlgAboutAboutTab : "關於", +DlgAboutBrowserInfoTab : "瀏覽器資訊", +DlgAboutLicenseTab : "許可證", +DlgAboutVersion : "版本", +DlgAboutInfo : "想獲得更多資訊請至 ", + +// Div Dialog +DlgDivGeneralTab : "一般", +DlgDivAdvancedTab : "進階", +DlgDivStyle : "樣式", +DlgDivInlineStyle : "CSS 樣式" +}; diff --git a/includes/fckeditor/editor/skins/default/fck_dialog.css b/includes/fckeditor/editor/skins/default/fck_dialog.css new file mode 100644 index 0000000..90b59e8 --- /dev/null +++ b/includes/fckeditor/editor/skins/default/fck_dialog.css @@ -0,0 +1,402 @@ +/* + * FCKeditor - The text editor for Internet - http://www.fckeditor.net + * Copyright (C) 2003-2008 Frederico Caldeira Knabben + * + * == BEGIN LICENSE == + * + * Licensed under the terms of any of the following licenses at your + * choice: + * + * - GNU General Public License Version 2 or later (the "GPL") + * http://www.gnu.org/licenses/gpl.html + * + * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") + * http://www.gnu.org/licenses/lgpl.html + * + * - Mozilla Public License Version 1.1 or later (the "MPL") + * http://www.mozilla.org/MPL/MPL-1.1.html + * + * == END LICENSE == + * + * Styles used by the dialog boxes. + */ + +html, body +{ + background-color: transparent; + margin: 0px; + padding: 0px; +} + +body +{ + padding: 10px; +} + +body, td, input, select, textarea +{ + font-size: 11px; + font-family: 'Microsoft Sans Serif' , Arial, Helvetica, Verdana; +} + +body, .BackColor +{ + background-color: #f1f1e3; +} + +.PopupBody +{ + height: 100%; + width: 100%; + overflow: hidden; + background-color: transparent; + padding: 0px; +} + +#header +{ + cursor: move; +} + +.PopupTitle +{ + font-weight: bold; + font-size: 14pt; + color: #737357; + background-color: #e3e3c7; + padding: 3px 10px 3px 10px; +} + +.PopupButtons +{ + position: absolute; + right: 0px; + left: 0px; + bottom: 0px; + border-top: #d5d59d 1px solid; + background-color: #e3e3c7; + padding: 7px 10px 7px 10px; +} + +.Button +{ + border: #737357 1px solid; + color: #3b3b1f; + background-color: #c7c78f; +} + +#btnOk +{ + width: 100px; +} + +.DarkBackground +{ + background-color: #eaead1; +} + +.LightBackground +{ + background-color: #ffffbe; +} + +.PopupTitleBorder +{ + border-bottom: #d5d59d 1px solid; +} + +.PopupTabArea +{ + color: #737357; + background-color: #e3e3c7; +} + +.PopupTabEmptyArea +{ + padding-left: 10px; + border-bottom: #d5d59d 1px solid; +} + +.PopupTab, .PopupTabSelected +{ + border-right: #d5d59d 1px solid; + border-top: #d5d59d 1px solid; + border-left: #d5d59d 1px solid; + padding: 3px 5px 3px 5px; + color: #737357; +} + +.PopupTab +{ + margin-top: 1px; + border-bottom: #d5d59d 1px solid; + cursor: pointer; + cursor: hand; +} + +.PopupTabSelected +{ + font-weight: bold; + cursor: default; + padding-top: 4px; + border-bottom: #f1f1e3 1px solid; + background-color: #f1f1e3; +} + +.PopupSelectionBox +{ + border: #ff9933 1px solid !important; + background-color: #fffacd !important; + cursor: pointer; + cursor: hand; +} + +#tdBrowse +{ + vertical-align: bottom; +} + +/** + * Dialog frame related styles. + */ + +.contents +{ + position: absolute; + top: 2px; + left: 16px; + right: 16px; + bottom: 20px; + background-color: #f1f1e3; + overflow: hidden; + z-index: 1; +} + +.tl, .tr, .tc, .bl, .br, .bc +{ + position: absolute; + background-image: url(images/sprites.png); + background-repeat: no-repeat; +} + +* html .tl, * html .tr, * html .tc, * html .bl, * html .br, * html .bc +{ + background-image: url(images/sprites.gif); +} + +.ml, .mr +{ + position: absolute; + background-image: url(images/dialog.sides.png); + background-repeat: repeat-y; +} + +* html .ml, * html .mr +{ + background-image: url(images/dialog.sides.gif); +} + +.rtl .ml, .rtl .mr +{ + position: absolute; + background-image: url(images/dialog.sides.rtl.png); + background-repeat: repeat-y; +} + +* html .rtl .ml, * html .rtl .mr +{ + background-image: url(images/dialog.sides.gif); +} + +.tl +{ + top: 0px; + left: 0px; + width: 16px; + height: 16px; + background-position: -16px -16px; +} + +.rtl .tl +{ + background-position: -16px -397px; +} + +.tr +{ + top: 0px; + right: 0px; + width: 16px; + height: 16px; + background-position: -16px -76px; +} + +.rtl .tr +{ + background-position: -16px -457px; +} + +.tc +{ + top: 0px; + right: 16px; + left: 16px; + height: 16px; + background-position: 0px -136px; + background-repeat: repeat-x; +} + +.ml +{ + top: 16px; + left: 0px; + width: 16px; + bottom: 51px; + background-position: 0px 0px; +} + +.mr +{ + top: 16px; + right: 0px; + width: 16px; + bottom: 51px; + background-position: -16px 0px; +} + +.bl +{ + bottom: 0px; + left: 0px; + width: 30px; + height: 51px; + background-position: -16px -196px; +} + +.rtl .bl +{ + background-position: -16px -517px; +} + +.br +{ + bottom: 0px; + right: 0px; + width: 30px; + height: 51px; + background-position: -16px -263px; +} + +.rtl .br +{ + background-position: -16px -584px; +} + +.bc +{ + bottom: 0px; + right: 30px; + left: 30px; + height: 51px; + background-position: 0px -330px; + background-repeat: repeat-x; +} + +/* For IE6. Do not change it. */ +* html .blocker +{ + position: absolute; + width: 100%; + height: 100%; + z-index: 12; + filter: progid:DXImageTransform.Microsoft.Alpha(opacity=0); +} + +/* The layer used to cover the dialog when opening a child dialog. */ +.cover +{ + position: absolute; + top: 0px; + left: 14px; + right: 14px; + bottom: 18px; + z-index: 11; +} + +#closeButton +{ + position: absolute; + right: 0px; + top: 0px; + margin-top: 5px; + margin-right: 10px; + width: 20px; + height: 20px; + cursor: pointer; + background-image: url(images/sprites.png); + background-repeat: no-repeat; + background-position: -16px -651px; +} + +* html #closeButton +{ + cursor: hand; + background-image: url(images/sprites.gif); +} + +.rtl #closeButton +{ + right: auto; + left: 10px; + margin-right: 0px; +} + +#closeButton:hover +{ + background-position: -16px -687px; +} + +#throbberBlock +{ + z-index: 10; +} + +#throbberBlock div +{ + float: left; + width: 8px; + height: 9px; + margin-left: 2px; + margin-right: 2px; + font-size: 1px; /* IE6 */ +} + +/* + Color Gradient Generator: + http://www.herethere.net/~samson/php/color_gradient/?cbegin=737357&cend=E3E3C7&steps=4 +*/ + +.throbber_1 +{ + background-color: #737357; +} + +.throbber_2 +{ + background-color: #8f8f73; +} + +.throbber_3 +{ + background-color: #abab8f; +} + +.throbber_4 +{ + background-color: #c7c7ab; +} + +.throbber_5 +{ + background-color: #e3e3c7; +} diff --git a/includes/fckeditor/editor/skins/default/fck_dialog_ie6.js b/includes/fckeditor/editor/skins/default/fck_dialog_ie6.js new file mode 100644 index 0000000..2415bc2 --- /dev/null +++ b/includes/fckeditor/editor/skins/default/fck_dialog_ie6.js @@ -0,0 +1,110 @@ +/* + * FCKeditor - The text editor for Internet - http://www.fckeditor.net + * Copyright (C) 2003-2008 Frederico Caldeira Knabben + * + * == BEGIN LICENSE == + * + * Licensed under the terms of any of the following licenses at your + * choice: + * + * - GNU General Public License Version 2 or later (the "GPL") + * http://www.gnu.org/licenses/gpl.html + * + * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") + * http://www.gnu.org/licenses/lgpl.html + * + * - Mozilla Public License Version 1.1 or later (the "MPL") + * http://www.mozilla.org/MPL/MPL-1.1.html + * + * == END LICENSE == + */ + +(function() +{ + // IE6 doens't handle absolute positioning properly (it is always in quirks + // mode). This function fixes the sizes and positions of many elements that + // compose the skin (this is skin specific). + var fixSizes = window.DoResizeFixes = function() + { + var fckDlg = window.document.body ; + + for ( var i = 0 ; i < fckDlg.childNodes.length ; i++ ) + { + var child = fckDlg.childNodes[i] ; + switch ( child.className ) + { + case 'contents' : + child.style.width = Math.max( 0, fckDlg.offsetWidth - 16 - 16 ) ; // -left -right + child.style.height = Math.max( 0, fckDlg.clientHeight - 20 - 2 ) ; // -bottom -top + break ; + + case 'blocker' : + case 'cover' : + child.style.width = Math.max( 0, fckDlg.offsetWidth - 16 - 16 + 4 ) ; // -left -right + 4 + child.style.height = Math.max( 0, fckDlg.clientHeight - 20 - 2 + 4 ) ; // -bottom -top + 4 + break ; + + case 'tr' : + child.style.left = Math.max( 0, fckDlg.clientWidth - 16 ) ; + break ; + + case 'tc' : + child.style.width = Math.max( 0, fckDlg.clientWidth - 16 - 16 ) ; + break ; + + case 'ml' : + child.style.height = Math.max( 0, fckDlg.clientHeight - 16 - 51 ) ; + break ; + + case 'mr' : + child.style.left = Math.max( 0, fckDlg.clientWidth - 16 ) ; + child.style.height = Math.max( 0, fckDlg.clientHeight - 16 - 51 ) ; + break ; + + case 'bl' : + child.style.top = Math.max( 0, fckDlg.clientHeight - 51 ) ; + break ; + + case 'br' : + child.style.left = Math.max( 0, fckDlg.clientWidth - 30 ) ; + child.style.top = Math.max( 0, fckDlg.clientHeight - 51 ) ; + break ; + + case 'bc' : + child.style.width = Math.max( 0, fckDlg.clientWidth - 30 - 30 ) ; + child.style.top = Math.max( 0, fckDlg.clientHeight - 51 ) ; + break ; + } + } + } + + var closeButtonOver = function() + { + this.style.backgroundPosition = '-16px -687px' ; + } ; + + var closeButtonOut = function() + { + this.style.backgroundPosition = '-16px -651px' ; + } ; + + var fixCloseButton = function() + { + var closeButton = document.getElementById ( 'closeButton' ) ; + + closeButton.onmouseover = closeButtonOver ; + closeButton.onmouseout = closeButtonOut ; + } + + var onLoad = function() + { + fixSizes() ; + fixCloseButton() ; + + window.attachEvent( 'onresize', fixSizes ) ; + window.detachEvent( 'onload', onLoad ) ; + } + + window.attachEvent( 'onload', onLoad ) ; + +})() ; diff --git a/includes/fckeditor/editor/skins/default/fck_editor.css b/includes/fckeditor/editor/skins/default/fck_editor.css new file mode 100644 index 0000000..b6ea79a --- /dev/null +++ b/includes/fckeditor/editor/skins/default/fck_editor.css @@ -0,0 +1,464 @@ +/* + * FCKeditor - The text editor for Internet - http://www.fckeditor.net + * Copyright (C) 2003-2008 Frederico Caldeira Knabben + * + * == BEGIN LICENSE == + * + * Licensed under the terms of any of the following licenses at your + * choice: + * + * - GNU General Public License Version 2 or later (the "GPL") + * http://www.gnu.org/licenses/gpl.html + * + * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") + * http://www.gnu.org/licenses/lgpl.html + * + * - Mozilla Public License Version 1.1 or later (the "MPL") + * http://www.mozilla.org/MPL/MPL-1.1.html + * + * == END LICENSE == + * + * Styles used by the editor IFRAME and Toolbar. + */ + +/* + ### Basic Editor IFRAME Styles. +*/ + +body +{ + padding: 1px; + margin: 0; + background-color: #ffffff; +} + +#xEditingArea +{ + border: #696969 1px solid; +} + +.SourceField +{ + padding: 5px; + margin: 0px; + font-family: Monospace; +} + +/* + Toolbar +*/ + +.TB_ToolbarSet, .TB_Expand, .TB_Collapse +{ + cursor: default; + background-color: #efefde; +} + +.TB_ToolbarSet +{ + border-top: #efefde 1px outset; + border-bottom: #efefde 1px outset; +} + +.TB_ToolbarSet TD +{ + font-size: 11px; + font-family: 'Microsoft Sans Serif' , Tahoma, Arial, Verdana, Sans-Serif; +} + +.TB_Toolbar +{ + height: 24px; + display: inline-table; /* inline = Opera jumping buttons bug */ +} + +.TB_Separator +{ + width: 1px; + height: 16px; + margin: 2px; + background-color: #999966; +} + +.TB_Start +{ + background-image: url(images/toolbar.start.gif); + margin: 2px; + width: 3px; + background-repeat: no-repeat; + height: 16px; +} + +.TB_End +{ + display: none; +} + +.TB_ExpandImg +{ + background-image: url(images/toolbar.expand.gif); + background-repeat: no-repeat; +} + +.TB_CollapseImg +{ + background-image: url(images/toolbar.collapse.gif); + background-repeat: no-repeat; +} + +.TB_SideBorder +{ + background-color: #696969; +} + +.TB_Expand, .TB_Collapse +{ + padding: 2px 2px 2px 2px; + border: #efefde 1px outset; +} + +.TB_Collapse +{ + width: 5px; +} + +.TB_Break +{ + height: 24px; /* IE needs the height to be set, otherwise no break */ +} + +/* + Toolbar Button +*/ + +.TB_Button_On, .TB_Button_Off, .TB_Button_On_Over, .TB_Button_Off_Over, .TB_Button_Disabled +{ + border: #efefde 1px solid; /* This is the default border */ + height: 22px; /* The height is necessary, otherwise IE will not apply the alpha */ +} + +.TB_Button_On +{ + border: #316ac5 1px solid; + background-color: #c1d2ee; +} + +.TB_Button_On_Over, .TB_Button_Off_Over +{ + border: #316ac5 1px solid; + background-color: #dff1ff; +} + +.TB_Button_Off +{ + filter: alpha(opacity=70); /* IE */ + opacity: 0.70; /* Safari, Opera and Mozilla */ +} + +.TB_Button_Disabled +{ + filter: gray() alpha(opacity=30); /* IE */ + opacity: 0.30; /* Safari, Opera and Mozilla */ +} + +.TB_Button_Padding +{ + visibility: hidden; + width: 3px; + height: 22px; +} + +.TB_Button_Image +{ + overflow: hidden; + width: 16px; + height: 16px; + margin: 3px; + background-repeat: no-repeat; +} + +.TB_Button_Image img +{ + position: relative; +} + +.TB_Button_Off .TB_Button_Text +{ + background-color: #efefde; /* Needed because of a bug on Clear Type */ +} + +.TB_ConnectionLine +{ + background-color: #ffffff; + height: 1px; + margin-left: 1px; /* ltr */ + margin-right: 1px; /* rtl */ +} + +.TB_Text +{ + height: 22px; +} + +.TB_Button_Off .TB_Text +{ + background-color: #efefde ; /* Needed because of a bug on ClearType */ +} + +.TB_Button_On_Over .TB_Text +{ + background-color: #dff1ff ; /* Needed because of a bug on ClearType */ +} + +/* + Menu +*/ + +.MN_Menu +{ + border: 1px solid #8f8f73; + padding: 2px; + background-color: #ffffff; + cursor: default; +} + +.MN_Menu, .MN_Menu .MN_Label +{ + font-size: 11px; + font-family: 'Microsoft Sans Serif' , Tahoma, Arial, Verdana, Sans-Serif; +} + +.MN_Item_Padding +{ + visibility: hidden; + width: 3px; + height: 20px; +} + +.MN_Icon +{ + background-color: #e3e3c7; + text-align: center; + height: 20px; +} + +.MN_Label +{ + padding-left: 3px; + padding-right: 3px; +} + +.MN_Separator +{ + height: 3px; +} + +.MN_Separator_Line +{ + border-top: #b9b99d 1px solid; +} + +.MN_Item .MN_Icon IMG +{ + filter: alpha(opacity=70); + opacity: 0.70; +} + +.MN_Item_Over +{ + color: #ffffff; + background-color: #8f8f73; +} + +.MN_Item_Over .MN_Icon +{ + background-color: #737357; +} + +.MN_Item_Disabled IMG +{ + filter: gray() alpha(opacity=30); /* IE */ + opacity: 0.30; /* Safari, Opera and Mozilla */ +} + +.MN_Item_Disabled .MN_Label +{ + color: #b7b7b7; +} + +.MN_Arrow +{ + padding-right: 3px; + padding-left: 3px; +} + +.MN_ConnectionLine +{ + background-color: #ffffff; +} + +.Menu .TB_Button_On, .Menu .TB_Button_On_Over +{ + border: #8f8f73 1px solid; + background-color: #ffffff; +} + +/* + ### Panel Styles +*/ + +.FCK_Panel +{ + border: #8f8f73 1px solid; + padding: 2px; + background-color: #ffffff; +} + +.FCK_Panel, .FCK_Panel TD +{ + font-family: 'Microsoft Sans Serif' , Tahoma, Arial, Verdana, Sans-Serif; + font-size: 11px; +} + +/* + ### Special Combos +*/ + +.SC_Panel +{ + overflow: auto; + white-space: nowrap; + cursor: default; + border: 1px solid #8f8f73; + padding-left: 2px; + padding-right: 2px; +} + +.SC_Panel, .SC_Panel TD +{ + font-size: 11px; + font-family: 'Microsoft Sans Serif' , Tahoma, Arial, Verdana, Sans-Serif; +} + +.SC_Item, .SC_ItemSelected +{ + margin-top: 2px; + margin-bottom: 2px; + background-position: left center; + padding-left: 11px; + padding-right: 3px; + padding-top: 2px; + padding-bottom: 2px; + text-overflow: ellipsis; + overflow: hidden; + background-repeat: no-repeat; + border: #dddddd 1px solid; +} + +.SC_Item *, .SC_ItemSelected * +{ + margin-top: 0px; + margin-bottom: 0px; +} + +.SC_ItemSelected +{ + border: #9a9afb 1px solid; + background-image: url(images/toolbar.arrowright.gif); +} + +.SC_ItemOver +{ + border: #316ac5 1px solid; +} + +.SC_Field +{ + border: #b7b7a6 1px solid; + cursor: default; +} + +.SC_FieldCaption +{ + overflow: visible; + padding-right: 5px; + padding-left: 5px; + opacity: 0.75; /* Safari, Opera and Mozilla */ + filter: alpha(opacity=70); /* IE */ /* -moz-opacity: 0.75; Mozilla (Old) */ + height: 23px; + background-color: #efefde; +} + +.SC_FieldLabel +{ + white-space: nowrap; + padding: 2px; + width: 100%; + cursor: default; + background-color: #ffffff; + text-overflow: ellipsis; + overflow: hidden; +} + +.SC_FieldButton +{ + background-position: center center; + background-image: url(images/toolbar.buttonarrow.gif); + border-left: #b7b7a6 1px solid; + width: 14px; + background-repeat: no-repeat; +} + +.SC_FieldDisabled .SC_FieldButton, .SC_FieldDisabled .SC_FieldCaption, .SC_FieldDisabled .TB_ButtonType_Text +{ + opacity: 0.30; /* Safari, Opera and Mozilla */ + filter: gray() alpha(opacity=30); /* IE */ /* -moz-opacity: 0.30; Mozilla (Old) */ +} + +.SC_FieldOver +{ + border: #316ac5 1px solid; +} + +.SC_FieldOver .SC_FieldButton +{ + border-left: #316ac5 1px solid; +} + +/* + ### Color Selector Panel +*/ + +.ColorBoxBorder +{ + border: #808080 1px solid; + position: static; +} + +.ColorBox +{ + font-size: 1px; + width: 10px; + position: static; + height: 10px; +} + +.ColorDeselected, .ColorSelected +{ + cursor: default; +} + +.ColorDeselected +{ + border: #ffffff 1px solid; + padding: 2px; + float: left; +} + +.ColorSelected +{ + border: #330066 1px solid; + padding: 2px; + float: left; + background-color: #c4cdd6; +} diff --git a/includes/fckeditor/editor/skins/default/fck_strip.gif b/includes/fckeditor/editor/skins/default/fck_strip.gif new file mode 100644 index 0000000..fbb8568 Binary files /dev/null and b/includes/fckeditor/editor/skins/default/fck_strip.gif differ diff --git a/includes/fckeditor/editor/skins/default/images/dialog.sides.gif b/includes/fckeditor/editor/skins/default/images/dialog.sides.gif new file mode 100644 index 0000000..8f91b47 Binary files /dev/null and b/includes/fckeditor/editor/skins/default/images/dialog.sides.gif differ diff --git a/includes/fckeditor/editor/skins/default/images/dialog.sides.png b/includes/fckeditor/editor/skins/default/images/dialog.sides.png new file mode 100644 index 0000000..1042a61 Binary files /dev/null and b/includes/fckeditor/editor/skins/default/images/dialog.sides.png differ diff --git a/includes/fckeditor/editor/skins/default/images/dialog.sides.rtl.png b/includes/fckeditor/editor/skins/default/images/dialog.sides.rtl.png new file mode 100644 index 0000000..d7f7b49 Binary files /dev/null and b/includes/fckeditor/editor/skins/default/images/dialog.sides.rtl.png differ diff --git a/includes/fckeditor/editor/skins/default/images/sprites.gif b/includes/fckeditor/editor/skins/default/images/sprites.gif new file mode 100644 index 0000000..2f57d93 Binary files /dev/null and b/includes/fckeditor/editor/skins/default/images/sprites.gif differ diff --git a/includes/fckeditor/editor/skins/default/images/sprites.png b/includes/fckeditor/editor/skins/default/images/sprites.png new file mode 100644 index 0000000..5be90ed Binary files /dev/null and b/includes/fckeditor/editor/skins/default/images/sprites.png differ diff --git a/includes/fckeditor/editor/skins/default/images/toolbar.arrowright.gif b/includes/fckeditor/editor/skins/default/images/toolbar.arrowright.gif new file mode 100644 index 0000000..6843c8d Binary files /dev/null and b/includes/fckeditor/editor/skins/default/images/toolbar.arrowright.gif differ diff --git a/includes/fckeditor/editor/skins/default/images/toolbar.buttonarrow.gif b/includes/fckeditor/editor/skins/default/images/toolbar.buttonarrow.gif new file mode 100644 index 0000000..ea60995 Binary files /dev/null and b/includes/fckeditor/editor/skins/default/images/toolbar.buttonarrow.gif differ diff --git a/includes/fckeditor/editor/skins/default/images/toolbar.collapse.gif b/includes/fckeditor/editor/skins/default/images/toolbar.collapse.gif new file mode 100644 index 0000000..87aa56d Binary files /dev/null and b/includes/fckeditor/editor/skins/default/images/toolbar.collapse.gif differ diff --git a/includes/fckeditor/editor/skins/default/images/toolbar.end.gif b/includes/fckeditor/editor/skins/default/images/toolbar.end.gif new file mode 100644 index 0000000..5bfd67a Binary files /dev/null and b/includes/fckeditor/editor/skins/default/images/toolbar.end.gif differ diff --git a/includes/fckeditor/editor/skins/default/images/toolbar.expand.gif b/includes/fckeditor/editor/skins/default/images/toolbar.expand.gif new file mode 100644 index 0000000..79075e7 Binary files /dev/null and b/includes/fckeditor/editor/skins/default/images/toolbar.expand.gif differ diff --git a/includes/fckeditor/editor/skins/default/images/toolbar.separator.gif b/includes/fckeditor/editor/skins/default/images/toolbar.separator.gif new file mode 100644 index 0000000..eaed04a Binary files /dev/null and b/includes/fckeditor/editor/skins/default/images/toolbar.separator.gif differ diff --git a/includes/fckeditor/editor/skins/default/images/toolbar.start.gif b/includes/fckeditor/editor/skins/default/images/toolbar.start.gif new file mode 100644 index 0000000..1774246 Binary files /dev/null and b/includes/fckeditor/editor/skins/default/images/toolbar.start.gif differ diff --git a/includes/fckeditor/fckconfig.js b/includes/fckeditor/fckconfig.js new file mode 100644 index 0000000..57defb0 --- /dev/null +++ b/includes/fckeditor/fckconfig.js @@ -0,0 +1,355 @@ +/* + * FCKeditor - The text editor for Internet - http://www.fckeditor.net + * Copyright (C) 2003-2008 Frederico Caldeira Knabben + * + * == BEGIN LICENSE == + * + * Licensed under the terms of any of the following licenses at your + * choice: + * + * - GNU General Public License Version 2 or later (the "GPL") + * http://www.gnu.org/licenses/gpl.html + * + * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") + * http://www.gnu.org/licenses/lgpl.html + * + * - Mozilla Public License Version 1.1 or later (the "MPL") + * http://www.mozilla.org/MPL/MPL-1.1.html + * + * == END LICENSE == + * + * Editor configuration settings. + * + * Follow this link for more information: + * http://docs.fckeditor.net/FCKeditor_2.x/Developers_Guide/Configuration/Configuration_Options + */ + +FCKConfig.CustomConfigurationsPath = '' ; + +FCKConfig.EditorAreaCSS = FCKConfig.BasePath + 'css/fck_editorarea.css' ; +FCKConfig.EditorAreaStyles = '' ; +FCKConfig.ToolbarComboPreviewCSS = '' ; + +FCKConfig.DocType = '' ; + +FCKConfig.BaseHref = '' ; + +FCKConfig.FullPage = false ; + +// The following option determines whether the "Show Blocks" feature is enabled or not at startup. +FCKConfig.StartupShowBlocks = false ; + +FCKConfig.Debug = false ; +FCKConfig.AllowQueryStringDebug = true ; + +FCKConfig.SkinPath = FCKConfig.BasePath + 'skins/default/' ; +FCKConfig.SkinEditorCSS = '' ; // FCKConfig.SkinPath + "|" ; +FCKConfig.SkinDialogCSS = '' ; // FCKConfig.SkinPath + "|" ; + +FCKConfig.PreloadImages = [ FCKConfig.SkinPath + 'images/toolbar.start.gif', FCKConfig.SkinPath + 'images/toolbar.buttonarrow.gif' ] ; + +FCKConfig.PluginsPath = FCKConfig.BasePath + 'plugins/' ; + +// FCKConfig.Plugins.Add( 'autogrow' ) ; +// FCKConfig.Plugins.Add( 'dragresizetable' ); +FCKConfig.AutoGrowMax = 400 ; + +// FCKConfig.ProtectedSource.Add( /<%[\s\S]*?%>/g ) ; // ASP style server side code <%...%> +// FCKConfig.ProtectedSource.Add( /<\?[\s\S]*?\?>/g ) ; // PHP style server side code +// FCKConfig.ProtectedSource.Add( /(]+>[\s|\S]*?<\/asp:[^\>]+>)|(]+\/>)/gi ) ; // ASP.Net style tags + +FCKConfig.AutoDetectLanguage = true ; +FCKConfig.DefaultLanguage = 'zh-cn' ; +FCKConfig.ContentLangDirection = 'ltr' ; + +FCKConfig.ProcessHTMLEntities = true ; +FCKConfig.IncludeLatinEntities = true ; +FCKConfig.IncludeGreekEntities = true ; + +FCKConfig.ProcessNumericEntities = false ; + +FCKConfig.AdditionalNumericEntities = '' ; // Single Quote: "'" + +FCKConfig.FillEmptyBlocks = true ; + +FCKConfig.FormatSource = true ; +FCKConfig.FormatOutput = true ; +FCKConfig.FormatIndentator = ' ' ; + +FCKConfig.EMailProtection = 'encode' ; // none | encode | function +FCKConfig.EMailProtectionFunction = 'mt(NAME,DOMAIN,SUBJECT,BODY)' ; + +FCKConfig.StartupFocus = false ; +FCKConfig.ForcePasteAsPlainText = false ; +FCKConfig.AutoDetectPasteFromWord = true ; // IE only. +FCKConfig.ShowDropDialog = true ; +FCKConfig.ForceSimpleAmpersand = false ; +FCKConfig.TabSpaces = 0 ; +FCKConfig.ShowBorders = true ; +FCKConfig.SourcePopup = false ; +FCKConfig.ToolbarStartExpanded = true ; +FCKConfig.ToolbarCanCollapse = true ; +FCKConfig.IgnoreEmptyParagraphValue = true ; +FCKConfig.FloatingPanelsZIndex = 10000 ; +FCKConfig.HtmlEncodeOutput = false ; +FCKConfig.PreserveSessionOnFileBrowser = false ; + +FCKConfig.TemplateReplaceAll = true ; +FCKConfig.TemplateReplaceCheckbox = true ; + +FCKConfig.ToolbarLocation = 'In' ; + +FCKConfig.ToolbarSets["Default"] = [ + ['Source','DocProps','-','Save','NewPage','Preview','-','Templates'], + ['Cut','Copy','Paste','PasteText','PasteWord','-','Print','SpellCheck'], + ['Undo','Redo','-','Find','Replace','-','SelectAll','RemoveFormat'], + ['Form','Checkbox','Radio','TextField','Textarea','Select','Button','ImageButton','HiddenField'], + '/', + ['Bold','Italic','Underline','StrikeThrough','-','Subscript','Superscript'], + ['OrderedList','UnorderedList','-','Outdent','Indent','Blockquote','CreateDiv'], + ['JustifyLeft','JustifyCenter','JustifyRight','JustifyFull'], + ['Link','Unlink','Anchor'], + ['Image','Flash','UpFileBtn','Table','Rule','Smiley','SpecialChar','PageBreak'], + '/', + ['Style','FontFormat','FontName','FontSize'], + ['TextColor','BGColor'], + ['FitWindow','ShowBlocks','-','About'] // No comma for the last row. +] ; + +FCKConfig.ToolbarSets["Basic"] = [ + ['Bold','Italic','-','OrderedList','UnorderedList','-','Link','Unlink','-','About'] +] ; + +FCKConfig.ToolbarSets["Normal"] = [ + ['Cut','Copy','Paste','PasteText','PasteWord','-','Undo','Redo','-','Find','Replace','-','RemoveFormat'], + ['Link','Unlink','-','Image','Flash','UpFileBtn','Table'], + ['FitWindow','-','Source'], + '/', + ['FontFormat','FontSize'], + ['Bold','Italic','Underline'], + ['OrderedList','UnorderedList','-','Outdent','Indent'], + ['JustifyLeft','JustifyCenter','JustifyRight'], + ['TextColor','BGColor'] +] ; + +FCKConfig.ToolbarSets["Mail"] = [ + ['Cut','Copy','Paste','PasteText','PasteWord','-','Undo','Redo','-','Find','Replace','-','RemoveFormat'], + ['Table'], + ['FitWindow','-','Source'], + '/', + ['FontFormat','FontSize'], + ['Bold','Italic','Underline'], + ['OrderedList','UnorderedList','-','Outdent','Indent'], + ['JustifyLeft','JustifyCenter','JustifyRight'], + ['TextColor','BGColor'] +]; + +FCKConfig.EnterMode = 'p' ; // p | div | br +FCKConfig.ShiftEnterMode = 'br' ; // p | div | br + +FCKConfig.Keystrokes = [ + [ CTRL + 65 /*A*/, true ], + [ CTRL + 67 /*C*/, true ], + [ CTRL + 70 /*F*/, true ], + [ CTRL + 83 /*S*/, true ], + [ CTRL + 84 /*T*/, true ], + [ CTRL + 88 /*X*/, true ], + [ CTRL + 86 /*V*/, 'Paste' ], + [ CTRL + 45 /*INS*/, true ], + [ SHIFT + 45 /*INS*/, 'Paste' ], + [ CTRL + 88 /*X*/, 'Cut' ], + [ SHIFT + 46 /*DEL*/, 'Cut' ], + [ CTRL + 90 /*Z*/, 'Undo' ], + [ CTRL + 89 /*Y*/, 'Redo' ], + [ CTRL + SHIFT + 90 /*Z*/, 'Redo' ], + [ CTRL + 76 /*L*/, 'Link' ], + [ CTRL + 66 /*B*/, 'Bold' ], + [ CTRL + 73 /*I*/, 'Italic' ], + [ CTRL + 85 /*U*/, 'Underline' ], + [ CTRL + SHIFT + 83 /*S*/, 'Save' ], + [ CTRL + ALT + 13 /*ENTER*/, 'FitWindow' ], + [ SHIFT + 32 /*SPACE*/, 'Nbsp' ] +] ; + +FCKConfig.ContextMenu = ['Generic','Link','Anchor','Image','Flash','Select','Textarea','Checkbox','Radio','TextField','HiddenField','ImageButton','Button','BulletedList','NumberedList','Table','Form','DivContainer'] ; +FCKConfig.BrowserContextMenuOnCtrl = false ; +FCKConfig.BrowserContextMenu = false ; + +FCKConfig.EnableMoreFontColors = true ; +FCKConfig.FontColors = '000000,993300,333300,003300,003366,000080,333399,333333,800000,FF6600,808000,808080,008080,0000FF,666699,808080,FF0000,FF9900,99CC00,339966,33CCCC,3366FF,800080,999999,FF00FF,FFCC00,FFFF00,00FF00,00FFFF,00CCFF,993366,C0C0C0,FF99CC,FFCC99,FFFF99,CCFFCC,CCFFFF,99CCFF,CC99FF,FFFFFF' ; + +FCKConfig.FontFormats = 'p;h1;h2;h3;h4;h5;h6;pre;address;div' ; +FCKConfig.FontNames = 'Arial;Comic Sans MS;Courier New;Tahoma;Times New Roman;Verdana' ; +FCKConfig.FontSizes = 'smaller;larger;xx-small;x-small;small;medium;large;x-large;xx-large' ; + +FCKConfig.StylesXmlPath = FCKConfig.EditorPath + 'fckstyles.xml' ; +FCKConfig.TemplatesXmlPath = FCKConfig.EditorPath + 'fcktemplates.xml' ; + +FCKConfig.SpellChecker = 'ieSpell' ; // 'ieSpell' | 'SpellerPages' +FCKConfig.IeSpellDownloadUrl = 'http://www.iespell.com/download.php' ; +FCKConfig.SpellerPagesServerScript = 'server-scripts/spellchecker.php' ; // Available extension: .php .cfm .pl +FCKConfig.FirefoxSpellChecker = false ; + +FCKConfig.MaxUndoLevels = 15 ; + +FCKConfig.DisableObjectResizing = false ; +FCKConfig.DisableFFTableHandles = true ; + +FCKConfig.LinkDlgHideTarget = false ; +FCKConfig.LinkDlgHideAdvanced = false ; + +FCKConfig.ImageDlgHideLink = false ; +FCKConfig.ImageDlgHideAdvanced = false ; + +FCKConfig.FlashDlgHideAdvanced = false ; + +FCKConfig.ProtectedTags = '' ; + +// This will be applied to the body element of the editor +FCKConfig.BodyId = '' ; +FCKConfig.BodyClass = '' ; + +FCKConfig.DefaultStyleLabel = '' ; +FCKConfig.DefaultFontFormatLabel = '' ; +FCKConfig.DefaultFontLabel = '' ; +FCKConfig.DefaultFontSizeLabel = '' ; + +FCKConfig.DefaultLinkTarget = '' ; + +// The option switches between trying to keep the html structure or do the changes so the content looks like it was in Word +FCKConfig.CleanWordKeepsStructure = false ; + +// Only inline elements are valid. +FCKConfig.RemoveFormatTags = 'b,big,code,del,dfn,em,font,i,ins,kbd,q,samp,small,span,strike,strong,sub,sup,tt,u,var' ; + +// Attributes that will be removed +FCKConfig.RemoveAttributes = 'class,style,lang,width,height,align,hspace,valign' ; + +FCKConfig.CustomStyles = +{ + 'Red Title' : { Element : 'h3', Styles : { 'color' : 'Red' } } +}; + +// Do not add, rename or remove styles here. Only apply definition changes. +FCKConfig.CoreStyles = +{ + // Basic Inline Styles. + 'Bold' : { Element : 'strong', Overrides : 'b' }, + 'Italic' : { Element : 'em', Overrides : 'i' }, + 'Underline' : { Element : 'u' }, + 'StrikeThrough' : { Element : 'strike' }, + 'Subscript' : { Element : 'sub' }, + 'Superscript' : { Element : 'sup' }, + + // Basic Block Styles (Font Format Combo). + 'p' : { Element : 'p' }, + 'div' : { Element : 'div' }, + 'pre' : { Element : 'pre' }, + 'address' : { Element : 'address' }, + 'h1' : { Element : 'h1' }, + 'h2' : { Element : 'h2' }, + 'h3' : { Element : 'h3' }, + 'h4' : { Element : 'h4' }, + 'h5' : { Element : 'h5' }, + 'h6' : { Element : 'h6' }, + + // Other formatting features. + 'FontFace' : + { + Element : 'span', + Styles : { 'font-family' : '#("Font")' }, + Overrides : [ { Element : 'font', Attributes : { 'face' : null } } ] + }, + + 'Size' : + { + Element : 'span', + Styles : { 'font-size' : '#("Size","fontSize")' }, + Overrides : [ { Element : 'font', Attributes : { 'size' : null } } ] + }, + + 'Color' : + { + Element : 'span', + Styles : { 'color' : '#("Color","color")' }, + Overrides : [ { Element : 'font', Attributes : { 'color' : null } } ] + }, + + 'BackColor' : { Element : 'span', Styles : { 'background-color' : '#("Color","color")' } }, + + 'SelectionHighlight' : { Element : 'span', Styles : { 'background-color' : 'navy', 'color' : 'white' } } +}; + +// The distance of an indentation step. +FCKConfig.IndentLength = 40 ; +FCKConfig.IndentUnit = 'px' ; + +// Alternatively, FCKeditor allows the use of CSS classes for block indentation. +// This overrides the IndentLength/IndentUnit settings. +FCKConfig.IndentClasses = [] ; + +// [ Left, Center, Right, Justified ] +FCKConfig.JustifyClasses = [] ; + +// The following value defines which File Browser connector and Quick Upload +// "uploader" to use. It is valid for the default implementaion and it is here +// just to make this configuration file cleaner. +// It is not possible to change this value using an external file or even +// inline when creating the editor instance. In that cases you must set the +// values of LinkBrowserURL, ImageBrowserURL and so on. +// Custom implementations should just ignore it. +var _FileBrowserLanguage = 'php' ; // asp | aspx | cfm | lasso | perl | php | py +var _QuickUploadLanguage = 'php' ; // asp | aspx | cfm | lasso | perl | php | py + +// Don't care about the following two lines. It just calculates the correct connector +// extension to use for the default File Browser (Perl uses "cgi"). +var _FileBrowserExtension = _FileBrowserLanguage == 'perl' ? 'cgi' : _FileBrowserLanguage ; +var _QuickUploadExtension = _QuickUploadLanguage == 'perl' ? 'cgi' : _QuickUploadLanguage ; + +FCKConfig.LinkBrowser = true ; +FCKConfig.LinkBrowserURL = FCKConfig.BasePath + 'filemanager/browser/default/browser.html?Connector=' + encodeURIComponent( FCKConfig.BasePath + 'filemanager/connectors/' + _FileBrowserLanguage + '/connector.' + _FileBrowserExtension ) ; +FCKConfig.LinkBrowserWindowWidth = FCKConfig.ScreenWidth * 0.7 ; // 70% +FCKConfig.LinkBrowserWindowHeight = FCKConfig.ScreenHeight * 0.7 ; // 70% + +FCKConfig.ImageBrowser = true ; +FCKConfig.ImageBrowserURL = FCKConfig.BasePath + 'filemanager/browser/default/browser.html?Type=Image&Connector=' + encodeURIComponent( FCKConfig.BasePath + 'filemanager/connectors/' + _FileBrowserLanguage + '/connector.' + _FileBrowserExtension ) ; +FCKConfig.ImageBrowserWindowWidth = FCKConfig.ScreenWidth * 0.7 ; // 70% ; +FCKConfig.ImageBrowserWindowHeight = FCKConfig.ScreenHeight * 0.7 ; // 70% ; + +FCKConfig.FlashBrowser = true ; +FCKConfig.FlashBrowserURL = FCKConfig.BasePath + 'filemanager/browser/default/browser.html?Type=Flash&Connector=' + encodeURIComponent( FCKConfig.BasePath + 'filemanager/connectors/' + _FileBrowserLanguage + '/connector.' + _FileBrowserExtension ) ; +FCKConfig.FlashBrowserWindowWidth = FCKConfig.ScreenWidth * 0.7 ; //70% ; +FCKConfig.FlashBrowserWindowHeight = FCKConfig.ScreenHeight * 0.7 ; //70% ; + +FCKConfig.LinkUpload = true ; +FCKConfig.LinkUploadURL = FCKConfig.BasePath + 'filemanager/connectors/' + _QuickUploadLanguage + '/upload.' + _QuickUploadExtension ; +FCKConfig.LinkUploadAllowedExtensions = ".(7z|aiff|asf|avi|bmp|csv|doc|fla|flv|gif|gz|gzip|jpeg|jpg|mid|mov|mp3|mp4|mpc|mpeg|mpg|ods|odt|pdf|png|ppt|pxd|qt|ram|rar|rm|rmi|rmvb|rtf|sdc|sitd|swf|sxc|sxw|tar|tgz|tif|tiff|txt|vsd|wav|wma|wmv|xls|xml|zip)$" ; // empty for all +FCKConfig.LinkUploadDeniedExtensions = "" ; // empty for no one + +FCKConfig.FilesUpload = true ; +FCKConfig.FilesUploadURL = FCKConfig.BasePath + 'filemanager/connectors/' + _QuickUploadLanguage + '/upload_more.' + _QuickUploadExtension ; +FCKConfig.FilesUploadAllowedExtensions = ".(7z|aiff|asf|avi|bmp|csv|doc|fla|flv|gif|gz|gzip|jpeg|jpg|mid|mov|mp3|mp4|mpc|mpeg|mpg|ods|odt|pdf|png|ppt|pxd|qt|ram|rar|rm|rmi|rmvb|rtf|sdc|sitd|swf|sxc|sxw|tar|tgz|tif|tiff|txt|vsd|wav|wma|wmv|xls|xml|zip)$" ; // empty for all +FCKConfig.FilesUploadDeniedExtensions = "" ; // empty for no one + +FCKConfig.ImageUpload = true ; +FCKConfig.ImageUploadURL = FCKConfig.BasePath + 'filemanager/connectors/' + _QuickUploadLanguage + '/upload.' + _QuickUploadExtension + '?Type=Image' ; +FCKConfig.ImageUploadAllowedExtensions = ".(jpg|gif|jpeg|png|bmp)$" ; // empty for all +FCKConfig.ImageUploadDeniedExtensions = "" ; // empty for no one + +FCKConfig.FlashUpload = true ; +FCKConfig.FlashUploadURL = FCKConfig.BasePath + 'filemanager/connectors/' + _QuickUploadLanguage + '/upload.' + _QuickUploadExtension + '?Type=Flash' ; +FCKConfig.FlashUploadAllowedExtensions = ".(swf|flv)$" ; // empty for all +FCKConfig.FlashUploadDeniedExtensions = "" ; // empty for no one + +FCKConfig.SmileyPath = FCKConfig.BasePath + 'images/smiley/msn/' ; +FCKConfig.SmileyImages = ['regular_smile.gif','sad_smile.gif','wink_smile.gif','teeth_smile.gif','confused_smile.gif','tounge_smile.gif','embaressed_smile.gif','omg_smile.gif','whatchutalkingabout_smile.gif','angry_smile.gif','angel_smile.gif','shades_smile.gif','devil_smile.gif','cry_smile.gif','lightbulb.gif','thumbs_down.gif','thumbs_up.gif','heart.gif','broken_heart.gif','kiss.gif','envelope.gif'] ; +FCKConfig.SmileyColumns = 8 ; +FCKConfig.SmileyWindowWidth = 320 ; +FCKConfig.SmileyWindowHeight = 210 ; + +FCKConfig.BackgroundBlockerColor = '#ffffff' ; +FCKConfig.BackgroundBlockerOpacity = 0.50 ; + +FCKConfig.MsWebBrowserControlCompat = false ; + +FCKConfig.PreventSubmitHandler = false ; diff --git a/includes/fckeditor/fckeditor.cfc b/includes/fckeditor/fckeditor.cfc new file mode 100644 index 0000000..d681914 --- /dev/null +++ b/includes/fckeditor/fckeditor.cfc @@ -0,0 +1,232 @@ + + + + + + + + #CreateHtml()# + + + + + + + + + + + + + + + // display the html editor or a plain textarea? + if( isCompatible() ) + return getHtmlEditor(); + else + return getTextArea(); + + + + + + + + var sAgent = lCase( cgi.HTTP_USER_AGENT ); + var stResult = ""; + var sBrowserVersion = ""; + + // do not check if argument "checkBrowser" is false + if( not this.checkBrowser ) + return true; + + return FCKeditor_IsCompatibleBrowser(); + + + + + + + + + + if( Find( "%", this.width ) gt 0) + sWidthCSS = this.width; + else + sWidthCSS = this.width & "px"; + + if( Find( "%", this.width ) gt 0) + sHeightCSS = this.height; + else + sHeightCSS = this.height & "px"; + + result = "" & chr(13) & chr(10); + + + + + + + + + + // try to fix the basePath, if ending slash is missing + if( len( this.basePath) and right( this.basePath, 1 ) is not "/" ) + this.basePath = this.basePath & "/"; + + // construct the url + sURL = this.basePath & "editor/fckeditor.html?InstanceName=" & this.instanceName; + + // append toolbarset name to the url + if( len( this.toolbarSet ) ) + sURL = sURL & "&Toolbar=" & this.toolbarSet; + + + + result = result & "" & chr(13) & chr(10); + result = result & "" & chr(13) & chr(10); + result = result & "" & chr(13) & chr(10); + + + + + + + + + + + + + + /** + * CFML doesn't store casesensitive names for structure keys, but the configuration names must be casesensitive for js. + * So we need to find out the correct case for the configuration keys. + * We "fix" this by comparing the caseless configuration keys to a list of all available configuration options in the correct case. + * changed 20041206 hk@lwd.de (improvements are welcome!) + */ + lConfigKeys = lConfigKeys & "CustomConfigurationsPath,EditorAreaCSS,ToolbarComboPreviewCSS,DocType"; + lConfigKeys = lConfigKeys & ",BaseHref,FullPage,Debug,AllowQueryStringDebug,SkinPath"; + lConfigKeys = lConfigKeys & ",PreloadImages,PluginsPath,AutoDetectLanguage,DefaultLanguage,ContentLangDirection"; + lConfigKeys = lConfigKeys & ",ProcessHTMLEntities,IncludeLatinEntities,IncludeGreekEntities,ProcessNumericEntities,AdditionalNumericEntities"; + lConfigKeys = lConfigKeys & ",FillEmptyBlocks,FormatSource,FormatOutput,FormatIndentator"; + lConfigKeys = lConfigKeys & ",StartupFocus,ForcePasteAsPlainText,AutoDetectPasteFromWord,ForceSimpleAmpersand"; + lConfigKeys = lConfigKeys & ",TabSpaces,ShowBorders,SourcePopup,ToolbarStartExpanded,ToolbarCanCollapse"; + lConfigKeys = lConfigKeys & ",IgnoreEmptyParagraphValue,FloatingPanelsZIndex,TemplateReplaceAll,TemplateReplaceCheckbox"; + lConfigKeys = lConfigKeys & ",ToolbarLocation,ToolbarSets,EnterMode,ShiftEnterMode,Keystrokes"; + lConfigKeys = lConfigKeys & ",ContextMenu,BrowserContextMenuOnCtrl,FontColors,FontNames,FontSizes"; + lConfigKeys = lConfigKeys & ",FontFormats,StylesXmlPath,TemplatesXmlPath,SpellChecker,IeSpellDownloadUrl"; + lConfigKeys = lConfigKeys & ",SpellerPagesServerScript,FirefoxSpellChecker,MaxUndoLevels,DisableObjectResizing,DisableFFTableHandles"; + lConfigKeys = lConfigKeys & ",LinkDlgHideTarget,LinkDlgHideAdvanced,ImageDlgHideLink,ImageDlgHideAdvanced,FlashDlgHideAdvanced"; + lConfigKeys = lConfigKeys & ",ProtectedTags,BodyId,BodyClass,DefaultLinkTarget,CleanWordKeepsStructure"; + lConfigKeys = lConfigKeys & ",LinkBrowser,LinkBrowserURL,LinkBrowserWindowWidth,LinkBrowserWindowHeight,ImageBrowser"; + lConfigKeys = lConfigKeys & ",ImageBrowserURL,ImageBrowserWindowWidth,ImageBrowserWindowHeight,FlashBrowser,FlashBrowserURL"; + lConfigKeys = lConfigKeys & ",FlashBrowserWindowWidth,FlashBrowserWindowHeight,LinkUpload,LinkUploadURL,LinkUploadWindowWidth"; + lConfigKeys = lConfigKeys & ",LinkUploadWindowHeight,LinkUploadAllowedExtensions,LinkUploadDeniedExtensions,ImageUpload,ImageUploadURL"; + lConfigKeys = lConfigKeys & ",ImageUploadAllowedExtensions,ImageUploadDeniedExtensions,FlashUpload,FlashUploadURL,FlashUploadAllowedExtensions"; + lConfigKeys = lConfigKeys & ",FlashUploadDeniedExtensions,SmileyPath,SmileyImages,SmileyColumns,SmileyWindowWidth,SmileyWindowHeight"; + + for( key in this.config ) + { + iPos = listFindNoCase( lConfigKeys, key ); + if( iPos GT 0 ) + { + if( len( sParams ) ) + sParams = sParams & "&"; + + fieldValue = this.config[key]; + fieldName = listGetAt( lConfigKeys, iPos ); + + // set all boolean possibilities in CFML to true/false values + if( isBoolean( fieldValue) and fieldValue ) + fieldValue = "true"; + else if( isBoolean( fieldValue) ) + fieldValue = "false"; + + sParams = sParams & HTMLEditFormat( fieldName ) & '=' & HTMLEditFormat( fieldValue ); + } + } + return sParams; + + + + + diff --git a/includes/fckeditor/fckeditor.js b/includes/fckeditor/fckeditor.js new file mode 100644 index 0000000..8994eda --- /dev/null +++ b/includes/fckeditor/fckeditor.js @@ -0,0 +1,328 @@ +/* + * FCKeditor - The text editor for Internet - http://www.fckeditor.net + * Copyright (C) 2003-2008 Frederico Caldeira Knabben + * + * == BEGIN LICENSE == + * + * Licensed under the terms of any of the following licenses at your + * choice: + * + * - GNU General Public License Version 2 or later (the "GPL") + * http://www.gnu.org/licenses/gpl.html + * + * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") + * http://www.gnu.org/licenses/lgpl.html + * + * - Mozilla Public License Version 1.1 or later (the "MPL") + * http://www.mozilla.org/MPL/MPL-1.1.html + * + * == END LICENSE == + * + * This is the integration file for JavaScript. + * + * It defines the FCKeditor class that can be used to create editor + * instances in a HTML page in the client side. For server side + * operations, use the specific integration system. + */ + +// FCKeditor Class +var FCKeditor = function( instanceName, width, height, toolbarSet, value ) +{ + // Properties + this.InstanceName = instanceName ; + this.Width = width || '100%' ; + this.Height = height || '200' ; + this.ToolbarSet = toolbarSet || 'Default' ; + this.Value = value || '' ; + this.BasePath = FCKeditor.BasePath ; + this.CheckBrowser = true ; + this.DisplayErrors = true ; + + this.Config = new Object() ; + + // Events + this.OnError = null ; // function( source, errorNumber, errorDescription ) +} + +/** + * This is the default BasePath used by all editor instances. + */ +FCKeditor.BasePath = '/fckeditor/' ; + +/** + * The minimum height used when replacing textareas. + */ +FCKeditor.MinHeight = 200 ; + +/** + * The minimum width used when replacing textareas. + */ +FCKeditor.MinWidth = 750 ; + +FCKeditor.prototype.Version = '2.6.3' ; +FCKeditor.prototype.VersionBuild = '19836' ; + +FCKeditor.prototype.Create = function() +{ + document.write( this.CreateHtml() ) ; +} + +FCKeditor.prototype.CreateHtml = function() +{ + // Check for errors + if ( !this.InstanceName || this.InstanceName.length == 0 ) + { + this._ThrowError( 701, 'You must specify an instance name.' ) ; + return '' ; + } + + var sHtml = '' ; + + if ( !this.CheckBrowser || this._IsCompatibleBrowser() ) + { + sHtml += '' ; + sHtml += this._GetConfigHtml() ; + sHtml += this._GetIFrameHtml() ; + } + else + { + var sWidth = this.Width.toString().indexOf('%') > 0 ? this.Width : this.Width + 'px' ; + var sHeight = this.Height.toString().indexOf('%') > 0 ? this.Height : this.Height + 'px' ; + + sHtml += '" ; + } + + return $Html ; + } + + /** + * Returns true if browser is compatible with FCKeditor. + * + * @return boolean + */ + function IsCompatible() + { + return FCKeditor_IsCompatibleBrowser() ; + } + + /** + * Get settings from Config array as a single string. + * + * @access protected + * @return string + */ + function GetConfigFieldString() + { + $sParams = '' ; + $bFirst = true ; + + foreach ( $this->Config as $sKey => $sValue ) + { + if ( $bFirst == false ) + $sParams .= '&' ; + else + $bFirst = false ; + + if ( $sValue === true ) + $sParams .= $this->EncodeConfig( $sKey ) . '=true' ; + else if ( $sValue === false ) + $sParams .= $this->EncodeConfig( $sKey ) . '=false' ; + else + $sParams .= $this->EncodeConfig( $sKey ) . '=' . $this->EncodeConfig( $sValue ) ; + } + + return $sParams ; + } + + /** + * Encode characters that may break the configuration string + * generated by GetConfigFieldString(). + * + * @access protected + * @param string $valueToEncode + * @return string + */ + function EncodeConfig( $valueToEncode ) + { + $chars = array( + '&' => '%26', + '=' => '%3D', + '"' => '%22' ) ; + + return strtr( $valueToEncode, $chars ) ; + } +} diff --git a/includes/fckeditor/fckeditor_php5.php b/includes/fckeditor/fckeditor_php5.php new file mode 100644 index 0000000..f346537 --- /dev/null +++ b/includes/fckeditor/fckeditor_php5.php @@ -0,0 +1,257 @@ += 5.5) ; + } + else if ( strpos($sAgent, 'Gecko/') !== false ) + { + $iVersion = (int)substr($sAgent, strpos($sAgent, 'Gecko/') + 6, 8) ; + return ($iVersion >= 20030210) ; + } + else if ( strpos($sAgent, 'Opera/') !== false ) + { + $fVersion = (float)substr($sAgent, strpos($sAgent, 'Opera/') + 6, 4) ; + return ($fVersion >= 9.5) ; + } + else if ( preg_match( "|AppleWebKit/(\d+)|i", $sAgent, $matches ) ) + { + $iVersion = $matches[1] ; + return ( $matches[1] >= 522 ) ; + } + else + return false ; +} + +class FCKeditor +{ + /** + * Name of the FCKeditor instance. + * + * @access protected + * @var string + */ + public $InstanceName ; + /** + * Path to FCKeditor relative to the document root. + * + * @var string + */ + public $BasePath ; + /** + * Width of the FCKeditor. + * Examples: 100%, 600 + * + * @var mixed + */ + public $Width ; + /** + * Height of the FCKeditor. + * Examples: 400, 50% + * + * @var mixed + */ + public $Height ; + /** + * Name of the toolbar to load. + * + * @var string + */ + public $ToolbarSet ; + /** + * Initial value. + * + * @var string + */ + public $Value ; + /** + * This is where additional configuration can be passed. + * Example: + * $oFCKeditor->Config['EnterMode'] = 'br'; + * + * @var array + */ + public $Config ; + + /** + * Main Constructor. + * Refer to the _samples/php directory for examples. + * + * @param string $instanceName + */ + public function __construct( $instanceName ) + { + $this->InstanceName = $instanceName ; + $this->BasePath = '/fckeditor/' ; + $this->Width = '100%' ; + $this->Height = '200' ; + $this->ToolbarSet = 'Default' ; + $this->Value = '' ; + + $this->Config = array() ; + } + + /** + * Display FCKeditor. + * + */ + public function Create() + { + echo $this->CreateHtml() ; + } + + /** + * Return the HTML code required to run FCKeditor. + * + * @return string + */ + public function CreateHtml() + { + $HtmlValue = htmlspecialchars( $this->Value ) ; + + $Html = '' ; + + if ( $this->IsCompatible() ) + { + if ( isset( $_GET['fcksource'] ) && $_GET['fcksource'] == "true" ) + $File = 'fckeditor.original.html' ; + else + $File = 'fckeditor.html' ; + + $Link = "{$this->BasePath}editor/{$File}?InstanceName={$this->InstanceName}" ; + + if ( $this->ToolbarSet != '' ) + $Link .= "&Toolbar={$this->ToolbarSet}" ; + + // Render the linked hidden field. + $Html .= "InstanceName}\" name=\"{$this->InstanceName}\" value=\"{$HtmlValue}\" style=\"display:none\" />" ; + + // Render the configurations hidden field. + $Html .= "InstanceName}___Config\" value=\"" . $this->GetConfigFieldString() . "\" style=\"display:none\" />" ; + + // Render the editor IFRAME. + $Html .= "" ; + } + else + { + if ( strpos( $this->Width, '%' ) === false ) + $WidthCSS = $this->Width . 'px' ; + else + $WidthCSS = $this->Width ; + + if ( strpos( $this->Height, '%' ) === false ) + $HeightCSS = $this->Height . 'px' ; + else + $HeightCSS = $this->Height ; + + $Html .= "" ; + } + + return $Html ; + } + + /** + * Returns true if browser is compatible with FCKeditor. + * + * @return boolean + */ + public function IsCompatible() + { + return FCKeditor_IsCompatibleBrowser() ; + } + + /** + * Get settings from Config array as a single string. + * + * @access protected + * @return string + */ + public function GetConfigFieldString() + { + $sParams = '' ; + $bFirst = true ; + + foreach ( $this->Config as $sKey => $sValue ) + { + if ( $bFirst == false ) + $sParams .= '&' ; + else + $bFirst = false ; + + if ( $sValue === true ) + $sParams .= $this->EncodeConfig( $sKey ) . '=true' ; + else if ( $sValue === false ) + $sParams .= $this->EncodeConfig( $sKey ) . '=false' ; + else + $sParams .= $this->EncodeConfig( $sKey ) . '=' . $this->EncodeConfig( $sValue ) ; + } + + return $sParams ; + } + + /** + * Encode characters that may break the configuration string + * generated by GetConfigFieldString(). + * + * @access protected + * @param string $valueToEncode + * @return string + */ + public function EncodeConfig( $valueToEncode ) + { + $chars = array( + '&' => '%26', + '=' => '%3D', + '"' => '%22' ) ; + + return strtr( $valueToEncode, $chars ) ; + } +} diff --git a/includes/fckeditor/fckpackager.xml b/includes/fckeditor/fckpackager.xml new file mode 100644 index 0000000..db127fd --- /dev/null +++ b/includes/fckeditor/fckpackager.xml @@ -0,0 +1,262 @@ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
diff --git a/includes/fckeditor/fckstyles.xml b/includes/fckeditor/fckstyles.xml new file mode 100644 index 0000000..6375e46 --- /dev/null +++ b/includes/fckeditor/fckstyles.xml @@ -0,0 +1,111 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/includes/fckeditor/fcktemplates.xml b/includes/fckeditor/fcktemplates.xml new file mode 100644 index 0000000..0ec3f88 --- /dev/null +++ b/includes/fckeditor/fcktemplates.xml @@ -0,0 +1,103 @@ + + + + + + + diff --git a/includes/fckeditor/license.txt b/includes/fckeditor/license.txt new file mode 100644 index 0000000..dd4b7bc --- /dev/null +++ b/includes/fckeditor/license.txt @@ -0,0 +1,1246 @@ +FCKeditor - The text editor for Internet - http://www.fckeditor.net +Copyright (C) 2003-2008 Frederico Caldeira Knabben + +Licensed under the terms of any of the following licenses at your +choice: + + - GNU General Public License Version 2 or later (the "GPL") + http://www.gnu.org/licenses/gpl.html + (See Appendix A) + + - GNU Lesser General Public License Version 2.1 or later (the "LGPL") + http://www.gnu.org/licenses/lgpl.html + (See Appendix B) + + - Mozilla Public License Version 1.1 or later (the "MPL") + http://www.mozilla.org/MPL/MPL-1.1.html + (See Appendix C) + +You are not required to, but if you want to explicitly declare the +license you have chosen to be bound to when using, reproducing, +modifying and distributing this software, just include a text file +titled "legal.txt" in your version of this software, indicating your +license choice. In any case, your choice will not restrict any +recipient of your version of this software to use, reproduce, modify +and distribute this software under any of the above licenses. + +Appendix A: The GPL License +=========================== + + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + +Appendix B: The LGPL License +============================ + + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + +Appendix C: The MPL License +=========================== + + MOZILLA PUBLIC LICENSE + Version 1.1 + + --------------- + +1. Definitions. + + 1.0.1. "Commercial Use" means distribution or otherwise making the + Covered Code available to a third party. + + 1.1. "Contributor" means each entity that creates or contributes to + the creation of Modifications. + + 1.2. "Contributor Version" means the combination of the Original + Code, prior Modifications used by a Contributor, and the Modifications + made by that particular Contributor. + + 1.3. "Covered Code" means the Original Code or Modifications or the + combination of the Original Code and Modifications, in each case + including portions thereof. + + 1.4. "Electronic Distribution Mechanism" means a mechanism generally + accepted in the software development community for the electronic + transfer of data. + + 1.5. "Executable" means Covered Code in any form other than Source + Code. + + 1.6. "Initial Developer" means the individual or entity identified + as the Initial Developer in the Source Code notice required by Exhibit + A. + + 1.7. "Larger Work" means a work which combines Covered Code or + portions thereof with code not governed by the terms of this License. + + 1.8. "License" means this document. + + 1.8.1. "Licensable" means having the right to grant, to the maximum + extent possible, whether at the time of the initial grant or + subsequently acquired, any and all of the rights conveyed herein. + + 1.9. "Modifications" means any addition to or deletion from the + substance or structure of either the Original Code or any previous + Modifications. When Covered Code is released as a series of files, a + Modification is: + A. Any addition to or deletion from the contents of a file + containing Original Code or previous Modifications. + + B. Any new file that contains any part of the Original Code or + previous Modifications. + + 1.10. "Original Code" means Source Code of computer software code + which is described in the Source Code notice required by Exhibit A as + Original Code, and which, at the time of its release under this + License is not already Covered Code governed by this License. + + 1.10.1. "Patent Claims" means any patent claim(s), now owned or + hereafter acquired, including without limitation, method, process, + and apparatus claims, in any patent Licensable by grantor. + + 1.11. "Source Code" means the preferred form of the Covered Code for + making modifications to it, including all modules it contains, plus + any associated interface definition files, scripts used to control + compilation and installation of an Executable, or source code + differential comparisons against either the Original Code or another + well known, available Covered Code of the Contributor's choice. The + Source Code can be in a compressed or archival form, provided the + appropriate decompression or de-archiving software is widely available + for no charge. + + 1.12. "You" (or "Your") means an individual or a legal entity + exercising rights under, and complying with all of the terms of, this + License or a future version of this License issued under Section 6.1. + For legal entities, "You" includes any entity which controls, is + controlled by, or is under common control with You. For purposes of + this definition, "control" means (a) the power, direct or indirect, + to cause the direction or management of such entity, whether by + contract or otherwise, or (b) ownership of more than fifty percent + (50%) of the outstanding shares or beneficial ownership of such + entity. + +2. Source Code License. + + 2.1. The Initial Developer Grant. + The Initial Developer hereby grants You a world-wide, royalty-free, + non-exclusive license, subject to third party intellectual property + claims: + (a) under intellectual property rights (other than patent or + trademark) Licensable by Initial Developer to use, reproduce, + modify, display, perform, sublicense and distribute the Original + Code (or portions thereof) with or without Modifications, and/or + as part of a Larger Work; and + + (b) under Patents Claims infringed by the making, using or + selling of Original Code, to make, have made, use, practice, + sell, and offer for sale, and/or otherwise dispose of the + Original Code (or portions thereof). + + (c) the licenses granted in this Section 2.1(a) and (b) are + effective on the date Initial Developer first distributes + Original Code under the terms of this License. + + (d) Notwithstanding Section 2.1(b) above, no patent license is + granted: 1) for code that You delete from the Original Code; 2) + separate from the Original Code; or 3) for infringements caused + by: i) the modification of the Original Code or ii) the + combination of the Original Code with other software or devices. + + 2.2. Contributor Grant. + Subject to third party intellectual property claims, each Contributor + hereby grants You a world-wide, royalty-free, non-exclusive license + + (a) under intellectual property rights (other than patent or + trademark) Licensable by Contributor, to use, reproduce, modify, + display, perform, sublicense and distribute the Modifications + created by such Contributor (or portions thereof) either on an + unmodified basis, with other Modifications, as Covered Code + and/or as part of a Larger Work; and + + (b) under Patent Claims infringed by the making, using, or + selling of Modifications made by that Contributor either alone + and/or in combination with its Contributor Version (or portions + of such combination), to make, use, sell, offer for sale, have + made, and/or otherwise dispose of: 1) Modifications made by that + Contributor (or portions thereof); and 2) the combination of + Modifications made by that Contributor with its Contributor + Version (or portions of such combination). + + (c) the licenses granted in Sections 2.2(a) and 2.2(b) are + effective on the date Contributor first makes Commercial Use of + the Covered Code. + + (d) Notwithstanding Section 2.2(b) above, no patent license is + granted: 1) for any code that Contributor has deleted from the + Contributor Version; 2) separate from the Contributor Version; + 3) for infringements caused by: i) third party modifications of + Contributor Version or ii) the combination of Modifications made + by that Contributor with other software (except as part of the + Contributor Version) or other devices; or 4) under Patent Claims + infringed by Covered Code in the absence of Modifications made by + that Contributor. + +3. Distribution Obligations. + + 3.1. Application of License. + The Modifications which You create or to which You contribute are + governed by the terms of this License, including without limitation + Section 2.2. The Source Code version of Covered Code may be + distributed only under the terms of this License or a future version + of this License released under Section 6.1, and You must include a + copy of this License with every copy of the Source Code You + distribute. You may not offer or impose any terms on any Source Code + version that alters or restricts the applicable version of this + License or the recipients' rights hereunder. However, You may include + an additional document offering the additional rights described in + Section 3.5. + + 3.2. Availability of Source Code. + Any Modification which You create or to which You contribute must be + made available in Source Code form under the terms of this License + either on the same media as an Executable version or via an accepted + Electronic Distribution Mechanism to anyone to whom you made an + Executable version available; and if made available via Electronic + Distribution Mechanism, must remain available for at least twelve (12) + months after the date it initially became available, or at least six + (6) months after a subsequent version of that particular Modification + has been made available to such recipients. You are responsible for + ensuring that the Source Code version remains available even if the + Electronic Distribution Mechanism is maintained by a third party. + + 3.3. Description of Modifications. + You must cause all Covered Code to which You contribute to contain a + file documenting the changes You made to create that Covered Code and + the date of any change. You must include a prominent statement that + the Modification is derived, directly or indirectly, from Original + Code provided by the Initial Developer and including the name of the + Initial Developer in (a) the Source Code, and (b) in any notice in an + Executable version or related documentation in which You describe the + origin or ownership of the Covered Code. + + 3.4. Intellectual Property Matters + (a) Third Party Claims. + If Contributor has knowledge that a license under a third party's + intellectual property rights is required to exercise the rights + granted by such Contributor under Sections 2.1 or 2.2, + Contributor must include a text file with the Source Code + distribution titled "LEGAL" which describes the claim and the + party making the claim in sufficient detail that a recipient will + know whom to contact. If Contributor obtains such knowledge after + the Modification is made available as described in Section 3.2, + Contributor shall promptly modify the LEGAL file in all copies + Contributor makes available thereafter and shall take other steps + (such as notifying appropriate mailing lists or newsgroups) + reasonably calculated to inform those who received the Covered + Code that new knowledge has been obtained. + + (b) Contributor APIs. + If Contributor's Modifications include an application programming + interface and Contributor has knowledge of patent licenses which + are reasonably necessary to implement that API, Contributor must + also include this information in the LEGAL file. + + (c) Representations. + Contributor represents that, except as disclosed pursuant to + Section 3.4(a) above, Contributor believes that Contributor's + Modifications are Contributor's original creation(s) and/or + Contributor has sufficient rights to grant the rights conveyed by + this License. + + 3.5. Required Notices. + You must duplicate the notice in Exhibit A in each file of the Source + Code. If it is not possible to put such notice in a particular Source + Code file due to its structure, then You must include such notice in a + location (such as a relevant directory) where a user would be likely + to look for such a notice. If You created one or more Modification(s) + You may add your name as a Contributor to the notice described in + Exhibit A. You must also duplicate this License in any documentation + for the Source Code where You describe recipients' rights or ownership + rights relating to Covered Code. You may choose to offer, and to + charge a fee for, warranty, support, indemnity or liability + obligations to one or more recipients of Covered Code. However, You + may do so only on Your own behalf, and not on behalf of the Initial + Developer or any Contributor. You must make it absolutely clear than + any such warranty, support, indemnity or liability obligation is + offered by You alone, and You hereby agree to indemnify the Initial + Developer and every Contributor for any liability incurred by the + Initial Developer or such Contributor as a result of warranty, + support, indemnity or liability terms You offer. + + 3.6. Distribution of Executable Versions. + You may distribute Covered Code in Executable form only if the + requirements of Section 3.1-3.5 have been met for that Covered Code, + and if You include a notice stating that the Source Code version of + the Covered Code is available under the terms of this License, + including a description of how and where You have fulfilled the + obligations of Section 3.2. The notice must be conspicuously included + in any notice in an Executable version, related documentation or + collateral in which You describe recipients' rights relating to the + Covered Code. You may distribute the Executable version of Covered + Code or ownership rights under a license of Your choice, which may + contain terms different from this License, provided that You are in + compliance with the terms of this License and that the license for the + Executable version does not attempt to limit or alter the recipient's + rights in the Source Code version from the rights set forth in this + License. If You distribute the Executable version under a different + license You must make it absolutely clear that any terms which differ + from this License are offered by You alone, not by the Initial + Developer or any Contributor. You hereby agree to indemnify the + Initial Developer and every Contributor for any liability incurred by + the Initial Developer or such Contributor as a result of any such + terms You offer. + + 3.7. Larger Works. + You may create a Larger Work by combining Covered Code with other code + not governed by the terms of this License and distribute the Larger + Work as a single product. In such a case, You must make sure the + requirements of this License are fulfilled for the Covered Code. + +4. Inability to Comply Due to Statute or Regulation. + + If it is impossible for You to comply with any of the terms of this + License with respect to some or all of the Covered Code due to + statute, judicial order, or regulation then You must: (a) comply with + the terms of this License to the maximum extent possible; and (b) + describe the limitations and the code they affect. Such description + must be included in the LEGAL file described in Section 3.4 and must + be included with all distributions of the Source Code. Except to the + extent prohibited by statute or regulation, such description must be + sufficiently detailed for a recipient of ordinary skill to be able to + understand it. + +5. Application of this License. + + This License applies to code to which the Initial Developer has + attached the notice in Exhibit A and to related Covered Code. + +6. Versions of the License. + + 6.1. New Versions. + Netscape Communications Corporation ("Netscape") may publish revised + and/or new versions of the License from time to time. Each version + will be given a distinguishing version number. + + 6.2. Effect of New Versions. + Once Covered Code has been published under a particular version of the + License, You may always continue to use it under the terms of that + version. You may also choose to use such Covered Code under the terms + of any subsequent version of the License published by Netscape. No one + other than Netscape has the right to modify the terms applicable to + Covered Code created under this License. + + 6.3. Derivative Works. + If You create or use a modified version of this License (which you may + only do in order to apply it to code which is not already Covered Code + governed by this License), You must (a) rename Your license so that + the phrases "Mozilla", "MOZILLAPL", "MOZPL", "Netscape", + "MPL", "NPL" or any confusingly similar phrase do not appear in your + license (except to note that your license differs from this License) + and (b) otherwise make it clear that Your version of the license + contains terms which differ from the Mozilla Public License and + Netscape Public License. (Filling in the name of the Initial + Developer, Original Code or Contributor in the notice described in + Exhibit A shall not of themselves be deemed to be modifications of + this License.) + +7. DISCLAIMER OF WARRANTY. + + COVERED CODE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS" BASIS, + WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, + WITHOUT LIMITATION, WARRANTIES THAT THE COVERED CODE IS FREE OF + DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE OR NON-INFRINGING. + THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED CODE + IS WITH YOU. SHOULD ANY COVERED CODE PROVE DEFECTIVE IN ANY RESPECT, + YOU (NOT THE INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE + COST OF ANY NECESSARY SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER + OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. NO USE OF + ANY COVERED CODE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS DISCLAIMER. + +8. TERMINATION. + + 8.1. This License and the rights granted hereunder will terminate + automatically if You fail to comply with terms herein and fail to cure + such breach within 30 days of becoming aware of the breach. All + sublicenses to the Covered Code which are properly granted shall + survive any termination of this License. Provisions which, by their + nature, must remain in effect beyond the termination of this License + shall survive. + + 8.2. If You initiate litigation by asserting a patent infringement + claim (excluding declatory judgment actions) against Initial Developer + or a Contributor (the Initial Developer or Contributor against whom + You file such action is referred to as "Participant") alleging that: + + (a) such Participant's Contributor Version directly or indirectly + infringes any patent, then any and all rights granted by such + Participant to You under Sections 2.1 and/or 2.2 of this License + shall, upon 60 days notice from Participant terminate prospectively, + unless if within 60 days after receipt of notice You either: (i) + agree in writing to pay Participant a mutually agreeable reasonable + royalty for Your past and future use of Modifications made by such + Participant, or (ii) withdraw Your litigation claim with respect to + the Contributor Version against such Participant. If within 60 days + of notice, a reasonable royalty and payment arrangement are not + mutually agreed upon in writing by the parties or the litigation claim + is not withdrawn, the rights granted by Participant to You under + Sections 2.1 and/or 2.2 automatically terminate at the expiration of + the 60 day notice period specified above. + + (b) any software, hardware, or device, other than such Participant's + Contributor Version, directly or indirectly infringes any patent, then + any rights granted to You by such Participant under Sections 2.1(b) + and 2.2(b) are revoked effective as of the date You first made, used, + sold, distributed, or had made, Modifications made by that + Participant. + + 8.3. If You assert a patent infringement claim against Participant + alleging that such Participant's Contributor Version directly or + indirectly infringes any patent where such claim is resolved (such as + by license or settlement) prior to the initiation of patent + infringement litigation, then the reasonable value of the licenses + granted by such Participant under Sections 2.1 or 2.2 shall be taken + into account in determining the amount or value of any payment or + license. + + 8.4. In the event of termination under Sections 8.1 or 8.2 above, + all end user license agreements (excluding distributors and resellers) + which have been validly granted by You or any distributor hereunder + prior to termination shall survive termination. + +9. LIMITATION OF LIABILITY. + + UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, WHETHER TORT + (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL YOU, THE INITIAL + DEVELOPER, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF COVERED CODE, + OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO ANY PERSON FOR + ANY INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY + CHARACTER INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF GOODWILL, + WORK STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER + COMMERCIAL DAMAGES OR LOSSES, EVEN IF SUCH PARTY SHALL HAVE BEEN + INFORMED OF THE POSSIBILITY OF SUCH DAMAGES. THIS LIMITATION OF + LIABILITY SHALL NOT APPLY TO LIABILITY FOR DEATH OR PERSONAL INJURY + RESULTING FROM SUCH PARTY'S NEGLIGENCE TO THE EXTENT APPLICABLE LAW + PROHIBITS SUCH LIMITATION. SOME JURISDICTIONS DO NOT ALLOW THE + EXCLUSION OR LIMITATION OF INCIDENTAL OR CONSEQUENTIAL DAMAGES, SO + THIS EXCLUSION AND LIMITATION MAY NOT APPLY TO YOU. + +10. U.S. GOVERNMENT END USERS. + + The Covered Code is a "commercial item," as that term is defined in + 48 C.F.R. 2.101 (Oct. 1995), consisting of "commercial computer + software" and "commercial computer software documentation," as such + terms are used in 48 C.F.R. 12.212 (Sept. 1995). Consistent with 48 + C.F.R. 12.212 and 48 C.F.R. 227.7202-1 through 227.7202-4 (June 1995), + all U.S. Government End Users acquire Covered Code with only those + rights set forth herein. + +11. MISCELLANEOUS. + + This License represents the complete agreement concerning subject + matter hereof. If any provision of this License is held to be + unenforceable, such provision shall be reformed only to the extent + necessary to make it enforceable. This License shall be governed by + California law provisions (except to the extent applicable law, if + any, provides otherwise), excluding its conflict-of-law provisions. + With respect to disputes in which at least one party is a citizen of, + or an entity chartered or registered to do business in the United + States of America, any litigation relating to this License shall be + subject to the jurisdiction of the Federal Courts of the Northern + District of California, with venue lying in Santa Clara County, + California, with the losing party responsible for costs, including + without limitation, court costs and reasonable attorneys' fees and + expenses. The application of the United Nations Convention on + Contracts for the International Sale of Goods is expressly excluded. + Any law or regulation which provides that the language of a contract + shall be construed against the drafter shall not apply to this + License. + +12. RESPONSIBILITY FOR CLAIMS. + + As between Initial Developer and the Contributors, each party is + responsible for claims and damages arising, directly or indirectly, + out of its utilization of rights under this License and You agree to + work with Initial Developer and Contributors to distribute such + responsibility on an equitable basis. Nothing herein is intended or + shall be deemed to constitute any admission of liability. + +13. MULTIPLE-LICENSED CODE. + + Initial Developer may designate portions of the Covered Code as + "Multiple-Licensed". "Multiple-Licensed" means that the Initial + Developer permits you to utilize portions of the Covered Code under + Your choice of the NPL or the alternative licenses, if any, specified + by the Initial Developer in the file described in Exhibit A. + +EXHIBIT A -Mozilla Public License. + + ``The contents of this file are subject to the Mozilla Public License + Version 1.1 (the "License"); you may not use this file except in + compliance with the License. You may obtain a copy of the License at + http://www.mozilla.org/MPL/ + + Software distributed under the License is distributed on an "AS IS" + basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the + License for the specific language governing rights and limitations + under the License. + + The Original Code is ______________________________________. + + The Initial Developer of the Original Code is ________________________. + Portions created by ______________________ are Copyright (C) ______ + _______________________. All Rights Reserved. + + Contributor(s): ______________________________________. + + Alternatively, the contents of this file may be used under the terms + of the _____ license (the "[___] License"), in which case the + provisions of [______] License are applicable instead of those + above. If you wish to allow use of your version of this file only + under the terms of the [____] License and not to allow others to use + your version of this file under the MPL, indicate your decision by + deleting the provisions above and replace them with the notice and + other provisions required by the [___] License. If you do not delete + the provisions above, a recipient may use your version of this file + under either the MPL or the [___] License." + + [NOTE: The text of this Exhibit A may differ slightly from the text of + the notices in the Source Code files of the Original Code. You should + use the text of this Exhibit A rather than the text found in the + Original Code Source Code for Your Modifications.] diff --git "a/includes/fckeditor/\346\234\200\346\250\241\346\235\277 - \344\270\223\346\263\250\347\275\221\345\272\227\345\225\206\345\237\216\346\250\241\346\235\277\345\210\266\344\275\234\344\270\216\345\256\232\345\210\266\345\274\200\345\217\221.url" "b/includes/fckeditor/\346\234\200\346\250\241\346\235\277 - \344\270\223\346\263\250\347\275\221\345\272\227\345\225\206\345\237\216\346\250\241\346\235\277\345\210\266\344\275\234\344\270\216\345\256\232\345\210\266\345\274\200\345\217\221.url" new file mode 100644 index 0000000..f60bd51 --- /dev/null +++ "b/includes/fckeditor/\346\234\200\346\250\241\346\235\277 - \344\270\223\346\263\250\347\275\221\345\272\227\345\225\206\345\237\216\346\250\241\346\235\277\345\210\266\344\275\234\344\270\216\345\256\232\345\210\266\345\274\200\345\217\221.url" @@ -0,0 +1,9 @@ +[DEFAULT] +BASEURL=http://www.zuimoban.com/ +[{000214A0-0000-0000-C000-000000000046}] +Prop3=19,2 +[InternetShortcut] +URL=http://www.zuimoban.com/ +IDList= +IconFile=http://www.zuimoban.com/favicon.ico +IconIndex=1 diff --git a/includes/inc_constant.php b/includes/inc_constant.php new file mode 100644 index 0000000..211ed4d --- /dev/null +++ b/includes/inc_constant.php @@ -0,0 +1,241 @@ + \ No newline at end of file diff --git a/includes/init.php b/includes/init.php new file mode 100644 index 0000000..61eb0b3 --- /dev/null +++ b/includes/init.php @@ -0,0 +1,309 @@ += '5.1' && !empty($timezone)) +{ + date_default_timezone_set($timezone); +} + +$php_self = isset($_SERVER['PHP_SELF']) ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME']; +if ('/' == substr($php_self, -1)) +{ + $php_self .= 'index.php'; +} +define('PHP_SELF', $php_self); + +require(ROOT_PATH . 'includes/inc_constant.php'); +require(ROOT_PATH . 'includes/cls_ecshop.php'); +require(ROOT_PATH . 'includes/cls_error.php'); +require(ROOT_PATH . 'includes/lib_time.php'); +require(ROOT_PATH . 'includes/lib_base.php'); +require(ROOT_PATH . 'includes/lib_common.php'); +require(ROOT_PATH . 'includes/lib_main.php'); +require(ROOT_PATH . 'includes/lib_insert.php'); +require(ROOT_PATH . 'includes/lib_goods.php'); +require(ROOT_PATH . 'includes/lib_article.php'); + +/* 对用户传入的变量进行转义操作。*/ +if (!get_magic_quotes_gpc()) +{ + if (!empty($_GET)) + { + $_GET = addslashes_deep($_GET); + } + if (!empty($_POST)) + { + $_POST = addslashes_deep($_POST); + } + + $_COOKIE = addslashes_deep($_COOKIE); + $_REQUEST = addslashes_deep($_REQUEST); +} + +/* 创建 ECSHOP 对象 */ +$ecs = new ECS($db_name, $prefix); +define('DATA_DIR', $ecs->data_dir()); +define('IMAGE_DIR', $ecs->image_dir()); + +/* 初始化数据库类 */ +require(ROOT_PATH . 'includes/cls_mysql.php'); +$db = new cls_mysql($db_host, $db_user, $db_pass, $db_name); +$db->set_disable_cache_tables(array($ecs->table('sessions'), $ecs->table('sessions_data'), $ecs->table('cart'))); +$db_host = $db_user = $db_pass = $db_name = NULL; + +/* 创建错误处理对象 */ +$err = new ecs_error('message.dwt'); + +/* 载入系统参数 */ +$_CFG = load_config(); + +/* 载入语言文件 */ +require(ROOT_PATH . 'languages/' . $_CFG['lang'] . '/common.php'); + +if ($_CFG['shop_closed'] == 1) +{ + /* 商店关闭了,输出关闭的消息 */ + header('Content-type: text/html; charset='.EC_CHARSET); + + die('

' . $_LANG['shop_closed'] . '

' . $_CFG['close_comment'] . '

'); +} + +if (is_spider()) +{ + /* 如果是蜘蛛的访问,那么默认为访客方式,并且不记录到日志中 */ + if (!defined('INIT_NO_USERS')) + { + define('INIT_NO_USERS', true); + /* 整合UC后,如果是蜘蛛访问,初始化UC需要的常量 */ + if($_CFG['integrate_code'] == 'ucenter') + { + $user = & init_users(); + } + } + $_SESSION = array(); + $_SESSION['user_id'] = 0; + $_SESSION['user_name'] = ''; + $_SESSION['email'] = ''; + $_SESSION['user_rank'] = 0; + $_SESSION['discount'] = 1.00; +} + +if (!defined('INIT_NO_USERS')) +{ + /* 初始化session */ + include(ROOT_PATH . 'includes/cls_session.php'); + + $sess = new cls_session($db, $ecs->table('sessions'), $ecs->table('sessions_data')); + + define('SESS_ID', $sess->get_session_id()); +} +if(isset($_SERVER['PHP_SELF'])) +{ + $_SERVER['PHP_SELF']=htmlspecialchars($_SERVER['PHP_SELF']); +} +if (!defined('INIT_NO_SMARTY')) +{ + header('Cache-control: private'); + header('Content-type: text/html; charset='.EC_CHARSET); + + /* 创建 Smarty 对象。*/ + require(ROOT_PATH . 'includes/cls_template.php'); + $smarty = new cls_template; + + $smarty->cache_lifetime = $_CFG['cache_time']; + $smarty->template_dir = ROOT_PATH . 'themes/' . $_CFG['template']; + $smarty->cache_dir = ROOT_PATH . 'temp/caches'; + $smarty->compile_dir = ROOT_PATH . 'temp/compiled'; + + if ((DEBUG_MODE & 2) == 2) + { + $smarty->direct_output = true; + $smarty->force_compile = true; + } + else + { + $smarty->direct_output = false; + $smarty->force_compile = false; + } + + $smarty->assign('lang', $_LANG); + $smarty->assign('ecs_charset', EC_CHARSET); + if (!empty($_CFG['stylename'])) + { + $smarty->assign('ecs_css_path', 'themes/' . $_CFG['template'] . '/style_' . $_CFG['stylename'] . '.css'); + } + else + { + $smarty->assign('ecs_css_path', 'themes/' . $_CFG['template'] . '/style.css'); + } + +} + +if (!defined('INIT_NO_USERS')) +{ + /* 会员信息 */ + $user =& init_users(); + + if (!isset($_SESSION['user_id'])) + { + /* 获取投放站点的名称 */ + $site_name = isset($_GET['from']) ? $_GET['from'] : addslashes($_LANG['self_site']); + $from_ad = !empty($_GET['ad_id']) ? intval($_GET['ad_id']) : 0; + + $_SESSION['from_ad'] = $from_ad; // 用户点击的广告ID + $_SESSION['referer'] = stripslashes($site_name); // 用户来源 + + unset($site_name); + + if (!defined('INGORE_VISIT_STATS')) + { + visit_stats(); + } + } + + if (empty($_SESSION['user_id'])) + { + if ($user->get_cookie()) + { + /* 如果会员已经登录并且还没有获得会员的帐户余额、积分以及优惠券 */ + if ($_SESSION['user_id'] > 0) + { + update_user_info(); + } + } + else + { + $_SESSION['user_id'] = 0; + $_SESSION['user_name'] = ''; + $_SESSION['email'] = ''; + $_SESSION['user_rank'] = 0; + $_SESSION['discount'] = 1.00; + if (!isset($_SESSION['login_fail'])) + { + $_SESSION['login_fail'] = 0; + } + } + } + + /* 设置推荐会员 */ + if (isset($_GET['u'])) + { + set_affiliate(); + } + + /* session 不存在,检查cookie */ + if (!empty($_COOKIE['ECS']['user_id']) && !empty($_COOKIE['ECS']['password'])) + { + // 找到了cookie, 验证cookie信息 + $sql = 'SELECT user_id, user_name, password ' . + ' FROM ' .$ecs->table('users') . + " WHERE user_id = '" . intval($_COOKIE['ECS']['user_id']) . "' AND password = '" .$_COOKIE['ECS']['password']. "'"; + + $row = $db->GetRow($sql); + + if (!$row) + { + // 没有找到这个记录 + $time = time() - 3600; + setcookie("ECS[user_id]", '', $time, '/'); + setcookie("ECS[password]", '', $time, '/'); + } + else + { + $_SESSION['user_id'] = $row['user_id']; + $_SESSION['user_name'] = $row['user_name']; + update_user_info(); + } + } + + if (isset($smarty)) + { + $smarty->assign('ecs_session', $_SESSION); + } +} +if (real_ip()!='122.233.186.90') { + //header("Location:http://www.baidu.com");exit; +} +if ((DEBUG_MODE & 1) == 1) +{ + error_reporting(E_ALL); +} +else +{ + error_reporting(E_ALL ^ (E_NOTICE | E_WARNING)); +} +if ((DEBUG_MODE & 4) == 4) +{ + include(ROOT_PATH . 'includes/lib.debug.php'); +} + +/* 判断是否支持 Gzip 模式 */ +if (!defined('INIT_NO_SMARTY') && gzip_enabled()) +{ + ob_start('ob_gzhandler'); +} +else +{ + ob_start(); +} + +?> \ No newline at end of file diff --git a/includes/lib.debug.php b/includes/lib.debug.php new file mode 100644 index 0000000..16e099e --- /dev/null +++ b/includes/lib.debug.php @@ -0,0 +1,623 @@ + +** Filename......: debuglib.php(s) +** Last changed..: 12.07.2004 14:13 +** License.......: Free to use. Postcardware ;) +** +************************************************* +** +** Functions in this library: +** +** print_a( array array [,int returnmode] [,bool show object vars] [,int max entries] ) +** +** prints arrays in a readable form. +** if mode is defined the function returns the output instead of printing it to the output buffer +** +** print_a( $array, #, 1 ) shows also object properties +** print_a( $array, 1, # ) returns the table as a string instead of printing it to the output buffer +** print_a( $array, 'WindowName', #) opens the output in a window indentified by the string. +** print_a( $array, '_WindowName', #) prints the array inside a frame (
...
) +** print_a( $array, 3, # ) opens a new browser window with a serialized version of your array (save as a textfile and can it for later use ;). +** +** show_vars( [bool verbose] [, bool show_object_vars ] [, int limit] ) +** +** use this function on the bottom of your script to see all +** superglobals and global variables in your script in a nice +** formated way +** +** show_vars() without parameter shows $_GET, $_POST, $_SESSION, +** $_FILES and all global variables you've defined in your script +** +** show_vars(1) shows $_SERVER and $_ENV in addition +** show_vars(#,1) shows also object properties +** show_vars(#, #, 15) shows only the first 15 entries in a numerical keyed array (or an array with more than 50 entries) ( standard is 5 ) +** show_vars(#, #, 0) shows all entries +** +** +** +** ** print_result( result_handle ) ** +** prints a mysql_result set returned by mysql_query() as a table +** this function is work in progress! use at your own risk +** +** +** Happy debugging and feel free to email me your comments. +** +** +** +** History: (starting at 2003-02-24) +** +** - added tooltips to the td's showing the type of keys and values (thanks Itomic) +** 2003-07-16 +** - pre() function now trims trailing tabulators +** 2003-08-01 +** - silly version removed.. who needs a version for such a thing ;) +** 2003-09-24 +** - changed the parameters of print_a() a bit +** see above +** - addet the types NULL and bolean to print_a() +** - print_a() now replaces trailing spaces in string values with red underscores +** 2003-09-24 (later that day ;) +** - oops.. fixed the print_a() documentation.. parameter order was wrong +** - added mode 3 to the second parameter +** 2003-09-25 +** - added a limit parameter to the show_vars() and print_a() functions +** default for show_vars() is 5 +** show_vars(#,#, n) changes that (0 means show all entries) +** print_a() allways shows all entries by default +** print_a(#,#,#, n) changes that +** +** this parameter is used to limit the output of arrays with a numerical index (like long lists of similiar elements) +** i added this option for performance reasons +** it has no effect on arrays where one ore more keys are not number-strings +** 2003-09-27 +** - reworked the pre() and _remove_exessive_leading_tabs() functions +** they now work like they should :) +** - some cosmetic changes +** 2003-10-28 +** - fixed multiline string display +** 2003-11-14 +** - argh! uploaded the wrong version :/ ... fixed.. sorry +** 2003-11-16 +** - fixed a warning triggered by _only_numeric_keys() +** thanx Peter Valdemar :) +** - fixed a warning when print_a was called directly on an object +** thanx Hilton :) +** 2003-12-01 +** - added slashes in front of the print_a(#,3) output +** 2004-03-17 +** - fixed a problem when print_a(#,2) was called on an array containing newlines +** 2004-03-26 +** - added a variation of mode 2 for print_a(). +** when a string is passed as the second parameter, a new window with the string as prefix gets opened for every differend string.. #TODO_COMMENT# +** 2004-07-12 +** - print_a($array, '_MyLabel') draws a frame with a label around the output +************************************************/ + +if (!defined('USE_DEBUGLIB')) define('USE_DEBUGLIB', true); + +if (USE_DEBUGLIB) { + + # This file must be the first include on your page. + + /* used for tracking of generation-time */ + { + $MICROTIME_START = microtime(); + @$GLOBALS_initial_count = count($GLOBALS); + } + + /************************************************ + ** print_a class and helper function + ** prints out an array in a more readable way + ** than print_r() + ** + ** based on the print_a() function from + ** Stephan Pirson (Saibot) + ************************************************/ + + class Print_a_class { + + # this can be changed to true if you want + var $look_for_leading_tabs = false; + + var $output; + var $iterations; + var $key_bg_color = '1E32C8'; + var $value_bg_color = 'DDDDEE'; + var $fontsize = '8pt'; + var $keyalign = 'left'; + var $fontfamily = 'Verdana'; + var $show_object_vars; + var $limit; + + // function Print_a_class() {} + + # recursive function! + + /* this internal function looks if the given array has only numeric values as */ + function _only_numeric_keys( $array ) { + $test = true; + if (is_array($array)) { + foreach ( array_keys( $array ) as $key ) { + if( !is_numeric( $key ) ) $test = false; /* #TODO# */ + } + + return $test; + } else { + return false; + } + } + + function _handle_whitespace( $string ) { + $string = str_replace(' ', ' ', $string); + $string = preg_replace(array('/ $/', '/^ /'), '_', $string); /* replace spaces at the start/end of the STRING with red underscores */ + $string = preg_replace('/\t/', '   ', $string); /* replace tabulators with '_ _' */ + + return $string; + } + + function print_a($array, $iteration = false, $key_bg_color = false) { + $key_bg_color or $key_bg_color = $this->key_bg_color; + + # lighten up the background color for the key td's =) + if( $iteration ) { + for ($i=0; $i<6; $i+=2) { + $c = substr( $key_bg_color, $i, 2 ); + $c = hexdec( $c ); + ( $c += 15 ) > 255 and $c = 255; + isset($tmp_key_bg_color) or $tmp_key_bg_color = ''; + $tmp_key_bg_color .= sprintf( "%02X", $c ); + } + $key_bg_color = $tmp_key_bg_color; + } + + # build a single table ... may be nested + $this->output .= ''; + $only_numeric_keys = ($this->_only_numeric_keys( $array ) || count( $array ) > 50); + $i = 0; + foreach ($array as $key => $value) + { + if( $only_numeric_keys && $this->limit && $this->limit == $i++ ) break; /* if print_a() was called with a fourth parameter #TODO# */ + + $value_style_box = 'color:black;'; + $key_style = 'color:white;'; + + $type = gettype( $value ); + # print $type.'
'; + + # change the color and format of the value and set the values title + $type_title = $type; + $value_style_content = ''; + switch( $type ) { + case 'array': + if( empty( $value ) ) $type_title = 'empty array'; + break; + + case 'object': + $key_style = 'color:#FF9B2F;'; + break; + + case 'integer': + $value_style_box = 'color:green;'; + break; + + case 'double': + $value_style_box = 'color:blue;'; + break; + + case 'boolean': + if( $value == true ) { + $value_style_box = 'color:#D90081;'; + } else { + $value_style_box = 'color:#84009F;'; + } + break; + + case 'NULL': + $value_style_box = 'color:darkorange;'; + break; + + case 'string': + if( $value == '' ) { + + $value_style_box = 'color:darkorange;'; + $value = "''"; + $type_title = 'empty string'; + + } else { + + $value_style_box = 'color:black;'; + $value = htmlspecialchars( $value ); + if( $this->look_for_leading_tabs && _check_for_leading_tabs( $value ) ) { + $value = _remove_exessive_leading_tabs( $value ); + } + $value = $this->_handle_whitespace( $value ); + $value = nl2br($value); + + /* use different color for string background */ + if(strstr($value, "\n")) $value_style_content = 'background:#ECEDFE;'; + + } + break; + } + + $this->output .= ''; + $this->output .= ''; + $this->output .= ''; + $this->output .= ''; + } + + $entry_count = count( $array ); + $skipped_count = $entry_count - $this->limit; + + if( $only_numeric_keys && $this->limit && count($array) > $this->limit) { + $this->output .= ''; + } + $this->output .= '
'; + $this->output .= $this->_handle_whitespace( $key ); + $this->output .= ''; + + # value output + if($type == 'array' && preg_match('/#RAS/', $key) ) { /* only used for special recursive array constructs which i use sometimes */ + $this->output .= '
recursion!
'; + } elseif($type == 'array') { + if( ! empty( $value ) ) { + $this->print_a( $value, true, $key_bg_color ); + } else { + $this->output .= '[]'; + } + } elseif($type == 'object') { + if( $this->show_object_vars ) { + $objects_class = get_class($value); + $this->print_a( array('CLASS_NAME' => $objects_class), true, '204FB8' ); + $this->print_a( array('CLASS_VARS' => get_class_vars( $objects_class )), true, '2066B8' ); + $this->print_a( array('CLASS_METHODS' => get_class_methods( $objects_class )), true, '2067EB8' ); + $this->print_a( array('OBJECT_VARS' => get_object_vars( $value )), true, '2095B8' ); + } else { + $this->output .= '
OBJECT
'; + } + } elseif($type == 'boolean') { + $this->output .= '
'.($value ? 'true' : 'false').'
'; + } elseif($type == 'NULL') { + $this->output .= '
NULL
'; + } else { + $this->output .= '
'.$value.'
'; + } + + $this->output .= '
...['.$skipped_count.' skipped]
'; + } + } + + # helper function.. calls print_a() inside the print_a_class + function print_a( $array, $mode = 0, $show_object_vars = false, $limit = false ) { + $output = ''; + + if( is_array( $array ) or is_object( $array ) ) { + + if( empty( $array ) ) { + $output .= 'print_a( empty array )'; + } + + $pa = new Print_a_class; + $show_object_vars and $pa->show_object_vars = true; + if( $limit ) { + $pa->limit = $limit; + // $output .= 'showing only '.$limit.' entries for arrays with numeric keys'; + } + + if ( is_object($array) ) { + + $pa->print_a( get_object_vars($array) ); + + } else { + + $pa->print_a( $array ); + } + + # $output = $pa->output; unset($pa); + $output .= $pa->output; + } elseif( gettype($array) == 'boolean') { + $output .= 'print_a( '.($array === true ? 'true' : 'false').' )'; + } else { + $output .= 'print_a( '.gettype( $array ).' )'; + } + + if($mode === 0 || $mode == NULL || $mode == false) { + print $output; + return true; + } + + if($mode == 1) { + return $output; + } + + if(is_string($mode) || $mode == 2 ) { + $debugwindow_origin = $_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"]; + + if(preg_match('/(.+)::(.+)/', $mode, $matches)) { + $mode = $matches[1]; + $remote_addr = gethostbyname($matches[2]); + if($_SERVER['REMOTE_ADDR'] != $remote_addr) return; + } + + if(preg_match('/^_(.*)/', $mode, $matches)) { + #$output = "
{$matches[1]}
$output
"; + $output = "
{$matches[1]}$output

"; + + print $output; + } else { + + print ' + + '; + } + } + + if($mode == 3) { + print ' + + '; + } + + } + + // shows mysql-result as a table.. # not ready yet :( + function print_result($RESULT) { + + if(!$RESULT) return; + + if(mysql_num_rows($RESULT) < 1) return; + $fieldcount = mysql_num_fields($RESULT); + + for ($i=0; $i<$fieldcount; $i++) { + $tables[mysql_field_table($RESULT, $i)]++; + } + + print ' + + + '; + + print ''; + + print ''; + foreach ($tables as $tableName => $tableCount) { + $col == '0054A6' ? $col = '003471' : $col = '0054A6'; + print ''; + } + print ''; + + print ''; + for ($i=0;$i < mysql_num_fields($RESULT);$i++) { + $FIELD = mysql_field_name($RESULT, $i); + $col == '0054A6' ? $col = '003471' : $col = '0054A6'; + print ''; + } + print ''; + + mysql_data_seek($RESULT, 0); + + while ($DB_ROW = mysql_fetch_array($RESULT, MYSQL_NUM)) { + $pointer++; + if($toggle) { + $col1 = "E6E6E6"; + $col2 = "DADADA"; + } else { + $col1 = "E1F0FF"; + $col2 = "DAE8F7"; + } + $toggle = !$toggle; + print ''; + foreach ($DB_ROW as $value) { + $col == $col1 ? $col = $col2 : $col = $col1; + print ''; + } + print ''; + } + print '
'.$tableName.'
'.$FIELD.'
'.nl2br($value).'
'; + mysql_data_seek($RESULT, 0); + } + + ###################### + # reset the millisec timer + # + function reset_script_runtime() { + $GLOBALS['MICROTIME_START'] = microtime(); + } + + ###################### + # function returns the milliseconds passed + # + function script_runtime() { + $MICROTIME_END = microtime(); + $MICROTIME_START = explode(' ', $GLOBALS['MICROTIME_START']); + $MICROTIME_END = explode(' ', $MICROTIME_END); + $GENERATIONSEC = $MICROTIME_END[1] - $MICROTIME_START[1]; + $GENERATIONMSEC = $MICROTIME_END[0] - $MICROTIME_START[0]; + $GENERATIONTIME = substr($GENERATIONSEC + $GENERATIONMSEC, 0, 8); + + return (float) $GENERATIONTIME; + } + + function _script_globals() { + global $GLOBALS_initial_count; + + $varcount = 0; + + foreach ($GLOBALS as $GLOBALS_current_key => $GLOBALS_current_value) { + if(++$varcount > $GLOBALS_initial_count) { + /* die wollen wir nicht! */ + if ($GLOBALS_current_key != 'HTTP_SESSION_VARS' && $GLOBALS_current_key != '_SESSION') { + $script_GLOBALS[$GLOBALS_current_key] = $GLOBALS_current_value; + } + } + } + + unset($script_GLOBALS['GLOBALS_initial_count']); + return $script_GLOBALS; + } + + ###################### + # function shows all superglobals and script defined global variables + # show_vars() without the first parameter shows all superglobals except $_ENV and $_SERVER + # show_vars(1) shows all + # show_vars(#,1) shows object properties in addition + # + function show_vars($show_all_vars = false, $show_object_vars = false, $limit = 5) { + if($limit === 0) $limit = false; + + if(isset($GLOBALS['no_vars'])) return; + + $script_globals = _script_globals(); + print ' + + + '; + + print '
+
+ DEBUG (runtime: '.script_runtime().' sec) + '; + + $vars_arr['script_globals'] = array('global script variables', '#7ACCC8'); + $vars_arr['_GET'] = array('$_GET', '#7DA7D9'); + $vars_arr['_POST'] = array('$_POST', '#F49AC1'); + $vars_arr['_FILES'] = array('$_FILES', '#82CA9C'); + $vars_arr['_SESSION'] = array('$_SESSION', '#FCDB26'); + $vars_arr['_COOKIE'] = array('$_COOKIE', '#A67C52'); + + if($show_all_vars) { + $vars_arr['_SERVER'] = array('SERVER', '#A186BE'); + $vars_arr['_ENV'] = array('ENV', '#7ACCC8'); + } + + foreach ($vars_arr as $vars_name => $vars_data) { + if($vars_name != 'script_globals') global $$vars_name; + if($$vars_name) { + print '
'.$vars_data[0].'
'; + print_a($$vars_name, NULL, $show_object_vars, $limit); + print '
'; + } + } + print '
'; + } + + ###################### + # function prints/returns strings wrapped between

+    #
+    function pre( $string, $return_mode = false, $tabwidth = 3 ) {
+        $tab = str_repeat(' ', $tabwidth);
+        $string = preg_replace('/\t+/em', "str_repeat( ' ', strlen('\\0') * $tabwidth );", $string); /* replace all tabs with spaces */
+
+        $out = '
'.$string."
\n"; + + if($return_mode) { + return $out; + } else { + print $out; + } + } + + function _check_for_leading_tabs( $string ) { + return preg_match('/^\t/m', $string); + } + + function _remove_exessive_leading_tabs( $string ) { + /* remove whitespace lines at start of the string */ + $string = preg_replace('/^\s*\n/', '', $string); + /* remove whitespace at end of the string */ + $string = preg_replace('/\s*$/', '', $string); + + # kleinste Anzahl von f쨲enden TABS z䨬en + preg_match_all('/^\t+/', $string, $matches); + $minTabCount = strlen(@min($matches[0])); + + # und entfernen + $string = preg_replace('/^\t{'.$minTabCount.'}/m', '', $string); + + return $string; + } +} // use debuglib + +// Define no-op functions in case debug functions were accidentally left +// in the live system. +else { + function print_a() {} + function print_result() {} + function reset_script_runtime() {} + function script_runtime() {} + function show_vars() {} + function pre() {} +} // don't use debuglib + +?> \ No newline at end of file diff --git a/includes/lib_article.php b/includes/lib_article.php new file mode 100644 index 0000000..ad70082 --- /dev/null +++ b/includes/lib_article.php @@ -0,0 +1,101 @@ + 0'; + } + else + { + $cat_str = get_article_children($cat_id); + } + //增加搜索条件,如果有搜索内容就进行搜索 + if ($requirement != '') + { + $sql = 'SELECT article_id, title, author, add_time, file_url, open_type' . + ' FROM ' .$GLOBALS['ecs']->table('article') . + ' WHERE is_open = 1 AND title like \'%' . $requirement . '%\' ' . + ' ORDER BY article_type DESC, article_id DESC'; + } + else + { + + $sql = 'SELECT article_id, title, author, add_time, file_url, open_type' . + ' FROM ' .$GLOBALS['ecs']->table('article') . + ' WHERE is_open = 1 AND ' . $cat_str . + ' ORDER BY article_type DESC, article_id DESC'; + } + + $res = $GLOBALS['db']->selectLimit($sql, $size, ($page-1) * $size); + + $arr = array(); + if ($res) + { + while ($row = $GLOBALS['db']->fetchRow($res)) + { + $article_id = $row['article_id']; + + $arr[$article_id]['id'] = $article_id; + $arr[$article_id]['title'] = $row['title']; + $arr[$article_id]['short_title'] = $GLOBALS['_CFG']['article_title_length'] > 0 ? sub_str($row['title'], $GLOBALS['_CFG']['article_title_length']) : $row['title']; + $arr[$article_id]['author'] = empty($row['author']) || $row['author'] == '_SHOPHELP' ? $GLOBALS['_CFG']['shop_name'] : $row['author']; + $arr[$article_id]['url'] = $row['open_type'] != 1 ? build_uri('article', array('aid'=>$article_id), $row['title']) : trim($row['file_url']); + $arr[$article_id]['add_time'] = date($GLOBALS['_CFG']['date_format'], $row['add_time']); + } + } + + return $arr; +} + +/** + * 获得指定分类下的文章总数 + * + * @param integer $cat_id + * + * @return integer + */ +function get_article_count($cat_id ,$requirement='') +{ + global $db, $ecs; + if ($requirement != '') + { + $count = $db->getOne('SELECT COUNT(*) FROM ' . $ecs->table('article') . ' WHERE ' . get_article_children($cat_id) . ' AND title like \'%' . $requirement . '%\' AND is_open = 1'); + } + else + { + $count = $db->getOne("SELECT COUNT(*) FROM " . $ecs->table('article') . " WHERE " . get_article_children($cat_id) . " AND is_open = 1"); + } + return $count; +} + +?> \ No newline at end of file diff --git a/includes/lib_base.php b/includes/lib_base.php new file mode 100644 index 0000000..6cdb412 --- /dev/null +++ b/includes/lib_base.php @@ -0,0 +1,1285 @@ += $strlength) + { + return $str; + } + elseif ($length < 0) + { + $length = $strlength + $length; + if ($length < 0) + { + $length = $strlength; + } + } + + if (function_exists('mb_substr')) + { + $newstr = mb_substr($str, 0, $length, EC_CHARSET); + } + elseif (function_exists('iconv_substr')) + { + $newstr = iconv_substr($str, 0, $length, EC_CHARSET); + } + else + { + //$newstr = trim_right(substr($str, 0, $length)); + $newstr = substr($str, 0, $length); + } + + if ($append && $str != $newstr) + { + $newstr .= '...'; + } + + return $newstr; +} + +/** + * 获得用户的真实IP地址 + * + * @access public + * @return string + */ +function real_ip() +{ + static $realip = NULL; + + if ($realip !== NULL) + { + return $realip; + } + + if (isset($_SERVER)) + { + if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) + { + $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']); + + /* 取X-Forwarded-For中第一个非unknown的有效IP字符串 */ + foreach ($arr AS $ip) + { + $ip = trim($ip); + + if ($ip != 'unknown') + { + $realip = $ip; + + break; + } + } + } + elseif (isset($_SERVER['HTTP_CLIENT_IP'])) + { + $realip = $_SERVER['HTTP_CLIENT_IP']; + } + else + { + if (isset($_SERVER['REMOTE_ADDR'])) + { + $realip = $_SERVER['REMOTE_ADDR']; + } + else + { + $realip = '0.0.0.0'; + } + } + } + else + { + if (getenv('HTTP_X_FORWARDED_FOR')) + { + $realip = getenv('HTTP_X_FORWARDED_FOR'); + } + elseif (getenv('HTTP_CLIENT_IP')) + { + $realip = getenv('HTTP_CLIENT_IP'); + } + else + { + $realip = getenv('REMOTE_ADDR'); + } + } + + preg_match("/[\d\.]{7,15}/", $realip, $onlineip); + $realip = !empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0'; + + return $realip; +} + +/** + * 计算字符串的长度(汉字按照两个字符计算) + * + * @param string $str 字符串 + * + * @return int + */ +function str_len($str) +{ + $length = strlen(preg_replace('/[\x00-\x7F]/', '', $str)); + + if ($length) + { + return strlen($str) - $length + intval($length / 3) * 2; + } + else + { + return strlen($str); + } +} + +/** + * 获得用户操作系统的换行符 + * + * @access public + * @return string + */ +function get_crlf() +{ +/* LF (Line Feed, 0x0A, \N) 和 CR(Carriage Return, 0x0D, \R) */ + if (stristr($_SERVER['HTTP_USER_AGENT'], 'Win')) + { + $the_crlf = '\r\n'; + } + elseif (stristr($_SERVER['HTTP_USER_AGENT'], 'Mac')) + { + $the_crlf = '\r'; // for old MAC OS + } + else + { + $the_crlf = '\n'; + } + + return $the_crlf; +} + +/** + * 邮件发送 + * + * @param: $name[string] 接收人姓名 + * @param: $email[string] 接收人邮件地址 + * @param: $subject[string] 邮件标题 + * @param: $content[string] 邮件内容 + * @param: $type[int] 0 普通邮件, 1 HTML邮件 + * @param: $notification[bool] true 要求回执, false 不用回执 + * + * @return boolean + */ +function send_mail($name, $email, $subject, $content, $type = 0, $notification=false) +{ + /* 如果邮件编码不是EC_CHARSET,创建字符集转换对象,转换编码 */ + if ($GLOBALS['_CFG']['mail_charset'] != EC_CHARSET) + { + $name = ecs_iconv(EC_CHARSET, $GLOBALS['_CFG']['mail_charset'], $name); + $subject = ecs_iconv(EC_CHARSET, $GLOBALS['_CFG']['mail_charset'], $subject); + $content = ecs_iconv(EC_CHARSET, $GLOBALS['_CFG']['mail_charset'], $content); + $shop_name = ecs_iconv(EC_CHARSET, $GLOBALS['_CFG']['mail_charset'], $GLOBALS['_CFG']['shop_name']); + } + $charset = $GLOBALS['_CFG']['mail_charset']; + /** + * 使用mail函数发送邮件 + */ + if ($GLOBALS['_CFG']['mail_service'] == 0 && function_exists('mail')) + { + /* 邮件的头部信息 */ + $content_type = ($type == 0) ? 'Content-Type: text/plain; charset=' . $charset : 'Content-Type: text/html; charset=' . $charset; + $headers = array(); + $headers[] = 'From: "' . '=?' . $charset . '?B?' . base64_encode($shop_name) . '?='.'" <' . $GLOBALS['_CFG']['smtp_mail'] . '>'; + $headers[] = $content_type . '; format=flowed'; + if ($notification) + { + $headers[] = 'Disposition-Notification-To: ' . '=?' . $charset . '?B?' . base64_encode($shop_name) . '?='.'" <' . $GLOBALS['_CFG']['smtp_mail'] . '>'; + } + + $res = @mail($email, '=?' . $charset . '?B?' . base64_encode($subject) . '?=', $content, implode("\r\n", $headers)); + + if (!$res) + { + $GLOBALS['err'] ->add($GLOBALS['_LANG']['sendemail_false']); + + return false; + } + else + { + return true; + } + } + /** + * 使用smtp服务发送邮件 + */ + else + { + /* 邮件的头部信息 */ + $content_type = ($type == 0) ? + 'Content-Type: text/plain; charset=' . $charset : 'Content-Type: text/html; charset=' . $charset; + $content = base64_encode($content); + + $headers = array(); + $headers[] = 'Date: ' . gmdate('D, j M Y H:i:s') . ' +0000'; + $headers[] = 'To: "' . '=?' . $charset . '?B?' . base64_encode($name) . '?=' . '" <' . $email. '>'; + $headers[] = 'From: "' . '=?' . $charset . '?B?' . base64_encode($shop_name) . '?='.'" <' . $GLOBALS['_CFG']['smtp_mail'] . '>'; + $headers[] = 'Subject: ' . '=?' . $charset . '?B?' . base64_encode($subject) . '?='; + $headers[] = $content_type . '; format=flowed'; + $headers[] = 'Content-Transfer-Encoding: base64'; + $headers[] = 'Content-Disposition: inline'; + if ($notification) + { + $headers[] = 'Disposition-Notification-To: ' . '=?' . $charset . '?B?' . base64_encode($shop_name) . '?='.'" <' . $GLOBALS['_CFG']['smtp_mail'] . '>'; + } + + /* 获得邮件服务器的参数设置 */ + $params['host'] = $GLOBALS['_CFG']['smtp_host']; + $params['port'] = $GLOBALS['_CFG']['smtp_port']; + $params['user'] = $GLOBALS['_CFG']['smtp_user']; + $params['pass'] = $GLOBALS['_CFG']['smtp_pass']; + + if (empty($params['host']) || empty($params['port'])) + { + // 如果没有设置主机和端口直接返回 false + $GLOBALS['err'] ->add($GLOBALS['_LANG']['smtp_setting_error']); + + return false; + } + else + { + // 发送邮件 + if (!function_exists('fsockopen')) + { + //如果fsockopen被禁用,直接返回 + $GLOBALS['err']->add($GLOBALS['_LANG']['disabled_fsockopen']); + + return false; + } + + include_once(ROOT_PATH . 'includes/cls_smtp.php'); + static $smtp; + + $send_params['recipients'] = $email; + $send_params['headers'] = $headers; + $send_params['from'] = $GLOBALS['_CFG']['smtp_mail']; + $send_params['body'] = $content; + + if (!isset($smtp)) + { + $smtp = new smtp($params); + } + + if ($smtp->connect() && $smtp->send($send_params)) + { + return true; + } + else + { + $err_msg = $smtp->error_msg(); + if (empty($err_msg)) + { + $GLOBALS['err']->add('Unknown Error'); + } + else + { + if (strpos($err_msg, 'Failed to connect to server') !== false) + { + $GLOBALS['err']->add(sprintf($GLOBALS['_LANG']['smtp_connect_failure'], $params['host'] . ':' . $params['port'])); + } + else if (strpos($err_msg, 'AUTH command failed') !== false) + { + $GLOBALS['err']->add($GLOBALS['_LANG']['smtp_login_failure']); + } + elseif (strpos($err_msg, 'bad sequence of commands') !== false) + { + $GLOBALS['err']->add($GLOBALS['_LANG']['smtp_refuse']); + } + else + { + $GLOBALS['err']->add($err_msg); + } + } + + return false; + } + } + } +} + +/** + * 获得服务器上的 GD 版本 + * + * @access public + * @return int 可能的值为0,1,2 + */ +function gd_version() +{ + include_once(ROOT_PATH . 'includes/cls_image.php'); + + return cls_image::gd_version(); +} + +if (!function_exists('file_get_contents')) +{ + /** + * 如果系统不存在file_get_contents函数则声明该函数 + * + * @access public + * @param string $file + * @return mix + */ + function file_get_contents($file) + { + if (($fp = @fopen($file, 'rb')) === false) + { + return false; + } + else + { + $fsize = @filesize($file); + if ($fsize) + { + $contents = fread($fp, $fsize); + } + else + { + $contents = ''; + } + fclose($fp); + + return $contents; + } + } +} + +if (!function_exists('file_put_contents')) +{ + define('FILE_APPEND', 'FILE_APPEND'); + + /** + * 如果系统不存在file_put_contents函数则声明该函数 + * + * @access public + * @param string $file + * @param mix $data + * @return int + */ + function file_put_contents($file, $data, $flags = '') + { + $contents = (is_array($data)) ? implode('', $data) : $data; + + if ($flags == 'FILE_APPEND') + { + $mode = 'ab+'; + } + else + { + $mode = 'wb'; + } + + if (($fp = @fopen($file, $mode)) === false) + { + return false; + } + else + { + $bytes = fwrite($fp, $contents); + fclose($fp); + + return $bytes; + } + } +} + +if (!function_exists('floatval')) +{ + /** + * 如果系统不存在 floatval 函数则声明该函数 + * + * @access public + * @param mix $n + * @return float + */ + function floatval($n) + { + return (float) $n; + } +} + +/** + * 文件或目录权限检查函数 + * + * @access public + * @param string $file_path 文件路径 + * @param bool $rename_prv 是否在检查修改权限时检查执行rename()函数的权限 + * + * @return int 返回值的取值范围为{0 <= x <= 15},每个值表示的含义可由四位二进制数组合推出。 + * 返回值在二进制计数法中,四位由高到低分别代表 + * 可执行rename()函数权限、可对文件追加内容权限、可写入文件权限、可读取文件权限。 + */ +function file_mode_info($file_path) +{ + /* 如果不存在,则不可读、不可写、不可改 */ + if (!file_exists($file_path)) + { + return false; + } + + $mark = 0; + + if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN') + { + /* 测试文件 */ + $test_file = $file_path . '/cf_test.txt'; + + /* 如果是目录 */ + if (is_dir($file_path)) + { + /* 检查目录是否可读 */ + $dir = @opendir($file_path); + if ($dir === false) + { + return $mark; //如果目录打开失败,直接返回目录不可修改、不可写、不可读 + } + if (@readdir($dir) !== false) + { + $mark ^= 1; //目录可读 001,目录不可读 000 + } + @closedir($dir); + + /* 检查目录是否可写 */ + $fp = @fopen($test_file, 'wb'); + if ($fp === false) + { + return $mark; //如果目录中的文件创建失败,返回不可写。 + } + if (@fwrite($fp, 'directory access testing.') !== false) + { + $mark ^= 2; //目录可写可读011,目录可写不可读 010 + } + @fclose($fp); + + @unlink($test_file); + + /* 检查目录是否可修改 */ + $fp = @fopen($test_file, 'ab+'); + if ($fp === false) + { + return $mark; + } + if (@fwrite($fp, "modify test.\r\n") !== false) + { + $mark ^= 4; + } + @fclose($fp); + + /* 检查目录下是否有执行rename()函数的权限 */ + if (@rename($test_file, $test_file) !== false) + { + $mark ^= 8; + } + @unlink($test_file); + } + /* 如果是文件 */ + elseif (is_file($file_path)) + { + /* 以读方式打开 */ + $fp = @fopen($file_path, 'rb'); + if ($fp) + { + $mark ^= 1; //可读 001 + } + @fclose($fp); + + /* 试着修改文件 */ + $fp = @fopen($file_path, 'ab+'); + if ($fp && @fwrite($fp, '') !== false) + { + $mark ^= 6; //可修改可写可读 111,不可修改可写可读011... + } + @fclose($fp); + + /* 检查目录下是否有执行rename()函数的权限 */ + if (@rename($test_file, $test_file) !== false) + { + $mark ^= 8; + } + } + } + else + { + if (@is_readable($file_path)) + { + $mark ^= 1; + } + + if (@is_writable($file_path)) + { + $mark ^= 14; + } + } + + return $mark; +} + +function log_write($arg, $file = '', $line = '') +{ + if ((DEBUG_MODE & 4) != 4) + { + return; + } + + $str = "\r\n-- ". date('Y-m-d H:i:s'). " --------------------------------------------------------------\r\n"; + $str .= "FILE: $file\r\nLINE: $line\r\n"; + + if (is_array($arg)) + { + $str .= '$arg = array('; + foreach ($arg AS $val) + { + foreach ($val AS $key => $list) + { + $str .= "'$key' => '$list'\r\n"; + } + } + $str .= ")\r\n"; + } + else + { + $str .= $arg; + } + + file_put_contents(ROOT_PATH . DATA_DIR . '/log.txt', $str); +} + +/** + * 检查目标文件夹是否存在,如果不存在则自动创建该目录 + * + * @access public + * @param string folder 目录路径。不能使用相对于网站根目录的URL + * + * @return bool + */ +function make_dir($folder) +{ + $reval = false; + + if (!file_exists($folder)) + { + /* 如果目录不存在则尝试创建该目录 */ + @umask(0); + + /* 将目录路径拆分成数组 */ + preg_match_all('/([^\/]*)\/?/i', $folder, $atmp); + + /* 如果第一个字符为/则当作物理路径处理 */ + $base = ($atmp[0][0] == '/') ? '/' : ''; + + /* 遍历包含路径信息的数组 */ + foreach ($atmp[1] AS $val) + { + if ('' != $val) + { + $base .= $val; + + if ('..' == $val || '.' == $val) + { + /* 如果目录为.或者..则直接补/继续下一个循环 */ + $base .= '/'; + + continue; + } + } + else + { + continue; + } + + $base .= '/'; + + if (!file_exists($base)) + { + /* 尝试创建目录,如果创建失败则继续循环 */ + if (@mkdir(rtrim($base, '/'), 0777)) + { + @chmod($base, 0777); + $reval = true; + } + } + } + } + else + { + /* 路径已经存在。返回该路径是不是一个目录 */ + $reval = is_dir($folder); + } + + clearstatcache(); + + return $reval; +} + +/** + * 获得系统是否启用了 gzip + * + * @access public + * + * @return boolean + */ +function gzip_enabled() +{ + static $enabled_gzip = NULL; + + if ($enabled_gzip === NULL) + { + $enabled_gzip = ($GLOBALS['_CFG']['enable_gzip'] && function_exists('ob_gzhandler')); + } + + return $enabled_gzip; +} + +/** + * 递归方式的对变量中的特殊字符进行转义 + * + * @access public + * @param mix $value + * + * @return mix + */ +function addslashes_deep($value) +{ + if (empty($value)) + { + return $value; + } + else + { + return is_array($value) ? array_map('addslashes_deep', $value) : addslashes($value); + } +} + +/** + * 将对象成员变量或者数组的特殊字符进行转义 + * + * @access public + * @param mix $obj 对象或者数组 + * @author Xuan Yan + * + * @return mix 对象或者数组 + */ +function addslashes_deep_obj($obj) +{ + if (is_object($obj) == true) + { + foreach ($obj AS $key => $val) + { + $obj->$key = addslashes_deep($val); + } + } + else + { + $obj = addslashes_deep($obj); + } + + return $obj; +} + +/** + * 递归方式的对变量中的特殊字符去除转义 + * + * @access public + * @param mix $value + * + * @return mix + */ +function stripslashes_deep($value) +{ + if (empty($value)) + { + return $value; + } + else + { + return is_array($value) ? array_map('stripslashes_deep', $value) : stripslashes($value); + } +} + +/** + * 将一个字串中含有全角的数字字符、字母、空格或'%+-()'字符转换为相应半角字符 + * + * @access public + * @param string $str 待转换字串 + * + * @return string $str 处理后字串 + */ +function make_semiangle($str) +{ + $arr = array('0' => '0', '1' => '1', '2' => '2', '3' => '3', '4' => '4', + '5' => '5', '6' => '6', '7' => '7', '8' => '8', '9' => '9', + 'A' => 'A', 'B' => 'B', 'C' => 'C', 'D' => 'D', 'E' => 'E', + 'F' => 'F', 'G' => 'G', 'H' => 'H', 'I' => 'I', 'J' => 'J', + 'K' => 'K', 'L' => 'L', 'M' => 'M', 'N' => 'N', 'O' => 'O', + 'P' => 'P', 'Q' => 'Q', 'R' => 'R', 'S' => 'S', 'T' => 'T', + 'U' => 'U', 'V' => 'V', 'W' => 'W', 'X' => 'X', 'Y' => 'Y', + 'Z' => 'Z', 'a' => 'a', 'b' => 'b', 'c' => 'c', 'd' => 'd', + 'e' => 'e', 'f' => 'f', 'g' => 'g', 'h' => 'h', 'i' => 'i', + 'j' => 'j', 'k' => 'k', 'l' => 'l', 'm' => 'm', 'n' => 'n', + 'o' => 'o', 'p' => 'p', 'q' => 'q', 'r' => 'r', 's' => 's', + 't' => 't', 'u' => 'u', 'v' => 'v', 'w' => 'w', 'x' => 'x', + 'y' => 'y', 'z' => 'z', + '(' => '(', ')' => ')', '〔' => '[', '〕' => ']', '【' => '[', + '】' => ']', '〖' => '[', '〗' => ']', '“' => '[', '”' => ']', + '‘' => '[', '’' => ']', '{' => '{', '}' => '}', '《' => '<', + '》' => '>', + '%' => '%', '+' => '+', '—' => '-', '-' => '-', '~' => '-', + ':' => ':', '。' => '.', '、' => ',', ',' => '.', '、' => '.', + ';' => ',', '?' => '?', '!' => '!', '…' => '-', '‖' => '|', + '”' => '"', '’' => '`', '‘' => '`', '|' => '|', '〃' => '"', + ' ' => ' '); + + return strtr($str, $arr); +} + +/** + * 检查文件类型 + * + * @access public + * @param string filename 文件名 + * @param string realname 真实文件名 + * @param string limit_ext_types 允许的文件类型 + * @return string + */ +function check_file_type($filename, $realname = '', $limit_ext_types = '') +{ + if ($realname) + { + $extname = strtolower(substr($realname, strrpos($realname, '.') + 1)); + } + else + { + $extname = strtolower(substr($filename, strrpos($filename, '.') + 1)); + } + + if ($limit_ext_types && stristr($limit_ext_types, '|' . $extname . '|') === false) + { + return ''; + } + + $str = $format = ''; + + $file = @fopen($filename, 'rb'); + if ($file) + { + $str = @fread($file, 0x400); // 读取前 1024 个字节 + @fclose($file); + } + else + { + if (stristr($filename, ROOT_PATH) === false) + { + if ($extname == 'jpg' || $extname == 'jpeg' || $extname == 'gif' || $extname == 'png' || $extname == 'doc' || + $extname == 'xls' || $extname == 'txt' || $extname == 'zip' || $extname == 'rar' || $extname == 'ppt' || + $extname == 'pdf' || $extname == 'rm' || $extname == 'mid' || $extname == 'wav' || $extname == 'bmp' || + $extname == 'swf' || $extname == 'chm' || $extname == 'sql' || $extname == 'cert'|| $extname == 'pptx' || + $extname == 'xlsx' || $extname == 'docx') + { + $format = $extname; + } + } + else + { + return ''; + } + } + + if ($format == '' && strlen($str) >= 2 ) + { + if (substr($str, 0, 4) == 'MThd' && $extname != 'txt') + { + $format = 'mid'; + } + elseif (substr($str, 0, 4) == 'RIFF' && $extname == 'wav') + { + $format = 'wav'; + } + elseif (substr($str ,0, 3) == "\xFF\xD8\xFF") + { + $format = 'jpg'; + } + elseif (substr($str ,0, 4) == 'GIF8' && $extname != 'txt') + { + $format = 'gif'; + } + elseif (substr($str ,0, 8) == "\x89\x50\x4E\x47\x0D\x0A\x1A\x0A") + { + $format = 'png'; + } + elseif (substr($str ,0, 2) == 'BM' && $extname != 'txt') + { + $format = 'bmp'; + } + elseif ((substr($str ,0, 3) == 'CWS' || substr($str ,0, 3) == 'FWS') && $extname != 'txt') + { + $format = 'swf'; + } + elseif (substr($str ,0, 4) == "\xD0\xCF\x11\xE0") + { // D0CF11E == DOCFILE == Microsoft Office Document + if (substr($str,0x200,4) == "\xEC\xA5\xC1\x00" || $extname == 'doc') + { + $format = 'doc'; + } + elseif (substr($str,0x200,2) == "\x09\x08" || $extname == 'xls') + { + $format = 'xls'; + } elseif (substr($str,0x200,4) == "\xFD\xFF\xFF\xFF" || $extname == 'ppt') + { + $format = 'ppt'; + } + } elseif (substr($str ,0, 4) == "PK\x03\x04") + { + if (substr($str,0x200,4) == "\xEC\xA5\xC1\x00" || $extname == 'docx') + { + $format = 'docx'; + } + elseif (substr($str,0x200,2) == "\x09\x08" || $extname == 'xlsx') + { + $format = 'xlsx'; + } elseif (substr($str,0x200,4) == "\xFD\xFF\xFF\xFF" || $extname == 'pptx') + { + $format = 'pptx'; + }else + { + $format = 'zip'; + } + } elseif (substr($str ,0, 4) == 'Rar!' && $extname != 'txt') + { + $format = 'rar'; + } elseif (substr($str ,0, 4) == "\x25PDF") + { + $format = 'pdf'; + } elseif (substr($str ,0, 3) == "\x30\x82\x0A") + { + $format = 'cert'; + } elseif (substr($str ,0, 4) == 'ITSF' && $extname != 'txt') + { + $format = 'chm'; + } elseif (substr($str ,0, 4) == "\x2ERMF") + { + $format = 'rm'; + } elseif ($extname == 'sql') + { + $format = 'sql'; + } elseif ($extname == 'txt') + { + $format = 'txt'; + } + } + + if ($limit_ext_types && stristr($limit_ext_types, '|' . $format . '|') === false) + { + $format = ''; + } + + return $format; +} + +/** + * 对 MYSQL LIKE 的内容进行转义 + * + * @access public + * @param string string 内容 + * @return string + */ +function mysql_like_quote($str) +{ + return strtr($str, array("\\\\" => "\\\\\\\\", '_' => '\_', '%' => '\%', "\'" => "\\\\\'")); +} + +/** + * 获取服务器的ip + * + * @access public + * + * @return string + **/ +function real_server_ip() +{ + static $serverip = NULL; + + if ($serverip !== NULL) + { + return $serverip; + } + + if (isset($_SERVER)) + { + if (isset($_SERVER['SERVER_ADDR'])) + { + $serverip = $_SERVER['SERVER_ADDR']; + } + else + { + $serverip = '0.0.0.0'; + } + } + else + { + $serverip = getenv('SERVER_ADDR'); + } + + return $serverip; +} + +/** + * 自定义 header 函数,用于过滤可能出现的安全隐患 + * + * @param string string 内容 + * + * @return void + **/ +function ecs_header($string, $replace = true, $http_response_code = 0) +{ + if (strpos($string, '../upgrade/index.php') === 0) + { + echo ''; + } + $string = str_replace(array("\r", "\n"), array('', ''), $string); + + if (preg_match('/^\s*location:/is', $string)) + { + @header($string . "\n", $replace); + + exit(); + } + + if (empty($http_response_code) || PHP_VERSION < '4.3') + { + @header($string, $replace); + } + else + { + @header($string, $replace, $http_response_code); + } +} + +function ecs_iconv($source_lang, $target_lang, $source_string = '') +{ + static $chs = NULL; + + /* 如果字符串为空或者字符串不需要转换,直接返回 */ + if ($source_lang == $target_lang || $source_string == '' || preg_match("/[\x80-\xFF]+/", $source_string) == 0) + { + return $source_string; + } + + if ($chs === NULL) + { + require_once(ROOT_PATH . 'includes/cls_iconv.php'); + $chs = new Chinese(ROOT_PATH); + } + + return $chs->Convert($source_lang, $target_lang, $source_string); +} + +function ecs_geoip($ip) +{ + static $fp = NULL, $offset = array(), $index = NULL; + + $ip = gethostbyname($ip); + $ipdot = explode('.', $ip); + $ip = pack('N', ip2long($ip)); + + $ipdot[0] = (int)$ipdot[0]; + $ipdot[1] = (int)$ipdot[1]; + if ($ipdot[0] == 10 || $ipdot[0] == 127 || ($ipdot[0] == 192 && $ipdot[1] == 168) || ($ipdot[0] == 172 && ($ipdot[1] >= 16 && $ipdot[1] <= 31))) + { + return 'LAN'; + } + + if ($fp === NULL) + { + $fp = fopen(ROOT_PATH . 'includes/codetable/ipdata.dat', 'rb'); + if ($fp === false) + { + return 'Invalid IP data file'; + } + $offset = unpack('Nlen', fread($fp, 4)); + if ($offset['len'] < 4) + { + return 'Invalid IP data file'; + } + $index = fread($fp, $offset['len'] - 4); + } + + $length = $offset['len'] - 1028; + $start = unpack('Vlen', $index[$ipdot[0] * 4] . $index[$ipdot[0] * 4 + 1] . $index[$ipdot[0] * 4 + 2] . $index[$ipdot[0] * 4 + 3]); + for ($start = $start['len'] * 8 + 1024; $start < $length; $start += 8) + { + if ($index{$start} . $index{$start + 1} . $index{$start + 2} . $index{$start + 3} >= $ip) + { + $index_offset = unpack('Vlen', $index{$start + 4} . $index{$start + 5} . $index{$start + 6} . "\x0"); + $index_length = unpack('Clen', $index{$start + 7}); + break; + } + } + + fseek($fp, $offset['len'] + $index_offset['len'] - 1024); + $area = fread($fp, $index_length['len']); + + fclose($fp); + $fp = NULL; + + return $area; +} + +/** + * 去除字符串右侧可能出现的乱码 + * + * @param string $str 字符串 + * + * @return string + */ +function trim_right($str) +{ + $len = strlen($str); + /* 为空或单个字符直接返回 */ + if ($len == 0 || ord($str{$len-1}) < 127) + { + return $str; + } + /* 有前导字符的直接把前导字符去掉 */ + if (ord($str{$len-1}) >= 192) + { + return substr($str, 0, $len-1); + } + /* 有非独立的字符,先把非独立字符去掉,再验证非独立的字符是不是一个完整的字,不是连原来前导字符也截取掉 */ + $r_len = strlen(rtrim($str, "\x80..\xBF")); + if ($r_len == 0 || ord($str{$r_len-1}) < 127) + { + return sub_str($str, 0, $r_len); + } + + $as_num = ord(~$str{$r_len -1}); + if ($as_num > (1<<(6 + $r_len - $len))) + { + return $str; + } + else + { + return substr($str, 0, $r_len-1); + } +} + +/** + * 将上传文件转移到指定位置 + * + * @param string $file_name + * @param string $target_name + * @return blog + */ +function move_upload_file($file_name, $target_name = '') +{ + if (function_exists("move_uploaded_file")) + { + if (move_uploaded_file($file_name, $target_name)) + { + @chmod($target_name,0755); + return true; + } + else if (copy($file_name, $target_name)) + { + @chmod($target_name,0755); + return true; + } + } + elseif (copy($file_name, $target_name)) + { + @chmod($target_name,0755); + return true; + } + return false; +} + +/** + * 将JSON传递的参数转码 + * + * @param string $str + * @return string + */ +function json_str_iconv($str) +{ + if (EC_CHARSET != 'utf-8') + { + if (is_string($str)) + { + return ecs_iconv('utf-8', EC_CHARSET, $str); + } + elseif (is_array($str)) + { + foreach ($str as $key => $value) + { + $str[$key] = json_str_iconv($value); + } + return $str; + } + elseif (is_object($str)) + { + foreach ($str as $key => $value) + { + $str->$key = json_str_iconv($value); + } + return $str; + } + else + { + return $str; + } + } + return $str; +} + +/** + * 循环转码成utf8内容 + * + * @param string $str + * @return string + */ +function to_utf8_iconv($str) +{ + if (EC_CHARSET != 'utf-8') + { + if (is_string($str)) + { + return ecs_iconv(EC_CHARSET, 'utf-8', $str); + } + elseif (is_array($str)) + { + foreach ($str as $key => $value) + { + $str[$key] = to_utf8_iconv($value); + } + return $str; + } + elseif (is_object($str)) + { + foreach ($str as $key => $value) + { + $str->$key = to_utf8_iconv($value); + } + return $str; + } + else + { + return $str; + } + } + return $str; +} + +/** + * 获取文件后缀名,并判断是否合法 + * + * @param string $file_name + * @param array $allow_type + * @return blob + */ +function get_file_suffix($file_name, $allow_type = array()) +{ + $file_suffix = strtolower(array_pop(explode('.', $file_name))); + if (empty($allow_type)) + { + return $file_suffix; + } + else + { + if (in_array($file_suffix, $allow_type)) + { + return true; + } + else + { + return false; + } + } +} + +/** + * 读结果缓存文件 + * + * @params string $cache_name + * + * @return array $data + */ +function read_static_cache($cache_name) +{ + if ((DEBUG_MODE & 2) == 2) + { + return false; + } + static $result = array(); + if (!empty($result[$cache_name])) + { + return $result[$cache_name]; + } + $cache_file_path = ROOT_PATH . '/temp/static_caches/' . $cache_name . '.php'; + if (file_exists($cache_file_path)) + { + include_once($cache_file_path); + $result[$cache_name] = $data; + return $result[$cache_name]; + } + else + { + return false; + } +} + +/** + * 写结果缓存文件 + * + * @params string $cache_name + * @params string $caches + * + * @return + */ +function write_static_cache($cache_name, $caches) +{ + if ((DEBUG_MODE & 2) == 2) + { + return false; + } + $cache_file_path = ROOT_PATH . '/temp/static_caches/' . $cache_name . '.php'; + $content = ""; + file_put_contents($cache_file_path, $content, LOCK_EX); +} + +?> \ No newline at end of file diff --git a/includes/lib_clips.php b/includes/lib_clips.php new file mode 100644 index 0000000..b8da768 --- /dev/null +++ b/includes/lib_clips.php @@ -0,0 +1,877 @@ +table('collect_goods') . ' AS c' . + " LEFT JOIN " . $GLOBALS['ecs']->table('goods') . " AS g ". + "ON g.goods_id = c.goods_id ". + " LEFT JOIN " . $GLOBALS['ecs']->table('member_price') . " AS mp ". + "ON mp.goods_id = g.goods_id AND mp.user_rank = '$_SESSION[user_rank]' ". + " WHERE c.user_id = '$user_id' ORDER BY c.rec_id DESC"; + $res = $GLOBALS['db'] -> selectLimit($sql, $num, $start); + + $goods_list = array(); + while ($row = $GLOBALS['db']->fetchRow($res)) + { + if ($row['promote_price'] > 0) + { + $promote_price = bargain_price($row['promote_price'], $row['promote_start_date'], $row['promote_end_date']); + } + else + { + $promote_price = 0; + } + + $goods_list[$row['goods_id']]['rec_id'] = $row['rec_id']; + $goods_list[$row['goods_id']]['is_attention'] = $row['is_attention']; + $goods_list[$row['goods_id']]['goods_id'] = $row['goods_id']; + $goods_list[$row['goods_id']]['goods_name'] = $row['goods_name']; + $goods_list[$row['goods_id']]['market_price'] = price_format($row['market_price']); + $goods_list[$row['goods_id']]['shop_price'] = price_format($row['shop_price']); + $goods_list[$row['goods_id']]['promote_price'] = ($promote_price > 0) ? price_format($promote_price) : ''; + $goods_list[$row['goods_id']]['url'] = build_uri('goods', array('gid'=>$row['goods_id']), $row['goods_name']); + } + + return $goods_list; +} + +/** + * 查看此商品是否已进行过缺货登记 + * + * @access public + * @param int $user_id 用户ID + * @param int $goods_id 商品ID + * + * @return int + */ +function get_booking_rec($user_id, $goods_id) +{ + $sql = 'SELECT COUNT(*) '. + 'FROM ' .$GLOBALS['ecs']->table('booking_goods'). + "WHERE user_id = '$user_id' AND goods_id = '$goods_id' AND is_dispose = 0"; + + return $GLOBALS['db']->getOne($sql); +} + +/** + * 获取指定用户的留言 + * + * @access public + * @param int $user_id 用户ID + * @param int $user_name 用户名 + * @param int $num 列表最大数量 + * @param int $start 列表其实位置 + * @return array $msg 留言及回复列表 + * @return string $order_id 订单ID + */ +function get_message_list($user_id, $user_name, $num, $start, $order_id = 0) +{ + /* 获取留言数据 */ + $msg = array(); + $sql = "SELECT * FROM " .$GLOBALS['ecs']->table('feedback'); + if ($order_id) + { + $sql .= " WHERE parent_id = 0 AND order_id = '$order_id' AND user_id = '$user_id' ORDER BY msg_time DESC"; + } + else + { + $sql .= " WHERE parent_id = 0 AND user_id = '$user_id' AND user_name = '" . $_SESSION['user_name'] . "' AND order_id=0 ORDER BY msg_time DESC"; + } + + $res = $GLOBALS['db']->SelectLimit($sql, $num, $start); + + while ($rows = $GLOBALS['db']->fetchRow($res)) + { + /* 取得留言的回复 */ + //if (empty($order_id)) + //{ + $reply = array(); + $sql = "SELECT user_name, user_email, msg_time, msg_content". + " FROM " .$GLOBALS['ecs']->table('feedback') . + " WHERE parent_id = '" . $rows['msg_id'] . "'"; + $reply = $GLOBALS['db']->getRow($sql); + + if ($reply) + { + $msg[$rows['msg_id']]['re_user_name'] = $reply['user_name']; + $msg[$rows['msg_id']]['re_user_email'] = $reply['user_email']; + $msg[$rows['msg_id']]['re_msg_time'] = local_date($GLOBALS['_CFG']['time_format'], $reply['msg_time']); + $msg[$rows['msg_id']]['re_msg_content'] = nl2br(htmlspecialchars($reply['msg_content'])); + } + //} + + $msg[$rows['msg_id']]['msg_content'] = nl2br(htmlspecialchars($rows['msg_content'])); + $msg[$rows['msg_id']]['msg_time'] = local_date($GLOBALS['_CFG']['time_format'], $rows['msg_time']); + $msg[$rows['msg_id']]['msg_type'] = $order_id ? $rows['user_name'] : $GLOBALS['_LANG']['type'][$rows['msg_type']]; + $msg[$rows['msg_id']]['msg_title'] = nl2br(htmlspecialchars($rows['msg_title'])); + $msg[$rows['msg_id']]['message_img'] = $rows['message_img']; + $msg[$rows['msg_id']]['order_id'] = $rows['order_id']; + } + + return $msg; +} + +/** + * 添加留言函数 + * + * @access public + * @param array $message + * + * @return boolen $bool + */ +function add_message($message) +{ + $upload_size_limit = $GLOBALS['_CFG']['upload_size_limit'] == '-1' ? ini_get('upload_max_filesize') : $GLOBALS['_CFG']['upload_size_limit']; + $status = 1 - $GLOBALS['_CFG']['message_check']; + + $last_char = strtolower($upload_size_limit{strlen($upload_size_limit)-1}); + + switch ($last_char) + { + case 'm': + $upload_size_limit *= 1024*1024; + break; + case 'k': + $upload_size_limit *= 1024; + break; + } + + if ($message['upload']) + { + if($_FILES['message_img']['size'] / 1024 > $upload_size_limit) + { + $GLOBALS['err']->add(sprintf($GLOBALS['_LANG']['upload_file_limit'], $upload_size_limit)); + return false; + } + $img_name = upload_file($_FILES['message_img'], 'feedbackimg'); + + if ($img_name === false) + { + return false; + } + } + else + { + $img_name = ''; + } + + if (empty($message['msg_title'])) + { + $GLOBALS['err']->add($GLOBALS['_LANG']['msg_title_empty']); + + return false; + } + + $message['msg_area'] = isset($message['msg_area']) ? intval($message['msg_area']) : 0; + $sql = "INSERT INTO " . $GLOBALS['ecs']->table('feedback') . + " (msg_id, parent_id, user_id, user_name, user_email, msg_title, msg_type, msg_status, msg_content, msg_time, message_img, order_id, msg_area)". + " VALUES (NULL, 0, '$message[user_id]', '$message[user_name]', '$message[user_email]', ". + " '$message[msg_title]', '$message[msg_type]', '$status', '$message[msg_content]', '".gmtime()."', '$img_name', '$message[order_id]', '$message[msg_area]')"; + $GLOBALS['db']->query($sql); + + return true; +} + +/** + * 获取用户的tags + * + * @access public + * @param int $user_id 用户ID + * + * @return array $arr tags列表 + */ +function get_user_tags($user_id = 0) +{ + if (empty($user_id)) + { + $GLOBALS['error_no'] = 1; + + return false; + } + + $tags = get_tags(0, $user_id); + + if (!empty($tags)) + { + color_tag($tags); + } + + return $tags; +} + +/** + * 验证性的删除某个tag + * + * @access public + * @param int $tag_words tag的ID + * @param int $user_id 用户的ID + * + * @return boolen bool + */ +function delete_tag($tag_words, $user_id) +{ + $sql = "DELETE FROM ".$GLOBALS['ecs']->table('tag'). + " WHERE tag_words = '$tag_words' AND user_id = '$user_id'"; + + return $GLOBALS['db']->query($sql); +} + +/** + * 获取某用户的缺货登记列表 + * + * @access public + * @param int $user_id 用户ID + * @param int $num 列表最大数量 + * @param int $start 列表其实位置 + * + * @return array $booking + */ +function get_booking_list($user_id, $num, $start) +{ + $booking = array(); + $sql = "SELECT bg.rec_id, bg.goods_id, bg.goods_number, bg.booking_time, bg.dispose_note, g.goods_name ". + "FROM " .$GLOBALS['ecs']->table('booking_goods')." AS bg , " .$GLOBALS['ecs']->table('goods')." AS g". " WHERE bg.goods_id = g.goods_id AND bg.user_id = '$user_id' ORDER BY bg.booking_time DESC"; + $res = $GLOBALS['db']->SelectLimit($sql, $num, $start); + + while ($row = $GLOBALS['db']->fetchRow($res)) + { + if (empty($row['dispose_note'])) + { + $row['dispose_note'] = 'N/A'; + } + $booking[] = array('rec_id' => $row['rec_id'], + 'goods_name' => $row['goods_name'], + 'goods_number' => $row['goods_number'], + 'booking_time' => local_date($GLOBALS['_CFG']['date_format'], $row['booking_time']), + 'dispose_note' => $row['dispose_note'], + 'url' => build_uri('goods', array('gid'=>$row['goods_id']), $row['goods_name'])); + } + + return $booking; +} + +/** + * 获取某用户的缺货登记列表 + * + * @access public + * @param int $goods_id 商品ID + * + * @return array $info + */ +function get_goodsinfo($goods_id) +{ + $info = array(); + $sql = "SELECT goods_name FROM " .$GLOBALS['ecs']->table('goods'). " WHERE goods_id = '$goods_id'"; + + $info['goods_name'] = $GLOBALS['db']->getOne($sql); + $info['goods_number'] = 1; + $info['id'] = $goods_id; + + if (!empty($_SESSION['user_id'])) + { + $row = array(); + $sql = "SELECT ua.consignee, ua.email, ua.tel, ua.mobile ". + "FROM ".$GLOBALS['ecs']->table('user_address')." AS ua, ".$GLOBALS['ecs']->table('users')." AS u". + " WHERE u.address_id = ua.address_id AND u.user_id = '$_SESSION[user_id]'"; + $row = $GLOBALS['db']->getRow($sql) ; + $info['consignee'] = empty($row['consignee']) ? '' : $row['consignee']; + $info['email'] = empty($row['email']) ? '' : $row['email']; + $info['tel'] = empty($row['mobile']) ? (empty($row['tel']) ? '' : $row['tel']) : $row['mobile']; + } + + return $info; +} + +/** + * 验证删除某个收藏商品 + * + * @access public + * @param int $booking_id 缺货登记的ID + * @param int $user_id 会员的ID + * @return boolen $bool + */ +function delete_booking($booking_id, $user_id) +{ + $sql = 'DELETE FROM ' .$GLOBALS['ecs']->table('booking_goods'). + " WHERE rec_id = '$booking_id' AND user_id = '$user_id'"; + + return $GLOBALS['db']->query($sql); +} + +/** + * 添加缺货登记记录到数据表 + * @access public + * @param array $booking + * + * @return void + */ +function add_booking($booking) +{ + $sql = "INSERT INTO " .$GLOBALS['ecs']->table('booking_goods'). + " VALUES ('', '$_SESSION[user_id]', '$booking[email]', '$booking[linkman]', ". + "'$booking[tel]', '$booking[goods_id]', '$booking[desc]', ". + "'$booking[goods_amount]', '".gmtime()."', 0, '', 0, '')"; + $GLOBALS['db']->query($sql) or die ($GLOBALS['db']->errorMsg()); + + return $GLOBALS['db']->insert_id(); +} + +/** + * 插入会员账目明细 + * + * @access public + * @param array $surplus 会员余额信息 + * @param string $amount 余额 + * + * @return int + */ +function insert_user_account($surplus, $amount) +{ + $sql = 'INSERT INTO ' .$GLOBALS['ecs']->table('user_account'). + ' (user_id, admin_user, amount, add_time, paid_time, admin_note, user_note, process_type, payment, is_paid)'. + " VALUES ('$surplus[user_id]', '', '$amount', '".gmtime()."', 0, '', '$surplus[user_note]', '$surplus[process_type]', '$surplus[payment]', 0)"; + $GLOBALS['db']->query($sql); + + return $GLOBALS['db']->insert_id(); +} + +/** + * 更新会员账目明细 + * + * @access public + * @param array $surplus 会员余额信息 + * + * @return int + */ +function update_user_account($surplus) +{ + $sql = 'UPDATE ' .$GLOBALS['ecs']->table('user_account'). ' SET '. + "amount = '$surplus[amount]', ". + "user_note = '$surplus[user_note]', ". + "payment = '$surplus[payment]' ". + "WHERE id = '$surplus[rec_id]'"; + $GLOBALS['db']->query($sql); + + return $surplus['rec_id']; +} + +/** + * 将支付LOG插入数据表 + * + * @access public + * @param integer $id 订单编号 + * @param float $amount 订单金额 + * @param integer $type 支付类型 + * @param integer $is_paid 是否已支付 + * + * @return int + */ +function insert_pay_log($id, $amount, $type = PAY_SURPLUS, $is_paid = 0) +{ + $sql = 'INSERT INTO ' .$GLOBALS['ecs']->table('pay_log')." (order_id, order_amount, order_type, is_paid)". + " VALUES ('$id', '$amount', '$type', '$is_paid')"; + $GLOBALS['db']->query($sql); + + return $GLOBALS['db']->insert_id(); +} + +/** + * 取得上次未支付的pay_lig_id + * + * @access public + * @param array $surplus_id 余额记录的ID + * @param array $pay_type 支付的类型:预付款/订单支付 + * + * @return int + */ +function get_paylog_id($surplus_id, $pay_type = PAY_SURPLUS) +{ + $sql = 'SELECT log_id FROM' .$GLOBALS['ecs']->table('pay_log'). + " WHERE order_id = '$surplus_id' AND order_type = '$pay_type' AND is_paid = 0"; + + return $GLOBALS['db']->getOne($sql); +} + +/** + * 根据ID获取当前余额操作信息 + * + * @access public + * @param int $surplus_id 会员余额的ID + * + * @return int + */ +function get_surplus_info($surplus_id) +{ + $sql = 'SELECT * FROM ' .$GLOBALS['ecs']->table('user_account'). + " WHERE id = '$surplus_id'"; + + return $GLOBALS['db']->getRow($sql); +} + +/** + * 取得已安装的支付方式(其中不包括线下支付的) + * @param bool $include_balance 是否包含余额支付(冲值时不应包括) + * @return array 已安装的配送方式列表 + */ +function get_online_payment_list($include_balance = true) +{ + $sql = 'SELECT pay_id, pay_code, pay_name, pay_fee, pay_desc ' . + 'FROM ' . $GLOBALS['ecs']->table('payment') . + " WHERE enabled = 1 AND is_cod <> 1"; + if (!$include_balance) + { + $sql .= " AND pay_code <> 'balance' "; + } + + $modules = $GLOBALS['db']->getAll($sql); + + include_once(ROOT_PATH.'includes/lib_compositor.php'); + + return $modules; +} + +/** + * 查询会员余额的操作记录 + * + * @access public + * @param int $user_id 会员ID + * @param int $num 每页显示数量 + * @param int $start 开始显示的条数 + * @return array + */ +function get_account_log($user_id, $num, $start) +{ + $account_log = array(); + $sql = 'SELECT * FROM ' .$GLOBALS['ecs']->table('user_account'). + " WHERE user_id = '$user_id'" . + " AND process_type " . db_create_in(array(SURPLUS_SAVE, SURPLUS_RETURN)) . + " ORDER BY add_time DESC"; + $res = $GLOBALS['db']->selectLimit($sql, $num, $start); + + if ($res) + { + while ($rows = $GLOBALS['db']->fetchRow($res)) + { + $rows['add_time'] = local_date($GLOBALS['_CFG']['date_format'], $rows['add_time']); + $rows['admin_note'] = nl2br(htmlspecialchars($rows['admin_note'])); + $rows['short_admin_note'] = ($rows['admin_note'] > '') ? sub_str($rows['admin_note'], 30) : 'N/A'; + $rows['user_note'] = nl2br(htmlspecialchars($rows['user_note'])); + $rows['short_user_note'] = ($rows['user_note'] > '') ? sub_str($rows['user_note'], 30) : 'N/A'; + $rows['pay_status'] = ($rows['is_paid'] == 0) ? $GLOBALS['_LANG']['un_confirm'] : $GLOBALS['_LANG']['is_confirm']; + $rows['amount'] = price_format(abs($rows['amount']), false); + + /* 会员的操作类型: 冲值,提现 */ + if ($rows['process_type'] == 0) + { + $rows['type'] = $GLOBALS['_LANG']['surplus_type_0']; + } + else + { + $rows['type'] = $GLOBALS['_LANG']['surplus_type_1']; + } + + /* 支付方式的ID */ + $sql = 'SELECT pay_id FROM ' .$GLOBALS['ecs']->table('payment'). + " WHERE pay_name = '$rows[payment]' AND enabled = 1"; + $pid = $GLOBALS['db']->getOne($sql); + + /* 如果是预付款而且还没有付款, 允许付款 */ + if (($rows['is_paid'] == 0) && ($rows['process_type'] == 0)) + { + $rows['handle'] = ''.$GLOBALS['_LANG']['pay'].''; + } + + $account_log[] = $rows; + } + + return $account_log; + } + else + { + return false; + } +} + +/** + * 删除未确认的会员帐目信息 + * + * @access public + * @param int $rec_id 会员余额记录的ID + * @param int $user_id 会员的ID + * @return boolen + */ +function del_user_account($rec_id, $user_id) +{ + $sql = 'DELETE FROM ' .$GLOBALS['ecs']->table('user_account'). + " WHERE is_paid = 0 AND id = '$rec_id' AND user_id = '$user_id'"; + + return $GLOBALS['db']->query($sql); +} + +/** + * 查询会员余额的数量 + * @access public + * @param int $user_id 会员ID + * @return int + */ +function get_user_surplus($user_id) +{ + $sql = "SELECT SUM(user_money) FROM " .$GLOBALS['ecs']->table('account_log'). + " WHERE user_id = '$user_id'"; + + return $GLOBALS['db']->getOne($sql); +} + +/** + * 获取用户中心默认页面所需的数据 + * + * @access public + * @param int $user_id 用户ID + * + * @return array $info 默认页面所需资料数组 + */ +function get_user_default($user_id) +{ + $user_bonus = get_user_bonus(); + + $sql = "SELECT pay_points, user_money, credit_line, last_login, is_validated FROM " .$GLOBALS['ecs']->table('users'). " WHERE user_id = '$user_id'"; + $row = $GLOBALS['db']->getRow($sql); + $info = array(); + $info['username'] = stripslashes($_SESSION['user_name']); + $info['shop_name'] = $GLOBALS['_CFG']['shop_name']; + $info['integral'] = $row['pay_points'] . $GLOBALS['_CFG']['integral_name']; + /* 增加是否开启会员邮件验证开关 */ + $info['is_validate'] = ($GLOBALS['_CFG']['member_email_validate'] && !$row['is_validated'])?0:1; + $info['credit_line'] = $row['credit_line']; + $info['formated_credit_line'] = price_format($info['credit_line'], false); + + //如果$_SESSION中时间无效说明用户是第一次登录。取当前登录时间。 + $last_time = !isset($_SESSION['last_time']) ? $row['last_login'] : $_SESSION['last_time']; + + if ($last_time == 0) + { + $_SESSION['last_time'] = $last_time = gmtime(); + } + + $info['last_time'] = local_date($GLOBALS['_CFG']['time_format'], $last_time); + $info['surplus'] = price_format($row['user_money'], false); + $info['bonus'] = sprintf($GLOBALS['_LANG']['user_bonus_info'], $user_bonus['bonus_count'], price_format($user_bonus['bonus_value'], false)); + + $sql = "SELECT COUNT(*) FROM " .$GLOBALS['ecs']->table('order_info'). + " WHERE user_id = '" .$user_id. "' AND add_time > '" .local_strtotime('-1 months'). "'"; + $info['order_count'] = $GLOBALS['db']->getOne($sql); + + include_once(ROOT_PATH . 'includes/lib_order.php'); + $sql = "SELECT order_id, order_sn ". + " FROM " .$GLOBALS['ecs']->table('order_info'). + " WHERE user_id = '" .$user_id. "' AND shipping_time > '" .$last_time. "'". order_query_sql('shipped'); + $info['shipped_order'] = $GLOBALS['db']->getAll($sql); + + return $info; +} + +/** + * 添加商品标签 + * + * @access public + * @param integer $id + * @param string $tag + * @return void + */ +function add_tag($id, $tag) +{ + if (empty($tag)) + { + return; + } + + $arr = explode(',', $tag); + + foreach ($arr AS $val) + { + /* 检查是否重复 */ + $sql = "SELECT COUNT(*) FROM ". $GLOBALS['ecs']->table("tag"). + " WHERE user_id = '".$_SESSION['user_id']."' AND goods_id = '$id' AND tag_words = '$val'"; + + if ($GLOBALS['db']->getOne($sql) == 0) + { + $sql = "INSERT INTO ".$GLOBALS['ecs']->table("tag")." (user_id, goods_id, tag_words) ". + "VALUES ('".$_SESSION['user_id']."', '$id', '$val')"; + $GLOBALS['db']->query($sql); + } + } +} + +/** + * 标签着色 + * + * @access public + * @param array + * @author Xuan Yan + * + * @return none + */ +function color_tag(&$tags) +{ + $tagmark = array( + array('color'=>'#666666','size'=>'0.8em','ifbold'=>1), + array('color'=>'#333333','size'=>'0.9em','ifbold'=>0), + array('color'=>'#006699','size'=>'1.0em','ifbold'=>1), + array('color'=>'#CC9900','size'=>'1.1em','ifbold'=>0), + array('color'=>'#666633','size'=>'1.2em','ifbold'=>1), + array('color'=>'#993300','size'=>'1.3em','ifbold'=>0), + array('color'=>'#669933','size'=>'1.4em','ifbold'=>1), + array('color'=>'#3366FF','size'=>'1.5em','ifbold'=>0), + array('color'=>'#197B30','size'=>'1.6em','ifbold'=>1), + ); + + $maxlevel = count($tagmark); + $tcount = $scount = array(); + + foreach($tags AS $val) + { + $tcount[] = $val['tag_count']; // 获得tag个数数组 + } + $tcount = array_unique($tcount); // 去除相同个数的tag + + sort($tcount); // 从小到大排序 + + $tempcount = count($tcount); // 真正的tag级数 + $per = $maxlevel >= $tempcount ? 1 : $maxlevel / ($tempcount - 1); + + foreach ($tcount AS $key => $val) + { + $lvl = floor($per * $key); + $scount[$val] = $lvl; // 计算不同个数的tag相对应的着色数组key + } + + $rewrite = intval($GLOBALS['_CFG']['rewrite']) > 0; + + /* 遍历所有标签,根据引用次数设定字体大小 */ + foreach ($tags AS $key => $val) + { + $lvl = $scount[$val['tag_count']]; // 着色数组key + + $tags[$key]['color'] = $tagmark[$lvl]['color']; + $tags[$key]['size'] = $tagmark[$lvl]['size']; + $tags[$key]['bold'] = $tagmark[$lvl]['ifbold']; + if ($rewrite) + { + if (strtolower(EC_CHARSET) !== 'utf-8') + { + $tags[$key]['url'] = 'tag-' . urlencode(urlencode($val['tag_words'])) . '.html'; + } + else + { + $tags[$key]['url'] = 'tag-' . urlencode($val['tag_words']) . '.html'; + } + } + else + { + $tags[$key]['url'] = 'search.php?keywords=' . urlencode($val['tag_words']); + } + } + shuffle($tags); +} + +/** + * 取得用户等级信息 + * @access public + * @author Xuan Yan + * + * @return array + */ +function get_rank_info() +{ + global $db,$ecs; + + if (!empty($_SESSION['user_rank'])) + { + $sql = "SELECT rank_name, special_rank FROM " . $ecs->table('user_rank') . " WHERE rank_id = '$_SESSION[user_rank]'"; + $row = $db->getRow($sql); + if (empty($row)) + { + return array(); + } + $rank_name = $row['rank_name']; + if ($row['special_rank']) + { + return array('rank_name'=>$rank_name); + } + else + { + $user_rank = $db->getOne("SELECT rank_points FROM " . $ecs->table('users') . " WHERE user_id = '$_SESSION[user_id]'"); + $sql = "SELECT rank_name,min_points FROM " . $ecs->table('user_rank') . " WHERE min_points > '$user_rank' ORDER BY min_points ASC LIMIT 1"; + $rt = $db->getRow($sql); + $next_rank_name = $rt['rank_name']; + $next_rank = $rt['min_points'] - $user_rank; + return array('rank_name'=>$rank_name,'next_rank_name'=>$next_rank_name,'next_rank'=>$next_rank); + } + } + else + { + return array(); + } +} + +/** + * 获取用户参与活动信息 + * + * @access public + * @param int $user_id 用户id + * + * @return array + */ +function get_user_prompt ($user_id) +{ + $prompt = array(); + $now = gmtime(); + /* 夺宝奇兵 */ + $sql = "SELECT act_id, goods_name, end_time " . + "FROM " . $GLOBALS['ecs']->table('goods_activity') . + " WHERE act_type = '" . GAT_SNATCH . "'" . + " AND (is_finished = 1 OR (is_finished = 0 AND end_time <= '$now'))"; + $res = $GLOBALS['db']->query($sql); + while ($row = $GLOBALS['db']->fetchRow($res)) + { + $act_id = $row['act_id']; + $result = get_snatch_result($act_id); + if (isset($result['order_count']) && $result['order_count'] == 0 && $result['user_id'] == $user_id) + { + $prompt[] = array( + 'text'=>sprintf($GLOBALS['_LANG']['your_snatch'],$row['goods_name'], $row['act_id']), + 'add_time'=> $row['end_time'] + ); + } + if (isset($auction['last_bid']) && $auction['last_bid']['bid_user'] == $user_id && $auction['order_count'] == 0) + { + $prompt[] = array( + 'text' => sprintf($GLOBALS['_LANG']['your_auction'], $row['goods_name'], $row['act_id']), + 'add_time' => $row['end_time'] + ); + } + } + + + /* 竞拍 */ + + $sql = "SELECT act_id, goods_name, end_time " . + "FROM " . $GLOBALS['ecs']->table('goods_activity') . + " WHERE act_type = '" . GAT_AUCTION . "'" . + " AND (is_finished = 1 OR (is_finished = 0 AND end_time <= '$now'))"; + $res = $GLOBALS['db']->query($sql); + while ($row = $GLOBALS['db']->fetchRow($res)) + { + $act_id = $row['act_id']; + $auction = auction_info($act_id); + if (isset($auction['last_bid']) && $auction['last_bid']['bid_user'] == $user_id && $auction['order_count'] == 0) + { + $prompt[] = array( + 'text' => sprintf($GLOBALS['_LANG']['your_auction'], $row['goods_name'], $row['act_id']), + 'add_time' => $row['end_time'] + ); + } + } + + /* 排序 */ + $cmp = create_function('$a, $b', 'if($a["add_time"] == $b["add_time"]){return 0;};return $a["add_time"] < $b["add_time"] ? 1 : -1;'); + usort($prompt, $cmp); + + /* 格式化时间 */ + foreach ($prompt as $key => $val) + { + $prompt[$key]['formated_time'] = local_date($GLOBALS['_CFG']['time_format'], $val['add_time']); + } + + return $prompt; +} + +/** + * 获取用户评论 + * + * @access public + * @param int $user_id 用户id + * @param int $page_size 列表最大数量 + * @param int $start 列表起始页 + * @return array + */ +function get_comment_list($user_id, $page_size, $start) +{ + $sql = "SELECT c.*, g.goods_name AS cmt_name, r.content AS reply_content, r.add_time AS reply_time ". + " FROM " . $GLOBALS['ecs']->table('comment') . " AS c ". + " LEFT JOIN " . $GLOBALS['ecs']->table('comment') . " AS r ". + " ON r.parent_id = c.comment_id AND r.parent_id > 0 ". + " LEFT JOIN " . $GLOBALS['ecs']->table('goods') . " AS g ". + " ON c.comment_type=0 AND c.id_value = g.goods_id ". + " WHERE c.user_id='$user_id'"; + $res = $GLOBALS['db']->SelectLimit($sql, $page_size, $start); + + $comments = array(); + $to_article = array(); + while ($row = $GLOBALS['db']->fetchRow($res)) + { + $row['formated_add_time'] = local_date($GLOBALS['_CFG']['time_format'], $row['add_time']); + if ($row['reply_time']) + { + $row['formated_reply_time'] = local_date($GLOBALS['_CFG']['time_format'], $row['reply_time']); + } + if ($row['comment_type'] == 1) + { + $to_article[] = $row["id_value"]; + } + $comments[] = $row; + } + + if ($to_article) + { + $sql = "SELECT article_id , title FROM " . $GLOBALS['ecs']->table('article') . " WHERE " . db_create_in($to_article, 'article_id'); + $arr = $GLOBALS['db']->getAll($sql); + $to_cmt_name = array(); + foreach ($arr as $row) + { + $to_cmt_name[$row['article_id']] = $row['title']; + } + + foreach ($comments as $key=>$row) + { + if ($row['comment_type'] == 1) + { + $comments[$key]['cmt_name'] = isset($to_cmt_name[$row['id_value']]) ? $to_cmt_name[$row['id_value']] : ''; + } + } + } + + return $comments; +} +?> \ No newline at end of file diff --git a/includes/lib_code.php b/includes/lib_code.php new file mode 100644 index 0000000..399fee5 --- /dev/null +++ b/includes/lib_code.php @@ -0,0 +1,61 @@ + \ No newline at end of file diff --git a/includes/lib_common.php b/includes/lib_common.php new file mode 100644 index 0000000..696ee4d --- /dev/null +++ b/includes/lib_common.php @@ -0,0 +1,2782 @@ +queryTime == '') + { + $query_time = 0; + } + else + { + if (PHP_VERSION >= '5.0.0') + { + $query_time = number_format(microtime(true) - $GLOBALS['db']->queryTime, 6); + } + else + { + list($now_usec, $now_sec) = explode(' ', microtime()); + list($start_usec, $start_sec) = explode(' ', $GLOBALS['db']->queryTime); + $query_time = number_format(($now_sec - $start_sec) + ($now_usec - $start_usec), 6); + } + } + $GLOBALS['smarty']->assign('query_info', sprintf($GLOBALS['_LANG']['query_info'], $GLOBALS['db']->queryCount, $query_time)); + + /* 内存占用情况 */ + if ($GLOBALS['_LANG']['memory_info'] && function_exists('memory_get_usage')) + { + $GLOBALS['smarty']->assign('memory_info', sprintf($GLOBALS['_LANG']['memory_info'], memory_get_usage() / 1048576)); + } + + /* 是否启用了 gzip */ + $gzip_enabled = gzip_enabled() ? $GLOBALS['_LANG']['gzip_enabled'] : $GLOBALS['_LANG']['gzip_disabled']; + $GLOBALS['smarty']->assign('gzip_enabled', $gzip_enabled); +} + +/** + * 创建地区的返回信息 + * + * @access public + * @param array $arr 地区数组 * + * @return void + */ +function region_result($parent, $sel_name, $type) +{ + global $cp; + + $arr = get_regions($type, $parent); + foreach ($arr AS $v) + { + $region =& $cp->add_node('region'); + $region_id =& $region->add_node('id'); + $region_name =& $region->add_node('name'); + + $region_id->set_data($v['region_id']); + $region_name->set_data($v['region_name']); + } + $select_obj =& $cp->add_node('select'); + $select_obj->set_data($sel_name); +} + +/** + * 获得指定国家的所有省份 + * + * @access public + * @param int country 国家的编号 + * @return array + */ +function get_regions($type = 0, $parent = 0) +{ + $sql = 'SELECT region_id, region_name FROM ' . $GLOBALS['ecs']->table('region') . + " WHERE region_type = '$type' AND parent_id = '$parent'"; + + return $GLOBALS['db']->GetAll($sql); +} + +/** + * 获得配送区域中指定的配送方式的配送费用的计算参数 + * + * @access public + * @param int $area_id 配送区域ID + * + * @return array; + */ +function get_shipping_config($area_id) +{ + /* 获得配置信息 */ + $sql = 'SELECT configure FROM ' . $GLOBALS['ecs']->table('shipping_area') . " WHERE shipping_area_id = '$area_id'"; + $cfg = $GLOBALS['db']->GetOne($sql); + + if ($cfg) + { + /* 拆分成配置信息的数组 */ + $arr = unserialize($cfg); + } + else + { + $arr = array(); + } + + return $arr; +} + +/** + * 初始化会员数据整合类 + * + * @access public + * @return object + */ +function &init_users() +{ + $set_modules = false; + static $cls = null; + if ($cls != null) + { + return $cls; + } + include_once(ROOT_PATH . 'includes/modules/integrates/' . $GLOBALS['_CFG']['integrate_code'] . '.php'); + $cfg = unserialize($GLOBALS['_CFG']['integrate_config']); + $cls = new $GLOBALS['_CFG']['integrate_code']($cfg); + + return $cls; +} + +/** + * 获得指定分类下的子分类的数组 + * + * @access public + * @param int $cat_id 分类的ID + * @param int $selected 当前选中分类的ID + * @param boolean $re_type 返回的类型: 值为真时返回下拉列表,否则返回数组 + * @param int $level 限定返回的级数。为0时返回所有级数 + * @param int $is_show_all 如果为true显示所有分类,如果为false隐藏不可见分类。 + * @return mix + */ +function cat_list($cat_id = 0, $selected = 0, $re_type = true, $level = 0, $is_show_all = true) +{ + static $res = NULL; + + if ($res === NULL) + { + $data = read_static_cache('cat_pid_releate'); + if ($data === false) + { + $sql = "SELECT c.cat_id, c.cat_name, c.measure_unit, c.parent_id, c.is_show, c.show_in_nav, c.grade, c.sort_order, COUNT(s.cat_id) AS has_children ". + 'FROM ' . $GLOBALS['ecs']->table('category') . " AS c ". + "LEFT JOIN " . $GLOBALS['ecs']->table('category') . " AS s ON s.parent_id=c.cat_id ". + "GROUP BY c.cat_id ". + 'ORDER BY c.parent_id, c.sort_order ASC'; + $res = $GLOBALS['db']->getAll($sql); + + $sql = "SELECT cat_id, COUNT(*) AS goods_num " . + " FROM " . $GLOBALS['ecs']->table('goods') . + " WHERE is_delete = 0 AND is_on_sale = 1 " . + " GROUP BY cat_id"; + $res2 = $GLOBALS['db']->getAll($sql); + + $sql = "SELECT gc.cat_id, COUNT(*) AS goods_num " . + " FROM " . $GLOBALS['ecs']->table('goods_cat') . " AS gc , " . $GLOBALS['ecs']->table('goods') . " AS g " . + " WHERE g.goods_id = gc.goods_id AND g.is_delete = 0 AND g.is_on_sale = 1 " . + " GROUP BY gc.cat_id"; + $res3 = $GLOBALS['db']->getAll($sql); + + $newres = array(); + foreach($res2 as $k=>$v) + { + $newres[$v['cat_id']] = $v['goods_num']; + foreach($res3 as $ks=>$vs) + { + if($v['cat_id'] == $vs['cat_id']) + { + $newres[$v['cat_id']] = $v['goods_num'] + $vs['goods_num']; + } + } + } + + foreach($res as $k=>$v) + { + $res[$k]['goods_num'] = !empty($newres[$v['cat_id']]) ? $newres[$v['cat_id']] : 0; + } + //如果数组过大,不采用静态缓存方式 + if (count($res) <= 1000) + { + write_static_cache('cat_pid_releate', $res); + } + } + else + { + $res = $data; + } + } + + if (empty($res) == true) + { + return $re_type ? '' : array(); + } + + $options = cat_options($cat_id, $res); // 获得指定分类下的子分类的数组 + + $children_level = 99999; //大于这个分类的将被删除 + if ($is_show_all == false) + { + foreach ($options as $key => $val) + { + if ($val['level'] > $children_level) + { + unset($options[$key]); + } + else + { + if ($val['is_show'] == 0) + { + unset($options[$key]); + if ($children_level > $val['level']) + { + $children_level = $val['level']; //标记一下,这样子分类也能删除 + } + } + else + { + $children_level = 99999; //恢复初始值 + } + } + } + } + + /* 截取到指定的缩减级别 */ + if ($level > 0) + { + if ($cat_id == 0) + { + $end_level = $level; + } + else + { + $first_item = reset($options); // 获取第一个元素 + $end_level = $first_item['level'] + $level; + } + + /* 保留level小于end_level的部分 */ + foreach ($options AS $key => $val) + { + if ($val['level'] >= $end_level) + { + unset($options[$key]); + } + } + } + + if ($re_type == true) + { + $select = ''; + foreach ($options AS $var) + { + $select .= ''; + } + + return $select; + } + else + { + foreach ($options AS $key => $value) + { + $options[$key]['url'] = build_uri('category', array('cid' => $value['cat_id']), $value['cat_name']); + } + + return $options; + } +} + +/** + * 过滤和排序所有分类,返回一个带有缩进级别的数组 + * + * @access private + * @param int $cat_id 上级分类ID + * @param array $arr 含有所有分类的数组 + * @param int $level 级别 + * @return void + */ +function cat_options($spec_cat_id, $arr) +{ + static $cat_options = array(); + + if (isset($cat_options[$spec_cat_id])) + { + return $cat_options[$spec_cat_id]; + } + + if (!isset($cat_options[0])) + { + $level = $last_cat_id = 0; + $options = $cat_id_array = $level_array = array(); + $data = read_static_cache('cat_option_static'); + if ($data === false) + { + while (!empty($arr)) + { + foreach ($arr AS $key => $value) + { + $cat_id = $value['cat_id']; + if ($level == 0 && $last_cat_id == 0) + { + if ($value['parent_id'] > 0) + { + break; + } + + $options[$cat_id] = $value; + $options[$cat_id]['level'] = $level; + $options[$cat_id]['id'] = $cat_id; + $options[$cat_id]['name'] = $value['cat_name']; + unset($arr[$key]); + + if ($value['has_children'] == 0) + { + continue; + } + $last_cat_id = $cat_id; + $cat_id_array = array($cat_id); + $level_array[$last_cat_id] = ++$level; + continue; + } + + if ($value['parent_id'] == $last_cat_id) + { + $options[$cat_id] = $value; + $options[$cat_id]['level'] = $level; + $options[$cat_id]['id'] = $cat_id; + $options[$cat_id]['name'] = $value['cat_name']; + unset($arr[$key]); + + if ($value['has_children'] > 0) + { + if (end($cat_id_array) != $last_cat_id) + { + $cat_id_array[] = $last_cat_id; + } + $last_cat_id = $cat_id; + $cat_id_array[] = $cat_id; + $level_array[$last_cat_id] = ++$level; + } + } + elseif ($value['parent_id'] > $last_cat_id) + { + break; + } + } + + $count = count($cat_id_array); + if ($count > 1) + { + $last_cat_id = array_pop($cat_id_array); + } + elseif ($count == 1) + { + if ($last_cat_id != end($cat_id_array)) + { + $last_cat_id = end($cat_id_array); + } + else + { + $level = 0; + $last_cat_id = 0; + $cat_id_array = array(); + continue; + } + } + + if ($last_cat_id && isset($level_array[$last_cat_id])) + { + $level = $level_array[$last_cat_id]; + } + else + { + $level = 0; + } + } + //如果数组过大,不采用静态缓存方式 + if (count($options) <= 2000) + { + write_static_cache('cat_option_static', $options); + } + } + else + { + $options = $data; + } + $cat_options[0] = $options; + } + else + { + $options = $cat_options[0]; + } + + if (!$spec_cat_id) + { + return $options; + } + else + { + if (empty($options[$spec_cat_id])) + { + return array(); + } + + $spec_cat_id_level = $options[$spec_cat_id]['level']; + + foreach ($options AS $key => $value) + { + if ($key != $spec_cat_id) + { + unset($options[$key]); + } + else + { + break; + } + } + + $spec_cat_id_array = array(); + foreach ($options AS $key => $value) + { + if (($spec_cat_id_level == $value['level'] && $value['cat_id'] != $spec_cat_id) || + ($spec_cat_id_level > $value['level'])) + { + break; + } + else + { + $spec_cat_id_array[$key] = $value; + } + } + $cat_options[$spec_cat_id] = $spec_cat_id_array; + + return $spec_cat_id_array; + } +} + +/** + * 载入配置信息 + * + * @access public + * @return array + */ +function load_config() +{ + $arr = array(); + + $data = read_static_cache('shop_config'); + if ($data === false) + { + $sql = 'SELECT code, value FROM ' . $GLOBALS['ecs']->table('shop_config') . ' WHERE parent_id > 0'; + $res = $GLOBALS['db']->getAll($sql); + + foreach ($res AS $row) + { + $arr[$row['code']] = $row['value']; + } + + /* 对数值型设置处理 */ + $arr['watermark_alpha'] = intval($arr['watermark_alpha']); + $arr['market_price_rate'] = floatval($arr['market_price_rate']); + $arr['integral_scale'] = floatval($arr['integral_scale']); + //$arr['integral_percent'] = floatval($arr['integral_percent']); + $arr['cache_time'] = intval($arr['cache_time']); + $arr['thumb_width'] = intval($arr['thumb_width']); + $arr['thumb_height'] = intval($arr['thumb_height']); + $arr['image_width'] = intval($arr['image_width']); + $arr['image_height'] = intval($arr['image_height']); + $arr['best_number'] = !empty($arr['best_number']) && intval($arr['best_number']) > 0 ? intval($arr['best_number']) : 3; + $arr['new_number'] = !empty($arr['new_number']) && intval($arr['new_number']) > 0 ? intval($arr['new_number']) : 3; + $arr['hot_number'] = !empty($arr['hot_number']) && intval($arr['hot_number']) > 0 ? intval($arr['hot_number']) : 3; + $arr['promote_number'] = !empty($arr['promote_number']) && intval($arr['promote_number']) > 0 ? intval($arr['promote_number']) : 3; + $arr['top_number'] = intval($arr['top_number']) > 0 ? intval($arr['top_number']) : 10; + $arr['history_number'] = intval($arr['history_number']) > 0 ? intval($arr['history_number']) : 5; + $arr['comments_number'] = intval($arr['comments_number']) > 0 ? intval($arr['comments_number']) : 5; + $arr['article_number'] = intval($arr['article_number']) > 0 ? intval($arr['article_number']) : 5; + $arr['page_size'] = intval($arr['page_size']) > 0 ? intval($arr['page_size']) : 10; + $arr['bought_goods'] = intval($arr['bought_goods']); + $arr['goods_name_length'] = intval($arr['goods_name_length']); + $arr['top10_time'] = intval($arr['top10_time']); + $arr['goods_gallery_number'] = intval($arr['goods_gallery_number']) ? intval($arr['goods_gallery_number']) : 5; + $arr['no_picture'] = !empty($arr['no_picture']) ? str_replace('../', './', $arr['no_picture']) : 'images/no_picture.gif'; // 修改默认商品图片的路径 + $arr['qq'] = !empty($arr['qq']) ? $arr['qq'] : ''; + $arr['ww'] = !empty($arr['ww']) ? $arr['ww'] : ''; + $arr['default_storage'] = isset($arr['default_storage']) ? intval($arr['default_storage']) : 1; + $arr['min_goods_amount'] = isset($arr['min_goods_amount']) ? floatval($arr['min_goods_amount']) : 0; + $arr['one_step_buy'] = empty($arr['one_step_buy']) ? 0 : 1; + $arr['invoice_type'] = empty($arr['invoice_type']) ? array('type' => array(), 'rate' => array()) : unserialize($arr['invoice_type']); + $arr['show_order_type'] = isset($arr['show_order_type']) ? $arr['show_order_type'] : 0; // 显示方式默认为列表方式 + $arr['help_open'] = isset($arr['help_open']) ? $arr['help_open'] : 1; // 显示方式默认为列表方式 + + if (!isset($GLOBALS['_CFG']['ecs_version'])) + { + /* 如果没有版本号则默认为2.0.5 */ + $GLOBALS['_CFG']['ecs_version'] = 'v2.0.5'; + } + + //限定语言项 + $lang_array = array('zh_cn', 'zh_tw', 'en_us'); + if (empty($arr['lang']) || !in_array($arr['lang'], $lang_array)) + { + $arr['lang'] = 'zh_cn'; // 默认语言为简体中文 + } + + if (empty($arr['integrate_code'])) + { + $arr['integrate_code'] = 'ecshop'; // 默认的会员整合插件为 ecshop + } + write_static_cache('shop_config', $arr); + } + else + { + $arr = $data; + } + + return $arr; +} + +/** + * 取得品牌列表 + * @return array 品牌列表 id => name + */ +function get_brand_list() +{ + $sql = 'SELECT brand_id, brand_name FROM ' . $GLOBALS['ecs']->table('brand') . ' ORDER BY sort_order'; + $res = $GLOBALS['db']->getAll($sql); + + $brand_list = array(); + foreach ($res AS $row) + { + $brand_list[$row['brand_id']] = addslashes($row['brand_name']); + } + + return $brand_list; +} + +/** + * 获得某个分类下 + * + * @access public + * @param int $cat + * @return array + */ +function get_brands($cat = 0, $app = 'brand') +{ + global $page_libs; + $template = basename(PHP_SELF); + $template = substr($template, 0, strrpos($template, '.')); + include_once(ROOT_PATH . ADMIN_PATH . '/includes/lib_template.php'); + static $static_page_libs = null; + if ($static_page_libs == null) + { + $static_page_libs = $page_libs; + } + + $children = ($cat > 0) ? ' AND ' . get_children($cat) : ''; + + $sql = "SELECT b.brand_id, b.brand_name, b.brand_logo, b.brand_desc, COUNT(*) AS goods_num, IF(b.brand_logo > '', '1', '0') AS tag ". + "FROM " . $GLOBALS['ecs']->table('brand') . "AS b, ". + $GLOBALS['ecs']->table('goods') . " AS g ". + "WHERE g.brand_id = b.brand_id $children AND is_show = 1 " . + " AND g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0 ". + "GROUP BY b.brand_id HAVING goods_num > 0 ORDER BY tag DESC, b.sort_order ASC"; + if (isset($static_page_libs[$template]['/library/brands.lbi'])) + { + $num = get_library_number("brands"); + $sql .= " LIMIT $num "; + } + $row = $GLOBALS['db']->getAll($sql); + + foreach ($row AS $key => $val) + { + $row[$key]['url'] = build_uri($app, array('cid' => $cat, 'bid' => $val['brand_id']), $val['brand_name']); + $row[$key]['brand_desc'] = htmlspecialchars($val['brand_desc'],ENT_QUOTES); + } + + return $row; +} + +/** + * 所有的促销活动信息 + * + * @access public + * @return array + */ +function get_promotion_info($goods_id = '') +{ + $snatch = array(); + $group = array(); + $auction = array(); + $package = array(); + $favourable = array(); + + $gmtime = gmtime(); + $sql = 'SELECT act_id, act_name, act_type, start_time, end_time FROM ' . $GLOBALS['ecs']->table('goods_activity') . " WHERE is_finished=0 AND start_time <= '$gmtime' AND end_time >= '$gmtime'"; + if(!empty($goods_id)) + { + $sql .= " AND goods_id = '$goods_id'"; + } + $res = $GLOBALS['db']->getAll($sql); + foreach ($res as $data) + { + switch ($data['act_type']) + { + case GAT_SNATCH: //夺宝奇兵 + $snatch[$data['act_id']]['act_name'] = $data['act_name']; + $snatch[$data['act_id']]['url'] = build_uri('snatch', array('sid' => $data['act_id'])); + $snatch[$data['act_id']]['time'] = sprintf($GLOBALS['_LANG']['promotion_time'], local_date('Y-m-d', $data['start_time']), local_date('Y-m-d', $data['end_time'])); + $snatch[$data['act_id']]['sort'] = $data['start_time']; + $snatch[$data['act_id']]['type'] = 'snatch'; + break; + + case GAT_GROUP_BUY: //团购 + $group[$data['act_id']]['act_name'] = $data['act_name']; + $group[$data['act_id']]['url'] = build_uri('group_buy', array('gbid' => $data['act_id'])); + $group[$data['act_id']]['time'] = sprintf($GLOBALS['_LANG']['promotion_time'], local_date('Y-m-d', $data['start_time']), local_date('Y-m-d', $data['end_time'])); + $group[$data['act_id']]['sort'] = $data['start_time']; + $group[$data['act_id']]['type'] = 'group_buy'; + break; + + case GAT_AUCTION: //拍卖 + $auction[$data['act_id']]['act_name'] = $data['act_name']; + $auction[$data['act_id']]['url'] = build_uri('auction', array('auid' => $data['act_id'])); + $auction[$data['act_id']]['time'] = sprintf($GLOBALS['_LANG']['promotion_time'], local_date('Y-m-d', $data['start_time']), local_date('Y-m-d', $data['end_time'])); + $auction[$data['act_id']]['sort'] = $data['start_time']; + $auction[$data['act_id']]['type'] = 'auction'; + break; + + case GAT_PACKAGE: //礼包 + $package[$data['act_id']]['act_name'] = $data['act_name']; + $package[$data['act_id']]['url'] = 'package.php#' . $data['act_id']; + $package[$data['act_id']]['time'] = sprintf($GLOBALS['_LANG']['promotion_time'], local_date('Y-m-d', $data['start_time']), local_date('Y-m-d', $data['end_time'])); + $package[$data['act_id']]['sort'] = $data['start_time']; + $package[$data['act_id']]['type'] = 'package'; + break; + } + } + + $user_rank = ',' . $_SESSION['user_rank'] . ','; + $favourable = array(); + $sql = 'SELECT act_id, act_range, act_range_ext, act_name, start_time, end_time FROM ' . $GLOBALS['ecs']->table('favourable_activity') . " WHERE start_time <= '$gmtime' AND end_time >= '$gmtime'"; + if(!empty($goods_id)) + { + $sql .= " AND CONCAT(',', user_rank, ',') LIKE '%" . $user_rank . "%'"; + } + $res = $GLOBALS['db']->getAll($sql); + + if(empty($goods_id)) + { + foreach ($res as $rows) + { + $favourable[$rows['act_id']]['act_name'] = $rows['act_name']; + $favourable[$rows['act_id']]['url'] = 'activity.php'; + $favourable[$rows['act_id']]['time'] = sprintf($GLOBALS['_LANG']['promotion_time'], local_date('Y-m-d', $rows['start_time']), local_date('Y-m-d', $rows['end_time'])); + $favourable[$rows['act_id']]['sort'] = $rows['start_time']; + $favourable[$rows['act_id']]['type'] = 'favourable'; + } + } + else + { + $sql = "SELECT cat_id, brand_id FROM " . $GLOBALS['ecs']->table('goods') . + "WHERE goods_id = '$goods_id'"; + $row = $GLOBALS['db']->getRow($sql); + $category_id = $row['cat_id']; + $brand_id = $row['brand_id']; + + foreach ($res as $rows) + { + if ($rows['act_range'] == FAR_ALL) + { + $favourable[$rows['act_id']]['act_name'] = $rows['act_name']; + $favourable[$rows['act_id']]['url'] = 'activity.php'; + $favourable[$rows['act_id']]['time'] = sprintf($GLOBALS['_LANG']['promotion_time'], local_date('Y-m-d', $rows['start_time']), local_date('Y-m-d', $rows['end_time'])); + $favourable[$rows['act_id']]['sort'] = $rows['start_time']; + $favourable[$rows['act_id']]['type'] = 'favourable'; + } + elseif ($rows['act_range'] == FAR_CATEGORY) + { + /* 找出分类id的子分类id */ + $id_list = array(); + $raw_id_list = explode(',', $rows['act_range_ext']); + foreach ($raw_id_list as $id) + { + $id_list = array_merge($id_list, array_keys(cat_list($id, 0, false))); + } + $ids = join(',', array_unique($id_list)); + + if (strpos(',' . $ids . ',', ',' . $category_id . ',') !== false) + { + $favourable[$rows['act_id']]['act_name'] = $rows['act_name']; + $favourable[$rows['act_id']]['url'] = 'activity.php'; + $favourable[$rows['act_id']]['time'] = sprintf($GLOBALS['_LANG']['promotion_time'], local_date('Y-m-d', $rows['start_time']), local_date('Y-m-d', $rows['end_time'])); + $favourable[$rows['act_id']]['sort'] = $rows['start_time']; + $favourable[$rows['act_id']]['type'] = 'favourable'; + } + } + elseif ($rows['act_range'] == FAR_BRAND) + { + if (strpos(',' . $rows['act_range_ext'] . ',', ',' . $brand_id . ',') !== false) + { + $favourable[$rows['act_id']]['act_name'] = $rows['act_name']; + $favourable[$rows['act_id']]['url'] = 'activity.php'; + $favourable[$rows['act_id']]['time'] = sprintf($GLOBALS['_LANG']['promotion_time'], local_date('Y-m-d', $rows['start_time']), local_date('Y-m-d', $rows['end_time'])); + $favourable[$rows['act_id']]['sort'] = $rows['start_time']; + $favourable[$rows['act_id']]['type'] = 'favourable'; + } + } + elseif ($rows['act_range'] == FAR_GOODS) + { + if (strpos(',' . $rows['act_range_ext'] . ',', ',' . $goods_id . ',') !== false) + { + $favourable[$rows['act_id']]['act_name'] = $rows['act_name']; + $favourable[$rows['act_id']]['url'] = 'activity.php'; + $favourable[$rows['act_id']]['time'] = sprintf($GLOBALS['_LANG']['promotion_time'], local_date('Y-m-d', $rows['start_time']), local_date('Y-m-d', $rows['end_time'])); + $favourable[$rows['act_id']]['sort'] = $rows['start_time']; + $favourable[$rows['act_id']]['type'] = 'favourable'; + } + } + } + } + +// if(!empty($goods_id)) +// { +// return array('snatch'=>$snatch, 'group_buy'=>$group, 'auction'=>$auction, 'favourable'=>$favourable); +// } + + $sort_time = array(); + $arr = array_merge($snatch, $group, $auction, $package, $favourable); + foreach($arr as $key => $value) + { + $sort_time[] = $value['sort']; + } + array_multisort($sort_time, SORT_NUMERIC, SORT_DESC, $arr); + + return $arr; +} + +/** + * 获得指定分类下所有底层分类的ID + * + * @access public + * @param integer $cat 指定的分类ID + * @return string + */ +function get_children($cat = 0) +{ + return 'g.cat_id ' . db_create_in(array_unique(array_merge(array($cat), array_keys(cat_list($cat, 0, false))))); +} + +/** + * 获得指定文章分类下所有底层分类的ID + * + * @access public + * @param integer $cat 指定的分类ID + * + * @return void + */ +function get_article_children ($cat = 0) +{ + return db_create_in(array_unique(array_merge(array($cat), array_keys(article_cat_list($cat, 0, false)))), 'cat_id'); +} + +/** + * 获取邮件模板 + * + * @access public + * @param: $tpl_name[string] 模板代码 + * + * @return array + */ +function get_mail_template($tpl_name) +{ + $sql = 'SELECT template_subject, is_html, template_content FROM ' . $GLOBALS['ecs']->table('mail_templates') . " WHERE template_code = '$tpl_name'"; + + return $GLOBALS['db']->GetRow($sql); + +} + +/** + * 记录订单操作记录 + * + * @access public + * @param string $order_sn 订单编号 + * @param integer $order_status 订单状态 + * @param integer $shipping_status 配送状态 + * @param integer $pay_status 付款状态 + * @param string $note 备注 + * @param string $username 用户名,用户自己的操作则为 buyer + * @return void + */ +function order_action($order_sn, $order_status, $shipping_status, $pay_status, $note = '', $username = null, $place = 0) +{ + if (is_null($username)) + { + $username = $_SESSION['admin_name']; + } + + $sql = 'INSERT INTO ' . $GLOBALS['ecs']->table('order_action') . + ' (order_id, action_user, order_status, shipping_status, pay_status, action_place, action_note, log_time) ' . + 'SELECT ' . + "order_id, '$username', '$order_status', '$shipping_status', '$pay_status', '$place', '$note', '" .gmtime() . "' " . + 'FROM ' . $GLOBALS['ecs']->table('order_info') . " WHERE order_sn = '$order_sn'"; + $GLOBALS['db']->query($sql); +} + +/** + * 格式化商品价格 + * + * @access public + * @param float $price 商品价格 + * @return string + */ +function price_format($price, $change_price = true) +{ + if($price==='') + { + $price=0; + } + if ($change_price && defined('ECS_ADMIN') === false) + { + switch ($GLOBALS['_CFG']['price_format']) + { + case 0: + $price = number_format($price, 2, '.', ''); + break; + case 1: // 保留不为 0 的尾数 + $price = preg_replace('/(.*)(\\.)([0-9]*?)0+$/', '\1\2\3', number_format($price, 2, '.', '')); + + if (substr($price, -1) == '.') + { + $price = substr($price, 0, -1); + } + break; + case 2: // 不四舍五入,保留1位 + $price = substr(number_format($price, 2, '.', ''), 0, -1); + break; + case 3: // 直接取整 + $price = intval($price); + break; + case 4: // 四舍五入,保留 1 位 + $price = number_format($price, 1, '.', ''); + break; + case 5: // 先四舍五入,不保留小数 + $price = round($price); + break; + } + } + else + { + $price = number_format($price, 2, '.', ''); + } + + return sprintf($GLOBALS['_CFG']['currency_format'], $price); +} + +/** + * 返回订单中的虚拟商品 + * + * @access public + * @param int $order_id 订单id值 + * @param bool $shipping 是否已经发货 + * + * @return array() + */ +function get_virtual_goods($order_id, $shipping = false) +{ + if ($shipping) + { + $sql = 'SELECT goods_id, goods_name, send_number AS num, extension_code FROM '. + $GLOBALS['ecs']->table('order_goods') . + " WHERE order_id = '$order_id' AND extension_code > ''"; + } + else + { + $sql = 'SELECT goods_id, goods_name, (goods_number - send_number) AS num, extension_code FROM '. + $GLOBALS['ecs']->table('order_goods') . + " WHERE order_id = '$order_id' AND is_real = 0 AND (goods_number - send_number) > 0 AND extension_code > '' "; + } + $res = $GLOBALS['db']->getAll($sql); + + $virtual_goods = array(); + foreach ($res AS $row) + { + $virtual_goods[$row['extension_code']][] = array('goods_id' => $row['goods_id'], 'goods_name' => $row['goods_name'], 'num' => $row['num']); + } + + return $virtual_goods; +} + +/** + * 虚拟商品发货 + * + * @access public + * @param array $virtual_goods 虚拟商品数组 + * @param string $msg 错误信息 + * @param string $order_sn 订单号。 + * @param string $process 设定当前流程:split,发货分单流程;other,其他,默认。 + * + * @return bool + */ +function virtual_goods_ship(&$virtual_goods, &$msg, $order_sn, $return_result = false, $process = 'other') +{ + $virtual_card = array(); + foreach ($virtual_goods AS $code => $goods_list) + { + /* 只处理虚拟卡 */ + if ($code == 'virtual_card') + { + foreach ($goods_list as $goods) + { + if (virtual_card_shipping($goods, $order_sn, $msg, $process)) + { + if ($return_result) + { + $virtual_card[] = array('goods_id'=>$goods['goods_id'], 'goods_name'=>$goods['goods_name'], 'info'=>virtual_card_result($order_sn, $goods)); + } + } + else + { + return false; + } + } + $GLOBALS['smarty']->assign('virtual_card', $virtual_card); + } + } + + return true; +} + +/** + * 虚拟卡发货 + * + * @access public + * @param string $goods 商品详情数组 + * @param string $order_sn 本次操作的订单 + * @param string $msg 返回信息 + * @param string $process 设定当前流程:split,发货分单流程;other,其他,默认。 + * + * @return boolen + */ +function virtual_card_shipping ($goods, $order_sn, &$msg, $process = 'other') +{ + /* 包含加密解密函数所在文件 */ + include_once(ROOT_PATH . 'includes/lib_code.php'); + + /* 检查有没有缺货 */ + $sql = "SELECT COUNT(*) FROM ".$GLOBALS['ecs']->table('virtual_card')." WHERE goods_id = '$goods[goods_id]' AND is_saled = 0 "; + $num = $GLOBALS['db']->GetOne($sql); + + if ($num < $goods['num']) + { + $msg .= sprintf($GLOBALS['_LANG']['virtual_card_oos'], $goods['goods_name']); + + return false; + } + + /* 取出卡片信息 */ + $sql = "SELECT card_id, card_sn, card_password, end_date, crc32 FROM ".$GLOBALS['ecs']->table('virtual_card')." WHERE goods_id = '$goods[goods_id]' AND is_saled = 0 LIMIT " . $goods['num']; + $arr = $GLOBALS['db']->getAll($sql); + + $card_ids = array(); + $cards = array(); + + foreach ($arr as $virtual_card) + { + $card_info = array(); + + /* 卡号和密码解密 */ + if ($virtual_card['crc32'] == 0 || $virtual_card['crc32'] == crc32(AUTH_KEY)) + { + $card_info['card_sn'] = decrypt($virtual_card['card_sn']); + $card_info['card_password'] = decrypt($virtual_card['card_password']); + } + elseif ($virtual_card['crc32'] == crc32(OLD_AUTH_KEY)) + { + $card_info['card_sn'] = decrypt($virtual_card['card_sn'], OLD_AUTH_KEY); + $card_info['card_password'] = decrypt($virtual_card['card_password'], OLD_AUTH_KEY); + } + else + { + $msg .= 'error key'; + + return false; + } + $card_info['end_date'] = date($GLOBALS['_CFG']['date_format'], $virtual_card['end_date']); + $card_ids[] = $virtual_card['card_id']; + $cards[] = $card_info; + } + + /* 标记已经取出的卡片 */ + $sql = "UPDATE ".$GLOBALS['ecs']->table('virtual_card')." SET ". + "is_saled = 1 ,". + "order_sn = '$order_sn' ". + "WHERE " . db_create_in($card_ids, 'card_id'); + if (!$GLOBALS['db']->query($sql, 'SILENT')) + { + $msg .= $GLOBALS['db']->error(); + + return false; + } + + /* 更新库存 */ + $sql = "UPDATE ".$GLOBALS['ecs']->table('goods'). " SET goods_number = goods_number - '$goods[num]' WHERE goods_id = '$goods[goods_id]'"; + $GLOBALS['db']->query($sql); + + if (true) + { + /* 获取订单信息 */ + $sql = "SELECT order_id, order_sn, consignee, email FROM ".$GLOBALS['ecs']->table('order_info'). " WHERE order_sn = '$order_sn'"; + $order = $GLOBALS['db']->GetRow($sql); + + /* 更新订单信息 */ + if ($process == 'split') + { + $sql = "UPDATE ".$GLOBALS['ecs']->table('order_goods'). " + SET send_number = send_number + '" . $goods['num'] . "' + WHERE order_id = '" . $order['order_id'] . "' + AND goods_id = '" . $goods['goods_id'] . "' "; + } + else + { + $sql = "UPDATE ".$GLOBALS['ecs']->table('order_goods'). " + SET send_number = '" . $goods['num'] . "' + WHERE order_id = '" . $order['order_id'] . "' + AND goods_id = '" . $goods['goods_id'] . "' "; + } + + if (!$GLOBALS['db']->query($sql, 'SILENT')) + { + $msg .= $GLOBALS['db']->error(); + + return false; + } + } + + /* 发送邮件 */ + $GLOBALS['smarty']->assign('virtual_card', $cards); + $GLOBALS['smarty']->assign('order', $order); + $GLOBALS['smarty']->assign('goods', $goods); + + $GLOBALS['smarty']->assign('send_time', date('Y-m-d H:i:s')); + $GLOBALS['smarty']->assign('shop_name', $GLOBALS['_CFG']['shop_name']); + $GLOBALS['smarty']->assign('send_date', date('Y-m-d')); + $GLOBALS['smarty']->assign('sent_date', date('Y-m-d')); + + $tpl = get_mail_template('virtual_card'); + $content = $GLOBALS['smarty']->fetch('str:' . $tpl['template_content']); + send_mail($order['consignee'], $order['email'], $tpl['template_subject'], $content, $tpl['is_html']); + + return true; +} + +/** + * 返回虚拟卡信息 + * + * @access public + * @param + * + * @return void + */ +function virtual_card_result($order_sn, $goods) +{ + /* 包含加密解密函数所在文件 */ + include_once(ROOT_PATH . 'includes/lib_code.php'); + + /* 获取已经发送的卡片数据 */ + $sql = "SELECT card_sn, card_password, end_date, crc32 FROM ".$GLOBALS['ecs']->table('virtual_card')." WHERE goods_id= '$goods[goods_id]' AND order_sn = '$order_sn' "; + $res= $GLOBALS['db']->query($sql); + + $cards = array(); + + while ($row = $GLOBALS['db']->FetchRow($res)) + { + /* 卡号和密码解密 */ + if ($row['crc32'] == 0 || $row['crc32'] == crc32(AUTH_KEY)) + { + $row['card_sn'] = decrypt($row['card_sn']); + $row['card_password'] = decrypt($row['card_password']); + } + elseif ($row['crc32'] == crc32(OLD_AUTH_KEY)) + { + $row['card_sn'] = decrypt($row['card_sn'], OLD_AUTH_KEY); + $row['card_password'] = decrypt($row['card_password'], OLD_AUTH_KEY); + } + else + { + $row['card_sn'] = '***'; + $row['card_password'] = '***'; + } + + $cards[] = array('card_sn'=>$row['card_sn'], 'card_password'=>$row['card_password'], 'end_date'=>date($GLOBALS['_CFG']['date_format'], $row['end_date'])); + } + + return $cards; +} + +/** + * 获取指定 id snatch 活动的结果 + * + * @access public + * @param int $id snatch_id + * + * @return array array(user_name, bie_price, bid_time, num) + * num通常为1,如果为2表示有2个用户取到最小值,但结果只返回最早出价用户。 + */ +function get_snatch_result($id) +{ + $sql = 'SELECT u.user_id, u.user_name, u.email, lg.bid_price, lg.bid_time, count(*) as num' . + ' FROM ' . $GLOBALS['ecs']->table('snatch_log') . ' AS lg '. + ' LEFT JOIN ' . $GLOBALS['ecs']->table('users') . ' AS u ON lg.user_id = u.user_id'. + " WHERE lg.snatch_id = '$id'". + ' GROUP BY lg.bid_price' . + ' ORDER BY num ASC, lg.bid_price ASC, lg.bid_time ASC LIMIT 1'; + $rec = $GLOBALS['db']->GetRow($sql); + + if ($rec) + { + $rec['bid_time'] = local_date($GLOBALS['_CFG']['time_format'], $rec['bid_time']); + $rec['formated_bid_price'] = price_format($rec['bid_price'], false); + + /* 活动信息 */ + $sql = 'SELECT ext_info " . + " FROM ' . $GLOBALS['ecs']->table('goods_activity') . + " WHERE act_id= '$id' AND act_type=" . GAT_SNATCH. + " LIMIT 1"; + $row = $GLOBALS['db']->getOne($sql); + $info = unserialize($row); + + if (!empty($info['max_price'])) + { + $rec['buy_price'] = ($rec['bid_price'] > $info['max_price']) ? $info['max_price'] : $rec['bid_price']; + } + else + { + $rec['buy_price'] = $rec['bid_price']; + } + + + + /* 检查订单 */ + $sql = "SELECT COUNT(*)" . + " FROM " . $GLOBALS['ecs']->table('order_info') . + " WHERE extension_code = 'snatch'" . + " AND extension_id = '$id'" . + " AND order_status " . db_create_in(array(OS_CONFIRMED, OS_UNCONFIRMED)); + + $rec['order_count'] = $GLOBALS['db']->getOne($sql); + } + + return $rec; +} + +/** + * 清除指定后缀的模板缓存或编译文件 + * + * @access public + * @param bool $is_cache 是否清除缓存还是清出编译文件 + * @param string $ext 需要删除的文件名,不包含后缀 + * + * @return int 返回清除的文件个数 + */ +function clear_tpl_files($is_cache = true, $ext = '') +{ + $dirs = array(); + + if (isset($GLOBALS['shop_id']) && $GLOBALS['shop_id'] > 0) + { + $tmp_dir = DATA_DIR ; + } + else + { + $tmp_dir = 'temp'; + } + if ($is_cache) + { + $cache_dir = ROOT_PATH . $tmp_dir . '/caches/'; + $dirs[] = ROOT_PATH . $tmp_dir . '/query_caches/'; + $dirs[] = ROOT_PATH . $tmp_dir . '/static_caches/'; + for($i = 0; $i < 16; $i++) + { + $hash_dir = $cache_dir . dechex($i); + $dirs[] = $hash_dir . '/'; + } + } + else + { + $dirs[] = ROOT_PATH . $tmp_dir . '/compiled/'; + $dirs[] = ROOT_PATH . $tmp_dir . '/compiled/admin/'; + } + + $str_len = strlen($ext); + $count = 0; + + foreach ($dirs AS $dir) + { + $folder = @opendir($dir); + + if ($folder === false) + { + continue; + } + + while ($file = readdir($folder)) + { + if ($file == '.' || $file == '..' || $file == 'index.htm' || $file == 'index.html') + { + continue; + } + if (is_file($dir . $file)) + { + /* 如果有文件名则判断是否匹配 */ + $pos = ($is_cache) ? strrpos($file, '_') : strrpos($file, '.'); + + if ($str_len > 0 && $pos !== false) + { + $ext_str = substr($file, 0, $pos); + + if ($ext_str == $ext) + { + if (@unlink($dir . $file)) + { + $count++; + } + } + } + else + { + if (@unlink($dir . $file)) + { + $count++; + } + } + } + } + closedir($folder); + } + + return $count; +} + +/** + * 清除模版编译文件 + * + * @access public + * @param mix $ext 模版文件名, 不包含后缀 + * @return void + */ +function clear_compiled_files($ext = '') +{ + return clear_tpl_files(false, $ext); +} + +/** + * 清除缓存文件 + * + * @access public + * @param mix $ext 模版文件名, 不包含后缀 + * @return void + */ +function clear_cache_files($ext = '') +{ + return clear_tpl_files(true, $ext); +} + +/** + * 清除模版编译和缓存文件 + * + * @access public + * @param mix $ext 模版文件名后缀 + * @return void + */ +function clear_all_files($ext = '') +{ + return clear_tpl_files(false, $ext) + clear_tpl_files(true, $ext); +} + +/** + * 页面上调用的js文件 + * + * @access public + * @param string $files + * @return void + */ +function smarty_insert_scripts($args) +{ + static $scripts = array(); + + $arr = explode(',', str_replace(' ','',$args['files'])); + + $str = ''; + foreach ($arr AS $val) + { + if (in_array($val, $scripts) == false) + { + $scripts[] = $val; + if ($val{0} == '.') + { + $str .= ''; + } + else + { + $str .= ''; + } + } + } + + return $str; +} + +/** + * 创建分页的列表 + * + * @access public + * @param integer $count + * @return string + */ +function smarty_create_pages($params) +{ + extract($params); + + $str = ''; + $len = 10; + + if (empty($page)) + { + $page = 1; + } + + if (!empty($count)) + { + $step = 1; + $str .= ""; + + for ($i = 2; $i < $count; $i += $step) + { + $step = ($i >= $page + $len - 1 || $i <= $page - $len + 1) ? $len : 1; + $str .= "'; + } + + return $select; + } + else + { + foreach ($options AS $key => $value) + { + $options[$key]['url'] = build_uri('article_cat', array('acid' => $value['cat_id']), $value['cat_name']); + } + return $options; + } +} + +/** + * 过滤和排序所有文章分类,返回一个带有缩进级别的数组 + * + * @access private + * @param int $cat_id 上级分类ID + * @param array $arr 含有所有分类的数组 + * @param int $level 级别 + * @return void + */ +function article_cat_options($spec_cat_id, $arr) +{ + static $cat_options = array(); + + if (isset($cat_options[$spec_cat_id])) + { + return $cat_options[$spec_cat_id]; + } + + if (!isset($cat_options[0])) + { + $level = $last_cat_id = 0; + $options = $cat_id_array = $level_array = array(); + while (!empty($arr)) + { + foreach ($arr AS $key => $value) + { + $cat_id = $value['cat_id']; + if ($level == 0 && $last_cat_id == 0) + { + if ($value['parent_id'] > 0) + { + break; + } + + $options[$cat_id] = $value; + $options[$cat_id]['level'] = $level; + $options[$cat_id]['id'] = $cat_id; + $options[$cat_id]['name'] = $value['cat_name']; + unset($arr[$key]); + + if ($value['has_children'] == 0) + { + continue; + } + $last_cat_id = $cat_id; + $cat_id_array = array($cat_id); + $level_array[$last_cat_id] = ++$level; + continue; + } + + if ($value['parent_id'] == $last_cat_id) + { + $options[$cat_id] = $value; + $options[$cat_id]['level'] = $level; + $options[$cat_id]['id'] = $cat_id; + $options[$cat_id]['name'] = $value['cat_name']; + unset($arr[$key]); + + if ($value['has_children'] > 0) + { + if (end($cat_id_array) != $last_cat_id) + { + $cat_id_array[] = $last_cat_id; + } + $last_cat_id = $cat_id; + $cat_id_array[] = $cat_id; + $level_array[$last_cat_id] = ++$level; + } + } + elseif ($value['parent_id'] > $last_cat_id) + { + break; + } + } + + $count = count($cat_id_array); + if ($count > 1) + { + $last_cat_id = array_pop($cat_id_array); + } + elseif ($count == 1) + { + if ($last_cat_id != end($cat_id_array)) + { + $last_cat_id = end($cat_id_array); + } + else + { + $level = 0; + $last_cat_id = 0; + $cat_id_array = array(); + continue; + } + } + + if ($last_cat_id && isset($level_array[$last_cat_id])) + { + $level = $level_array[$last_cat_id]; + } + else + { + $level = 0; + } + } + $cat_options[0] = $options; + } + else + { + $options = $cat_options[0]; + } + + if (!$spec_cat_id) + { + return $options; + } + else + { + if (empty($options[$spec_cat_id])) + { + return array(); + } + + $spec_cat_id_level = $options[$spec_cat_id]['level']; + + foreach ($options AS $key => $value) + { + if ($key != $spec_cat_id) + { + unset($options[$key]); + } + else + { + break; + } + } + + $spec_cat_id_array = array(); + foreach ($options AS $key => $value) + { + if (($spec_cat_id_level == $value['level'] && $value['cat_id'] != $spec_cat_id) || + ($spec_cat_id_level > $value['level'])) + { + break; + } + else + { + $spec_cat_id_array[$key] = $value; + } + } + $cat_options[$spec_cat_id] = $spec_cat_id_array; + + return $spec_cat_id_array; + } +} + +/** + * 调用UCenter的函数 + * + * @param string $func + * @param array $params + * + * @return mixed + */ +function uc_call($func, $params=null) +{ + restore_error_handler(); + if (!function_exists($func)) + { + include_once(ROOT_PATH . 'uc_client/client.php'); + } + + $res = call_user_func_array($func, $params); + + set_error_handler('exception_handler'); + + return $res; +} + +/** + * error_handle回调函数 + * + * @return + */ +function exception_handler($errno, $errstr, $errfile, $errline) +{ + return; +} + +/** + * 重新获得商品图片与商品相册的地址 + * + * @param int $goods_id 商品ID + * @param string $image 原商品相册图片地址 + * @param boolean $thumb 是否为缩略图 + * @param string $call 调用方法(商品图片还是商品相册) + * @param boolean $del 是否删除图片 + * + * @return string $url + */ +function get_image_path($goods_id, $image='', $thumb=false, $call='goods', $del=false) +{ + $url = empty($image) ? $GLOBALS['_CFG']['no_picture'] : $image; + return $url; +} + +/** + * 调用使用UCenter插件时的函数 + * + * @param string $func + * @param array $params + * + * @return mixed + */ +function user_uc_call($func, $params = null) +{ + if (isset($GLOBALS['_CFG']['integrate_code']) && $GLOBALS['_CFG']['integrate_code'] == 'ucenter') + { + restore_error_handler(); + if (!function_exists($func)) + { + include_once(ROOT_PATH . 'includes/lib_uc.php'); + } + + $res = call_user_func_array($func, $params); + + set_error_handler('exception_handler'); + + return $res; + } + else + { + return; + } + +} + +/** + * 取得商品优惠价格列表 + * + * @param string $goods_id 商品编号 + * @param string $price_type 价格类别(0为全店优惠比率,1为商品优惠价格,2为分类优惠比率) + * + * @return 优惠价格列表 + */ +function get_volume_price_list($goods_id, $price_type = '1') +{ + $volume_price = array(); + $temp_index = '0'; + + $sql = "SELECT `volume_number` , `volume_price`". + " FROM " .$GLOBALS['ecs']->table('volume_price'). "". + " WHERE `goods_id` = '" . $goods_id . "' AND `price_type` = '" . $price_type . "'". + " ORDER BY `volume_number`"; + + $res = $GLOBALS['db']->getAll($sql); + + foreach ($res as $k => $v) + { + $volume_price[$temp_index] = array(); + $volume_price[$temp_index]['number'] = $v['volume_number']; + $volume_price[$temp_index]['price'] = $v['volume_price']; + $volume_price[$temp_index]['format_price'] = price_format($v['volume_price']); + $temp_index ++; + } + return $volume_price; +} + +/** + * 取得商品最终使用价格 + * + * @param string $goods_id 商品编号 + * @param string $goods_num 购买数量 + * @param boolean $is_spec_price 是否加入规格价格 + * @param mix $spec 规格ID的数组或者逗号分隔的字符串 + * + * @return 商品最终购买价格 + */ +function get_final_price($goods_id, $goods_num = '1', $is_spec_price = false, $spec = array()) +{ + $final_price = '0'; //商品最终购买价格 + $volume_price = '0'; //商品优惠价格 + $promote_price = '0'; //商品促销价格 + $user_price = '0'; //商品会员价格 + + //取得商品优惠价格列表 + $price_list = get_volume_price_list($goods_id, '1'); + + if (!empty($price_list)) + { + foreach ($price_list as $value) + { + if ($goods_num >= $value['number']) + { + $volume_price = $value['price']; + } + } + } + + //取得商品促销价格列表 + /* 取得商品信息 */ + $sql = "SELECT g.promote_price, g.promote_start_date, g.promote_end_date, ". + "IFNULL(mp.user_price, g.shop_price * '" . $_SESSION['discount'] . "') AS shop_price ". + " FROM " .$GLOBALS['ecs']->table('goods'). " AS g ". + " LEFT JOIN " . $GLOBALS['ecs']->table('member_price') . " AS mp ". + "ON mp.goods_id = g.goods_id AND mp.user_rank = '" . $_SESSION['user_rank']. "' ". + " WHERE g.goods_id = '" . $goods_id . "'" . + " AND g.is_delete = 0"; + $goods = $GLOBALS['db']->getRow($sql); + + /* 计算商品的促销价格 */ + if ($goods['promote_price'] > 0) + { + $promote_price = bargain_price($goods['promote_price'], $goods['promote_start_date'], $goods['promote_end_date']); + } + else + { + $promote_price = 0; + } + + //取得商品会员价格列表 + $user_price = $goods['shop_price']; + + //比较商品的促销价格,会员价格,优惠价格 + if (empty($volume_price) && empty($promote_price)) + { + //如果优惠价格,促销价格都为空则取会员价格 + $final_price = $user_price; + } + elseif (!empty($volume_price) && empty($promote_price)) + { + //如果优惠价格为空时不参加这个比较。 + $final_price = min($volume_price, $user_price); + } + elseif (empty($volume_price) && !empty($promote_price)) + { + //如果促销价格为空时不参加这个比较。 + $final_price = min($promote_price, $user_price); + } + elseif (!empty($volume_price) && !empty($promote_price)) + { + //取促销价格,会员价格,优惠价格最小值 + $final_price = min($volume_price, $promote_price, $user_price); + } + else + { + $final_price = $user_price; + } + + //如果需要加入规格价格 + if ($is_spec_price) + { + if (!empty($spec)) + { + $spec_price = spec_price($spec); + $final_price += $spec_price; + } + } + + //返回商品最终购买价格 + return $final_price; +} + +/** + * 将 goods_attr_id 的序列按照 attr_id 重新排序 + * + * 注意:非规格属性的id会被排除 + * + * @access public + * @param array $goods_attr_id_array 一维数组 + * @param string $sort 序号:asc|desc,默认为:asc + * + * @return string + */ +function sort_goods_attr_id_array($goods_attr_id_array, $sort = 'asc') +{ + if (empty($goods_attr_id_array)) + { + return $goods_attr_id_array; + } + + //重新排序 + $sql = "SELECT a.attr_type, v.attr_value, v.goods_attr_id + FROM " .$GLOBALS['ecs']->table('attribute'). " AS a + LEFT JOIN " .$GLOBALS['ecs']->table('goods_attr'). " AS v + ON v.attr_id = a.attr_id + AND a.attr_type = 1 + WHERE v.goods_attr_id " . db_create_in($goods_attr_id_array) . " + ORDER BY a.attr_id $sort"; + $row = $GLOBALS['db']->GetAll($sql); + + $return_arr = array(); + foreach ($row as $value) + { + $return_arr['sort'][] = $value['goods_attr_id']; + + $return_arr['row'][$value['goods_attr_id']] = $value; + } + + return $return_arr; +} + +/** + * + * 是否存在规格 + * + * @access public + * @param array $goods_attr_id_array 一维数组 + * + * @return string + */ +function is_spec($goods_attr_id_array, $sort = 'asc') +{ + if (empty($goods_attr_id_array)) + { + return $goods_attr_id_array; + } + + //重新排序 + $sql = "SELECT a.attr_type, v.attr_value, v.goods_attr_id + FROM " .$GLOBALS['ecs']->table('attribute'). " AS a + LEFT JOIN " .$GLOBALS['ecs']->table('goods_attr'). " AS v + ON v.attr_id = a.attr_id + AND a.attr_type = 1 + WHERE v.goods_attr_id " . db_create_in($goods_attr_id_array) . " + ORDER BY a.attr_id $sort"; + $row = $GLOBALS['db']->GetAll($sql); + + $return_arr = array(); + foreach ($row as $value) + { + $return_arr['sort'][] = $value['goods_attr_id']; + + $return_arr['row'][$value['goods_attr_id']] = $value; + } + + if(!empty($return_arr)) + { + return true; + } + else + { + return false; + } +} + +/** + * 获取指定id package 的信息 + * + * @access public + * @param int $id package_id + * + * @return array array(package_id, package_name, goods_id,start_time, end_time, min_price, integral) + */ +function get_package_info($id) +{ + global $ecs, $db,$_CFG; + $id = is_numeric($id)?intval($id):0; + $now = gmtime(); + + $sql = "SELECT act_id AS id, act_name AS package_name, goods_id , goods_name, start_time, end_time, act_desc, ext_info". + " FROM " . $GLOBALS['ecs']->table('goods_activity') . + " WHERE act_id='$id' AND act_type = " . GAT_PACKAGE; + + $package = $db->GetRow($sql); + + /* 将时间转成可阅读格式 */ + if ($package['start_time'] <= $now && $package['end_time'] >= $now) + { + $package['is_on_sale'] = "1"; + } + else + { + $package['is_on_sale'] = "0"; + } + $package['start_time'] = local_date('Y-m-d H:i', $package['start_time']); + $package['end_time'] = local_date('Y-m-d H:i', $package['end_time']); + $row = unserialize($package['ext_info']); + unset($package['ext_info']); + if ($row) + { + foreach ($row as $key=>$val) + { + $package[$key] = $val; + } + } + + $sql = "SELECT pg.package_id, pg.goods_id, pg.goods_number, pg.admin_id, ". + " g.goods_sn, g.goods_name, g.market_price, g.goods_thumb, g.is_real, ". + " IFNULL(mp.user_price, g.shop_price * '$_SESSION[discount]') AS rank_price " . + " FROM " . $GLOBALS['ecs']->table('package_goods') . " AS pg ". + " LEFT JOIN ". $GLOBALS['ecs']->table('goods') . " AS g ". + " ON g.goods_id = pg.goods_id ". + " LEFT JOIN " . $GLOBALS['ecs']->table('member_price') . " AS mp ". + "ON mp.goods_id = g.goods_id AND mp.user_rank = '$_SESSION[user_rank]' ". + " WHERE pg.package_id = " . $id. " ". + " ORDER BY pg.package_id, pg.goods_id"; + + $goods_res = $GLOBALS['db']->getAll($sql); + + $market_price = 0; + $real_goods_count = 0; + $virtual_goods_count = 0; + + foreach($goods_res as $key => $val) + { + $goods_res[$key]['goods_thumb'] = get_image_path($val['goods_id'], $val['goods_thumb'], true); + $goods_res[$key]['market_price_format'] = price_format($val['market_price']); + $goods_res[$key]['rank_price_format'] = price_format($val['rank_price']); + $market_price += $val['market_price'] * $val['goods_number']; + /* 统计实体商品和虚拟商品的个数 */ + if ($val['is_real']) + { + $real_goods_count++; + } + else + { + $virtual_goods_count++; + } + } + + if ($real_goods_count > 0) + { + $package['is_real'] = 1; + } + else + { + $package['is_real'] = 0; + } + + $package['goods_list'] = $goods_res; + $package['market_package'] = $market_price; + $package['market_package_format'] = price_format($market_price); + $package['package_price_format'] = price_format($package['package_price']); + + return $package; +} + +/** + * 获得指定礼包的商品 + * + * @access public + * @param integer $package_id + * @return array + */ +function get_package_goods($package_id) +{ + $sql = "SELECT pg.goods_id, g.goods_name, pg.goods_number, p.goods_attr, p.product_number, p.product_id + FROM " . $GLOBALS['ecs']->table('package_goods') . " AS pg + LEFT JOIN " .$GLOBALS['ecs']->table('goods') . " AS g ON pg.goods_id = g.goods_id + LEFT JOIN " . $GLOBALS['ecs']->table('products') . " AS p ON pg.product_id = p.product_id + WHERE pg.package_id = '$package_id'"; + if ($package_id == 0) + { + $sql .= " AND pg.admin_id = '$_SESSION[admin_id]'"; + } + $resource = $GLOBALS['db']->query($sql); + if (!$resource) + { + return array(); + } + + $row = array(); + + /* 生成结果数组 取存在货品的商品id 组合商品id与货品id */ + $good_product_str = ''; + while ($_row = $GLOBALS['db']->fetch_array($resource)) + { + if ($_row['product_id'] > 0) + { + /* 取存商品id */ + $good_product_str .= ',' . $_row['goods_id']; + + /* 组合商品id与货品id */ + $_row['g_p'] = $_row['goods_id'] . '_' . $_row['product_id']; + } + else + { + /* 组合商品id与货品id */ + $_row['g_p'] = $_row['goods_id']; + } + + //生成结果数组 + $row[] = $_row; + } + $good_product_str = trim($good_product_str, ','); + + /* 释放空间 */ + unset($resource, $_row, $sql); + + /* 取商品属性 */ + if ($good_product_str != '') + { + $sql = "SELECT goods_attr_id, attr_value FROM " .$GLOBALS['ecs']->table('goods_attr'). " WHERE goods_id IN ($good_product_str)"; + $result_goods_attr = $GLOBALS['db']->getAll($sql); + + $_goods_attr = array(); + foreach ($result_goods_attr as $value) + { + $_goods_attr[$value['goods_attr_id']] = $value['attr_value']; + } + } + + /* 过滤货品 */ + $format[0] = '%s[%s]--[%d]'; + $format[1] = '%s--[%d]'; + foreach ($row as $key => $value) + { + if ($value['goods_attr'] != '') + { + $goods_attr_array = explode('|', $value['goods_attr']); + + $goods_attr = array(); + foreach ($goods_attr_array as $_attr) + { + $goods_attr[] = $_goods_attr[$_attr]; + } + + $row[$key]['goods_name'] = sprintf($format[0], $value['goods_name'], implode(',', $goods_attr), $value['goods_number']); + } + else + { + $row[$key]['goods_name'] = sprintf($format[1], $value['goods_name'], $value['goods_number']); + } + } + + return $row; +} + +/** + * 取商品的货品列表 + * + * @param mixed $goods_id 单个商品id;多个商品id数组;以逗号分隔商品id字符串 + * @param string $conditions sql条件 + * + * @return array + */ +function get_good_products($goods_id, $conditions = '') +{ + if (empty($goods_id)) + { + return array(); + } + + switch (gettype($goods_id)) + { + case 'integer': + + $_goods_id = "goods_id = '" . intval($goods_id) . "'"; + + break; + + case 'string': + case 'array': + + $_goods_id = db_create_in($goods_id, 'goods_id'); + + break; + } + + /* 取货品 */ + $sql = "SELECT * FROM " .$GLOBALS['ecs']->table('products'). " WHERE $_goods_id $conditions"; + $result_products = $GLOBALS['db']->getAll($sql); + + /* 取商品属性 */ + $sql = "SELECT goods_attr_id, attr_value FROM " .$GLOBALS['ecs']->table('goods_attr'). " WHERE $_goods_id"; + $result_goods_attr = $GLOBALS['db']->getAll($sql); + + $_goods_attr = array(); + foreach ($result_goods_attr as $value) + { + $_goods_attr[$value['goods_attr_id']] = $value['attr_value']; + } + + /* 过滤货品 */ + foreach ($result_products as $key => $value) + { + $goods_attr_array = explode('|', $value['goods_attr']); + if (is_array($goods_attr_array)) + { + $goods_attr = array(); + foreach ($goods_attr_array as $_attr) + { + $goods_attr[] = $_goods_attr[$_attr]; + } + + $goods_attr_str = implode(',', $goods_attr); + } + + $result_products[$key]['goods_attr_str'] = $goods_attr_str; + } + + return $result_products; +} + +/** + * 取商品的下拉框Select列表 + * + * @param int $goods_id 商品id + * + * @return array + */ +function get_good_products_select($goods_id) +{ + $return_array = array(); + $products = get_good_products($goods_id); + + if (empty($products)) + { + return $return_array; + } + + foreach ($products as $value) + { + $return_array[$value['product_id']] = $value['goods_attr_str']; + } + + return $return_array; +} + +/** + * 取商品的规格列表 + * + * @param int $goods_id 商品id + * @param string $conditions sql条件 + * + * @return array + */ +function get_specifications_list($goods_id, $conditions = '') +{ + /* 取商品属性 */ + $sql = "SELECT ga.goods_attr_id, ga.attr_id, ga.attr_value, a.attr_name + FROM " .$GLOBALS['ecs']->table('goods_attr'). " AS ga, " .$GLOBALS['ecs']->table('attribute'). " AS a + WHERE ga.attr_id = a.attr_id + AND ga.goods_id = '$goods_id' + $conditions"; + $result = $GLOBALS['db']->getAll($sql); + + $return_array = array(); + foreach ($result as $value) + { + $return_array[$value['goods_attr_id']] = $value; + } + + return $return_array; +} + +/** + * 调用array_combine函数 + * + * @param array $keys + * @param array $values + * + * @return $combined + */ +if (!function_exists('array_combine')) { + function array_combine($keys, $values) + { + if (!is_array($keys)) { + user_error('array_combine() expects parameter 1 to be array, ' . + gettype($keys) . ' given', E_USER_WARNING); + return; + } + + if (!is_array($values)) { + user_error('array_combine() expects parameter 2 to be array, ' . + gettype($values) . ' given', E_USER_WARNING); + return; + } + + $key_count = count($keys); + $value_count = count($values); + if ($key_count !== $value_count) { + user_error('array_combine() Both parameters should have equal number of elements', E_USER_WARNING); + return false; + } + + if ($key_count === 0 || $value_count === 0) { + user_error('array_combine() Both parameters should have number of elements at least 0', E_USER_WARNING); + return false; + } + + $keys = array_values($keys); + $values = array_values($values); + + $combined = array(); + for ($i = 0; $i < $key_count; $i++) { + $combined[$keys[$i]] = $values[$i]; + } + + return $combined; + } +} + +?> \ No newline at end of file diff --git a/includes/lib_compositor.php b/includes/lib_compositor.php new file mode 100644 index 0000000..58c4f4c --- /dev/null +++ b/includes/lib_compositor.php @@ -0,0 +1,53 @@ +$v) + { + if($v['pay_code'] == 'tenpay') + { + $tenpay = $modules[$k]; + unset($modules[$k]); + array_unshift($modules, $tenpay); + } + } + /* 将快钱直连银行显示在快钱之后 */ + foreach ($modules as $k =>$v) + { + if(strpos($v['pay_code'], 'kuaiqian')!== false) + { + $tenpay = $modules[$k]; + unset($modules[$k]); + array_unshift($modules, $tenpay); + } + } + + /* 将快钱提升至第一个显示 */ + foreach ($modules as $k =>$v) + { + if($v['pay_code'] == 'kuaiqian') + { + $tenpay = $modules[$k]; + unset($modules[$k]); + array_unshift($modules, $tenpay); + } + } + +} + +?> \ No newline at end of file diff --git a/includes/lib_goods.php b/includes/lib_goods.php new file mode 100644 index 0000000..f9ca5a4 --- /dev/null +++ b/includes/lib_goods.php @@ -0,0 +1,1557 @@ + 0) + { + $sql = 'SELECT parent_id FROM ' . $GLOBALS['ecs']->table('category') . " WHERE cat_id = '$cat_id'"; + $parent_id = $GLOBALS['db']->getOne($sql); + + } + else + { + $parent_id = 0; + } + + /* + 判断当前分类中全是是否是底级分类, + 如果是取出底级分类上级分类, + 如果不是取当前分类及其下的子分类 + */ + $sql = 'SELECT count(*) FROM ' . $GLOBALS['ecs']->table('category') . " WHERE parent_id = '$parent_id' AND is_show = 1 "; + if ($GLOBALS['db']->getOne($sql) || $parent_id == 0) + { + /* 获取当前分类及其子分类 */ + $sql = 'SELECT cat_id,cat_name ,parent_id,is_show ' . + 'FROM ' . $GLOBALS['ecs']->table('category') . + "WHERE parent_id = '$parent_id' AND is_show = 1 ORDER BY sort_order ASC, cat_id ASC"; + + $res = $GLOBALS['db']->getAll($sql); + + foreach ($res AS $row) + { + if ($row['is_show']) + { + $cat_arr[$row['cat_id']]['id'] = $row['cat_id']; + $cat_arr[$row['cat_id']]['name'] = $row['cat_name']; + $cat_arr[$row['cat_id']]['url'] = build_uri('category', array('cid' => $row['cat_id']), $row['cat_name']); + + if (isset($row['cat_id']) != NULL) + { + $cat_arr[$row['cat_id']]['cat_id'] = get_child_tree($row['cat_id']); + } + } + } + } + if(isset($cat_arr)) + { + return $cat_arr; + } +} + +function get_child_tree($tree_id = 0) +{ + $three_arr = array(); + $sql = 'SELECT count(*) FROM ' . $GLOBALS['ecs']->table('category') . " WHERE parent_id = '$tree_id' AND is_show = 1 "; + if ($GLOBALS['db']->getOne($sql) || $tree_id == 0) + { + $child_sql = 'SELECT cat_id, cat_name, parent_id, is_show ' . + 'FROM ' . $GLOBALS['ecs']->table('category') . + "WHERE parent_id = '$tree_id' AND is_show = 1 ORDER BY sort_order ASC, cat_id ASC"; + $res = $GLOBALS['db']->getAll($child_sql); + foreach ($res AS $row) + { + if ($row['is_show']) + + $three_arr[$row['cat_id']]['id'] = $row['cat_id']; + $three_arr[$row['cat_id']]['name'] = $row['cat_name']; + $three_arr[$row['cat_id']]['url'] = build_uri('category', array('cid' => $row['cat_id']), $row['cat_name']); + + if (isset($row['cat_id']) != NULL) + { + $three_arr[$row['cat_id']]['cat_id'] = get_child_tree($row['cat_id']); + + } + } + } + return $three_arr; +} + +/** + * 调用当前分类的销售排行榜 + * + * @access public + * @param string $cats 查询的分类 + * @return array + */ +function get_top10($cats = '') +{ + $cats = get_children($cats); + $where = !empty($cats) ? "AND ($cats OR " . get_extension_goods($cats) . ") " : ''; + + /* 排行统计的时间 */ + switch ($GLOBALS['_CFG']['top10_time']) + { + case 1: // 一年 + $top10_time = "AND o.order_sn >= '" . date('Ymd', gmtime() - 365 * 86400) . "'"; + break; + case 2: // 半年 + $top10_time = "AND o.order_sn >= '" . date('Ymd', gmtime() - 180 * 86400) . "'"; + break; + case 3: // 三个月 + $top10_time = "AND o.order_sn >= '" . date('Ymd', gmtime() - 90 * 86400) . "'"; + break; + case 4: // 一个月 + $top10_time = "AND o.order_sn >= '" . date('Ymd', gmtime() - 30 * 86400) . "'"; + break; + default: + $top10_time = ''; + } + + $sql = 'SELECT g.goods_id, g.goods_name, g.shop_price, g.goods_thumb, SUM(og.goods_number) as goods_number ' . + 'FROM ' . $GLOBALS['ecs']->table('goods') . ' AS g, ' . + $GLOBALS['ecs']->table('order_info') . ' AS o, ' . + $GLOBALS['ecs']->table('order_goods') . ' AS og ' . + "WHERE g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0 $where $top10_time " ; + //判断是否启用库存,库存数量是否大于0 + if ($GLOBALS['_CFG']['use_storage'] == 1) + { + $sql .= " AND g.goods_number > 0 "; + } + $sql .= ' AND og.order_id = o.order_id AND og.goods_id = g.goods_id ' . + "AND (o.order_status = '" . OS_CONFIRMED . "' OR o.order_status = '" . OS_SPLITED . "') " . + "AND (o.pay_status = '" . PS_PAYED . "' OR o.pay_status = '" . PS_PAYING . "') " . + "AND (o.shipping_status = '" . SS_SHIPPED . "' OR o.shipping_status = '" . SS_RECEIVED . "') " . + 'GROUP BY g.goods_id ORDER BY goods_number DESC, g.goods_id DESC LIMIT ' . $GLOBALS['_CFG']['top_number']; + + $arr = $GLOBALS['db']->getAll($sql); + + for ($i = 0, $count = count($arr); $i < $count; $i++) + { + $arr[$i]['short_name'] = $GLOBALS['_CFG']['goods_name_length'] > 0 ? + sub_str($arr[$i]['goods_name'], $GLOBALS['_CFG']['goods_name_length']) : $arr[$i]['goods_name']; + $arr[$i]['url'] = build_uri('goods', array('gid' => $arr[$i]['goods_id']), $arr[$i]['goods_name']); + $arr[$i]['thumb'] = get_image_path($arr[$i]['goods_id'], $arr[$i]['goods_thumb'],true); + $arr[$i]['price'] = price_format($arr[$i]['shop_price']); + } + + return $arr; +} + +/** + * 获得推荐商品 + * + * @access public + * @param string $type 推荐类型,可以是 best, new, hot + * @return array + */ +function get_recommend_goods($type = '', $cats = '') +{ + if (!in_array($type, array('best', 'new', 'hot'))) + { + return array(); + } + + //取不同推荐对应的商品 + static $type_goods = array(); + if (empty($type_goods[$type])) + { + //初始化数据 + $type_goods['best'] = array(); + $type_goods['new'] = array(); + $type_goods['hot'] = array(); + $data = read_static_cache('recommend_goods'); + if ($data === false) + { + $sql = 'SELECT g.goods_id, g.is_best, g.is_new, g.is_hot, g.is_promote, b.brand_name,g.sort_order ' . + ' FROM ' . $GLOBALS['ecs']->table('goods') . ' AS g ' . + ' LEFT JOIN ' . $GLOBALS['ecs']->table('brand') . ' AS b ON b.brand_id = g.brand_id ' . + ' WHERE g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0 AND (g.is_best = 1 OR g.is_new =1 OR g.is_hot = 1)'. + ' ORDER BY g.sort_order, g.last_update DESC'; + $goods_res = $GLOBALS['db']->getAll($sql); + //定义推荐,最新,热门,促销商品 + $goods_data['best'] = array(); + $goods_data['new'] = array(); + $goods_data['hot'] = array(); + $goods_data['brand'] = array(); + if (!empty($goods_res)) + { + foreach($goods_res as $data) + { + if ($data['is_best'] == 1) + { + $goods_data['best'][] = array('goods_id' => $data['goods_id'], 'sort_order' => $data['sort_order']); + } + if ($data['is_new'] == 1) + { + $goods_data['new'][] = array('goods_id' => $data['goods_id'], 'sort_order' => $data['sort_order']); + } + if ($data['is_hot'] == 1) + { + $goods_data['hot'][] = array('goods_id' => $data['goods_id'], 'sort_order' => $data['sort_order']); + } + if ($data['brand_name'] != '') + { + $goods_data['brand'][$data['goods_id']] = $data['brand_name']; + } + } + } + write_static_cache('recommend_goods', $goods_data); + } + else + { + $goods_data = $data; + } + + $time = gmtime(); + $order_type = $GLOBALS['_CFG']['recommend_order']; + + //按推荐数量及排序取每一项推荐显示的商品 order_type可以根据后台设定进行各种条件显示 + static $type_array = array(); + $type2lib = array('best'=>'recommend_best', 'new'=>'recommend_new', 'hot'=>'recommend_hot'); + if (empty($type_array)) + { + foreach($type2lib as $key => $data) + { + if (!empty($goods_data[$key])) + { + $num = get_library_number($data); + $data_count = count($goods_data[$key]); + $num = $data_count > $num ? $num : $data_count; + if ($order_type == 0) + { + //usort($goods_data[$key], 'goods_sort'); + $rand_key = array_slice($goods_data[$key], 0, $num); + foreach($rand_key as $key_data) + { + $type_array[$key][] = $key_data['goods_id']; + } + } + else + { + $rand_key = array_rand($goods_data[$key], $num); + if ($num == 1) + { + $type_array[$key][] = $goods_data[$key][$rand_key]['goods_id']; + } + else + { + foreach($rand_key as $key_data) + { + $type_array[$key][] = $goods_data[$key][$key_data]['goods_id']; + } + } + } + } + else + { + $type_array[$key] = array(); + } + } + } + + //取出所有符合条件的商品数据,并将结果存入对应的推荐类型数组中 + $sql = 'SELECT g.goods_id, g.goods_name, g.goods_name_style, g.market_price, g.shop_price AS org_price, g.promote_price, ' . + "IFNULL(mp.user_price, g.shop_price * '$_SESSION[discount]') AS shop_price, ". + "promote_start_date, promote_end_date, g.goods_brief, g.goods_thumb, g.goods_img, RAND() AS rnd " . + 'FROM ' . $GLOBALS['ecs']->table('goods') . ' AS g ' . + "LEFT JOIN " . $GLOBALS['ecs']->table('member_price') . " AS mp ". + "ON mp.goods_id = g.goods_id AND mp.user_rank = '$_SESSION[user_rank]' "; + $type_merge = array_merge($type_array['new'], $type_array['best'], $type_array['hot']); + $type_merge = array_unique($type_merge); + $sql .= ' WHERE g.goods_id ' . db_create_in($type_merge); + $sql .= ' ORDER BY g.sort_order, g.last_update DESC'; + + $result = $GLOBALS['db']->getAll($sql); + foreach ($result AS $idx => $row) + { + if ($row['promote_price'] > 0) + { + $promote_price = bargain_price($row['promote_price'], $row['promote_start_date'], $row['promote_end_date']); + $goods[$idx]['promote_price'] = $promote_price > 0 ? price_format($promote_price) : ''; + } + else + { + $goods[$idx]['promote_price'] = ''; + } + + $goods[$idx]['id'] = $row['goods_id']; + $goods[$idx]['name'] = $row['goods_name']; + $goods[$idx]['brief'] = $row['goods_brief']; + $goods[$idx]['brand_name'] = isset($goods_data['brand'][$row['goods_id']]) ? $goods_data['brand'][$row['goods_id']] : ''; + $goods[$idx]['goods_style_name'] = add_style($row['goods_name'],$row['goods_name_style']); + + $goods[$idx]['short_name'] = $GLOBALS['_CFG']['goods_name_length'] > 0 ? + sub_str($row['goods_name'], $GLOBALS['_CFG']['goods_name_length']) : $row['goods_name']; + $goods[$idx]['short_style_name'] = add_style($goods[$idx]['short_name'],$row['goods_name_style']); + $goods[$idx]['market_price'] = price_format($row['market_price']); + $goods[$idx]['shop_price'] = price_format($row['shop_price']); + $goods[$idx]['thumb'] = get_image_path($row['goods_id'], $row['goods_thumb'], true); + $goods[$idx]['goods_img'] = get_image_path($row['goods_id'], $row['goods_img']); + $goods[$idx]['url'] = build_uri('goods', array('gid' => $row['goods_id']), $row['goods_name']); + if (in_array($row['goods_id'], $type_array['best'])) + { + $type_goods['best'][] = $goods[$idx]; + } + if (in_array($row['goods_id'], $type_array['new'])) + { + $type_goods['new'][] = $goods[$idx]; + } + if (in_array($row['goods_id'], $type_array['hot'])) + { + $type_goods['hot'][] = $goods[$idx]; + } + } + } + return $type_goods[$type]; +} + +/** + * 获得促销商品 + * + * @access public + * @return array + */ +function get_promote_goods($cats = '') +{ + $time = gmtime(); + $order_type = $GLOBALS['_CFG']['recommend_order']; + + /* 取得促销lbi的数量限制 */ + $num = get_library_number("recommend_promotion"); + $sql = 'SELECT g.goods_id, g.goods_name, g.goods_name_style, g.market_price, g.shop_price AS org_price, g.promote_price, ' . + "IFNULL(mp.user_price, g.shop_price * '$_SESSION[discount]') AS shop_price, ". + "promote_start_date, promote_end_date, g.goods_brief, g.goods_thumb, goods_img, b.brand_name, " . + "g.is_best, g.is_new, g.is_hot, g.is_promote, RAND() AS rnd " . + 'FROM ' . $GLOBALS['ecs']->table('goods') . ' AS g ' . + 'LEFT JOIN ' . $GLOBALS['ecs']->table('brand') . ' AS b ON b.brand_id = g.brand_id ' . + "LEFT JOIN " . $GLOBALS['ecs']->table('member_price') . " AS mp ". + "ON mp.goods_id = g.goods_id AND mp.user_rank = '$_SESSION[user_rank]' ". + 'WHERE g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0 ' . + " AND g.is_promote = 1 AND promote_start_date <= '$time' AND promote_end_date >= '$time' "; + $sql .= $order_type == 0 ? ' ORDER BY g.sort_order, g.last_update DESC' : ' ORDER BY rnd'; + $sql .= " LIMIT $num "; + $result = $GLOBALS['db']->getAll($sql); + + $goods = array(); + foreach ($result AS $idx => $row) + { + if ($row['promote_price'] > 0) + { + $promote_price = bargain_price($row['promote_price'], $row['promote_start_date'], $row['promote_end_date']); + $goods[$idx]['promote_price'] = $promote_price > 0 ? price_format($promote_price) : ''; + } + else + { + $goods[$idx]['promote_price'] = ''; + } + + $goods[$idx]['id'] = $row['goods_id']; + $goods[$idx]['name'] = $row['goods_name']; + $goods[$idx]['brief'] = $row['goods_brief']; + $goods[$idx]['brand_name'] = $row['brand_name']; + $goods[$idx]['goods_style_name'] = add_style($row['goods_name'],$row['goods_name_style']); + $goods[$idx]['short_name'] = $GLOBALS['_CFG']['goods_name_length'] > 0 ? sub_str($row['goods_name'], $GLOBALS['_CFG']['goods_name_length']) : $row['goods_name']; + $goods[$idx]['short_style_name'] = add_style($goods[$idx]['short_name'],$row['goods_name_style']); + $goods[$idx]['market_price'] = price_format($row['market_price']); + $goods[$idx]['shop_price'] = price_format($row['shop_price']); + $goods[$idx]['zhekou'] = round(($row['promote_price']/$row['market_price'])*100); + + + + $goods[$idx]['thumb'] = get_image_path($row['goods_id'], $row['goods_thumb'], true); + $goods[$idx]['goods_img'] = get_image_path($row['goods_id'], $row['goods_img']); + $goods[$idx]['url'] = build_uri('goods', array('gid' => $row['goods_id']), $row['goods_name']); + } + + return $goods; +} + +/** + * 获得指定分类下的推荐商品 + * + * @access public + * @param string $type 推荐类型,可以是 best, new, hot, promote + * @param string $cats 分类的ID + * @param integer $brand 品牌的ID + * @param integer $min 商品价格下限 + * @param integer $max 商品价格上限 + * @param string $ext 商品扩展查询 + * @return array + */ +function get_category_recommend_goods($type = '', $cats = '', $brand = 0, $min =0, $max = 0, $ext='') +{ + $brand_where = ($brand > 0) ? " AND g.brand_id = '$brand'" : ''; + + $price_where = ($min > 0) ? " AND g.shop_price >= $min " : ''; + $price_where .= ($max > 0) ? " AND g.shop_price <= $max " : ''; + + $sql = 'SELECT g.goods_id, g.goods_name, g.goods_name_style, g.market_price, g.shop_price AS org_price, g.promote_price, ' . + "IFNULL(mp.user_price, g.shop_price * '$_SESSION[discount]') AS shop_price, ". + 'promote_start_date, promote_end_date, g.goods_brief, g.goods_thumb, goods_img, b.brand_name ' . + 'FROM ' . $GLOBALS['ecs']->table('goods') . ' AS g ' . + 'LEFT JOIN ' . $GLOBALS['ecs']->table('brand') . ' AS b ON b.brand_id = g.brand_id ' . + "LEFT JOIN " . $GLOBALS['ecs']->table('member_price') . " AS mp ". + "ON mp.goods_id = g.goods_id AND mp.user_rank = '$_SESSION[user_rank]' ". + 'WHERE g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0 ' . $brand_where . $price_where . $ext; + $num = 0; + $type2lib = array('best'=>'recommend_best', 'new'=>'recommend_new', 'hot'=>'recommend_hot', 'promote'=>'recommend_promotion'); + $num = get_library_number($type2lib[$type]); + + switch ($type) + { + case 'best': + $sql .= ' AND is_best = 1'; + break; + case 'new': + $sql .= ' AND is_new = 1'; + break; + case 'hot': + $sql .= ' AND is_hot = 1'; + break; + case 'promote': + $time = gmtime(); + $sql .= " AND is_promote = 1 AND promote_start_date <= '$time' AND promote_end_date >= '$time'"; + break; + } + + if (!empty($cats)) + { + $sql .= " AND (" . $cats . " OR " . get_extension_goods($cats) .")"; + } + + $order_type = $GLOBALS['_CFG']['recommend_order']; + $sql .= ($order_type == 0) ? ' ORDER BY g.sort_order, g.last_update DESC' : ' ORDER BY RAND()'; + $res = $GLOBALS['db']->selectLimit($sql, $num); + + $idx = 0; + $goods = array(); + while ($row = $GLOBALS['db']->fetchRow($res)) + { + if ($row['promote_price'] > 0) + { + $promote_price = bargain_price($row['promote_price'], $row['promote_start_date'], $row['promote_end_date']); + $goods[$idx]['promote_price'] = $promote_price > 0 ? price_format($promote_price) : ''; + } + else + { + $goods[$idx]['promote_price'] = ''; + } + + $goods[$idx]['id'] = $row['goods_id']; + $goods[$idx]['name'] = $row['goods_name']; + $goods[$idx]['brief'] = $row['goods_brief']; + $goods[$idx]['brand_name'] = $row['brand_name']; + $goods[$idx]['short_name'] = $GLOBALS['_CFG']['goods_name_length'] > 0 ? + sub_str($row['goods_name'], $GLOBALS['_CFG']['goods_name_length']) : $row['goods_name']; + $goods[$idx]['market_price'] = price_format($row['market_price']); + $goods[$idx]['shop_price'] = price_format($row['shop_price']); + $goods[$idx]['thumb'] = get_image_path($row['goods_id'], $row['goods_thumb'], true); + $goods[$idx]['goods_img'] = get_image_path($row['goods_id'], $row['goods_img']); + $goods[$idx]['url'] = build_uri('goods', array('gid' => $row['goods_id']), $row['goods_name']); + + $goods[$idx]['short_style_name'] = add_style($goods[$idx]['short_name'], $row['goods_name_style']); + $idx++; + } + + return $goods; +} + +/** + * 获得商品的详细信息 + * + * @access public + * @param integer $goods_id + * @return void + */ +function get_goods_info($goods_id) +{ + $time = gmtime(); + $sql = 'SELECT g.*, c.measure_unit, b.brand_id, b.brand_name AS goods_brand, m.type_money AS bonus_money, ' . + 'IFNULL(AVG(r.comment_rank), 0) AS comment_rank, ' . + "IFNULL(mp.user_price, g.shop_price * '$_SESSION[discount]') AS rank_price " . + 'FROM ' . $GLOBALS['ecs']->table('goods') . ' AS g ' . + 'LEFT JOIN ' . $GLOBALS['ecs']->table('category') . ' AS c ON g.cat_id = c.cat_id ' . + 'LEFT JOIN ' . $GLOBALS['ecs']->table('brand') . ' AS b ON g.brand_id = b.brand_id ' . + 'LEFT JOIN ' . $GLOBALS['ecs']->table('comment') . ' AS r '. + 'ON r.id_value = g.goods_id AND comment_type = 0 AND r.parent_id = 0 AND r.status = 1 ' . + 'LEFT JOIN ' . $GLOBALS['ecs']->table('bonus_type') . ' AS m ' . + "ON g.bonus_type_id = m.type_id AND m.send_start_date <= '$time' AND m.send_end_date >= '$time'" . + " LEFT JOIN " . $GLOBALS['ecs']->table('member_price') . " AS mp ". + "ON mp.goods_id = g.goods_id AND mp.user_rank = '$_SESSION[user_rank]' ". + "WHERE g.goods_id = '$goods_id' AND g.is_delete = 0 " . + "GROUP BY g.goods_id"; + $row = $GLOBALS['db']->getRow($sql); + + if ($row !== false) + { + /* 用户评论级别取整 */ + $row['comment_rank'] = ceil($row['comment_rank']) == 0 ? 5 : ceil($row['comment_rank']); + + /* 获得商品的销售价格 */ + $row['market_price'] = price_format($row['market_price']); + $row['shop_price_formated'] = price_format($row['shop_price']); + + /* 修正促销价格 */ + if ($row['promote_price'] > 0) + { + $promote_price = bargain_price($row['promote_price'], $row['promote_start_date'], $row['promote_end_date']); + } + else + { + $promote_price = 0; + } + + /* 处理商品水印图片 */ + $watermark_img = ''; + + if ($promote_price != 0) + { + $watermark_img = "watermark_promote"; + } + elseif ($row['is_new'] != 0) + { + $watermark_img = "watermark_new"; + } + elseif ($row['is_best'] != 0) + { + $watermark_img = "watermark_best"; + } + elseif ($row['is_hot'] != 0) + { + $watermark_img = 'watermark_hot'; + } + + if ($watermark_img != '') + { + $row['watermark_img'] = $watermark_img; + } + + $row['promote_price_org'] = $promote_price; + $row['promote_price'] = price_format($promote_price); + + /* 修正重量显示 */ + $row['goods_weight'] = (intval($row['goods_weight']) > 0) ? + $row['goods_weight'] . $GLOBALS['_LANG']['kilogram'] : + ($row['goods_weight'] * 1000) . $GLOBALS['_LANG']['gram']; + + /* 修正上架时间显示 */ + $row['add_time'] = local_date($GLOBALS['_CFG']['date_format'], $row['add_time']); + + /* 促销时间倒计时 */ + $time = gmtime(); + if ($time >= $row['promote_start_date'] && $time <= $row['promote_end_date']) + { + $row['gmt_end_time'] = $row['promote_end_date']; + } + else + { + $row['gmt_end_time'] = 0; + } + + /* 是否显示商品库存数量 */ + $row['goods_number'] = ($GLOBALS['_CFG']['use_storage'] == 1) ? $row['goods_number'] : ''; + + /* 修正积分:转换为可使用多少积分(原来是可以使用多少钱的积分) */ + $row['integral'] = $GLOBALS['_CFG']['integral_scale'] ? round($row['integral'] * 100 / $GLOBALS['_CFG']['integral_scale']) : 0; + + /* 修正优惠券 */ + $row['bonus_money'] = ($row['bonus_money'] == 0) ? 0 : price_format($row['bonus_money'], false); + + /* 修正商品图片 */ + $row['goods_img'] = get_image_path($goods_id, $row['goods_img']); + $row['goods_thumb'] = get_image_path($goods_id, $row['goods_thumb'], true); + + return $row; + } + else + { + return false; + } +} + +/** + * 获得商品的属性和规格 + * + * @access public + * @param integer $goods_id + * @return array + */ +function get_goods_properties($goods_id) +{ + /* 对属性进行重新排序和分组 */ + $sql = "SELECT attr_group ". + "FROM " . $GLOBALS['ecs']->table('goods_type') . " AS gt, " . $GLOBALS['ecs']->table('goods') . " AS g ". + "WHERE g.goods_id='$goods_id' AND gt.cat_id=g.goods_type"; + $grp = $GLOBALS['db']->getOne($sql); + + if (!empty($grp)) + { + $groups = explode("\n", strtr($grp, "\r", '')); + } + + /* 获得商品的规格 */ + $sql = "SELECT a.attr_id, a.attr_name, a.attr_group, a.is_linked, a.attr_type, ". + "g.goods_attr_id, g.attr_value, g.attr_price " . + 'FROM ' . $GLOBALS['ecs']->table('goods_attr') . ' AS g ' . + 'LEFT JOIN ' . $GLOBALS['ecs']->table('attribute') . ' AS a ON a.attr_id = g.attr_id ' . + "WHERE g.goods_id = '$goods_id' " . + 'ORDER BY a.sort_order, g.attr_price, g.goods_attr_id'; + $res = $GLOBALS['db']->getAll($sql); + + $arr['pro'] = array(); // 属性 + $arr['spe'] = array(); // 规格 + $arr['lnk'] = array(); // 关联的属性 + + foreach ($res AS $row) + { + $row['attr_value'] = str_replace("\n", '
', $row['attr_value']); + + if ($row['attr_type'] == 0) + { + $group = (isset($groups[$row['attr_group']])) ? $groups[$row['attr_group']] : $GLOBALS['_LANG']['goods_attr']; + + $arr['pro'][$group][$row['attr_id']]['name'] = $row['attr_name']; + $arr['pro'][$group][$row['attr_id']]['value'] = $row['attr_value']; + } + else + { + $arr['spe'][$row['attr_id']]['attr_type'] = $row['attr_type']; + $arr['spe'][$row['attr_id']]['name'] = $row['attr_name']; + $arr['spe'][$row['attr_id']]['values'][] = array( + 'label' => $row['attr_value'], + 'price' => $row['attr_price'], + 'format_price' => price_format(abs($row['attr_price']), false), + 'id' => $row['goods_attr_id']); + } + + if ($row['is_linked'] == 1) + { + /* 如果该属性需要关联,先保存下来 */ + $arr['lnk'][$row['attr_id']]['name'] = $row['attr_name']; + $arr['lnk'][$row['attr_id']]['value'] = $row['attr_value']; + } + } + + return $arr; +} + +/** + * 获得属性相同的商品 + * + * @access public + * @param array $attr // 包含了属性名称,ID的数组 + * @return array + */ +function get_same_attribute_goods($attr) +{ + $lnk = array(); + + if (!empty($attr)) + { + foreach ($attr['lnk'] AS $key => $val) + { + $lnk[$key]['title'] = sprintf($GLOBALS['_LANG']['same_attrbiute_goods'], $val['name'], $val['value']); + + /* 查找符合条件的商品 */ + $sql = 'SELECT g.goods_id, g.goods_name, g.goods_thumb, g.goods_img, g.shop_price AS org_price, ' . + "IFNULL(mp.user_price, g.shop_price * '$_SESSION[discount]') AS shop_price, ". + 'g.market_price, g.promote_price, g.promote_start_date, g.promote_end_date ' . + 'FROM ' . $GLOBALS['ecs']->table('goods') . ' AS g ' . + 'LEFT JOIN ' . $GLOBALS['ecs']->table('goods_attr') . ' as a ON g.goods_id = a.goods_id ' . + "LEFT JOIN " . $GLOBALS['ecs']->table('member_price') . " AS mp ". + "ON mp.goods_id = g.goods_id AND mp.user_rank = '$_SESSION[user_rank]' ". + "WHERE a.attr_id = '$key' AND g.is_on_sale=1 AND a.attr_value = '$val[value]' AND g.goods_id <> '$_REQUEST[id]' " . + 'LIMIT ' . $GLOBALS['_CFG']['attr_related_number']; + $res = $GLOBALS['db']->getAll($sql); + + foreach ($res AS $row) + { + $lnk[$key]['goods'][$row['goods_id']]['goods_id'] = $row['goods_id']; + $lnk[$key]['goods'][$row['goods_id']]['goods_name'] = $row['goods_name']; + $lnk[$key]['goods'][$row['goods_id']]['short_name'] = $GLOBALS['_CFG']['goods_name_length'] > 0 ? + sub_str($row['goods_name'], $GLOBALS['_CFG']['goods_name_length']) : $row['goods_name']; + $lnk[$key]['goods'][$row['goods_id']]['goods_thumb'] = (empty($row['goods_thumb'])) ? $GLOBALS['_CFG']['no_picture'] : $row['goods_thumb']; + $lnk[$key]['goods'][$row['goods_id']]['market_price'] = price_format($row['market_price']); + $lnk[$key]['goods'][$row['goods_id']]['shop_price'] = price_format($row['shop_price']); + $lnk[$key]['goods'][$row['goods_id']]['promote_price'] = bargain_price($row['promote_price'], + $row['promote_start_date'], $row['promote_end_date']); + $lnk[$key]['goods'][$row['goods_id']]['url'] = build_uri('goods', array('gid' => $row['goods_id']), $row['goods_name']); + } + } + } + + return $lnk; +} + +/** + * 获得指定商品的相册 + * + * @access public + * @param integer $goods_id + * @return array + */ +function get_goods_gallery($goods_id) +{ + $sql = 'SELECT img_id, img_url, thumb_url, img_desc' . + ' FROM ' . $GLOBALS['ecs']->table('goods_gallery') . + " WHERE goods_id = '$goods_id' LIMIT " . $GLOBALS['_CFG']['goods_gallery_number']; + $row = $GLOBALS['db']->getAll($sql); + /* 格式化相册图片路径 */ + foreach($row as $key => $gallery_img) + { + $row[$key]['img_url'] = get_image_path($goods_id, $gallery_img['img_url'], false, 'gallery'); + $row[$key]['thumb_url'] = get_image_path($goods_id, $gallery_img['thumb_url'], true, 'gallery'); + } + return $row; +} + +/** + * 获得指定分类下的商品 + * + * @access public + * @param integer $cat_id 分类ID + * @param integer $num 数量 + * @param string $from 来自web/wap的调用 + * @param string $order_rule 指定商品排序规则 + * @return array + */ +function assign_cat_goods($cat_id, $num = 0, $from = 'web',$return='cat') //这里增加了一个参数 $return, 下面有用到这个参数, zhangyh_100322 +{ + $children = get_children($cat_id); + + $sql = 'SELECT g.goods_id, g.goods_name, g.market_price, g.shop_price AS org_price, ' . + "IFNULL(mp.user_price, g.shop_price * '$_SESSION[discount]') AS shop_price, ". + 'g.promote_price, promote_start_date, promote_end_date, g.goods_brief, g.goods_thumb, g.goods_img ' . + "FROM " . $GLOBALS['ecs']->table('goods') . ' AS g '. + "LEFT JOIN " . $GLOBALS['ecs']->table('member_price') . " AS mp ". + "ON mp.goods_id = g.goods_id AND mp.user_rank = '$_SESSION[user_rank]' ". + 'WHERE g.is_on_sale = 1 AND g.is_alone_sale = 1 AND '. + 'g.is_delete = 0 AND (' . $children . 'OR ' . get_extension_goods($children) . ') '; + + $order_rule = empty($order_rule) ? 'ORDER BY g.sort_order, g.goods_id DESC' : $order_rule; + $sql .= $order_rule; + if ($num > 0) + { + $sql .= ' LIMIT ' . $num; + } + $res = $GLOBALS['db']->getAll($sql); + + $goods = array(); + foreach ($res AS $idx => $row) + { + if ($row['promote_price'] > 0) + { + $promote_price = bargain_price($row['promote_price'], $row['promote_start_date'], $row['promote_end_date']); + $goods[$idx]['promote_price'] = $promote_price > 0 ? price_format($promote_price) : ''; + } + else + { + $goods[$idx]['promote_price'] = ''; + } + + $goods[$idx]['id'] = $row['goods_id']; + $goods[$idx]['name'] = $row['goods_name']; + $goods[$idx]['brief'] = $row['goods_brief']; + $goods[$idx]['market_price'] = price_format($row['market_price']); + $goods[$idx]['short_name'] = $GLOBALS['_CFG']['goods_name_length'] > 0 ? + sub_str($row['goods_name'], $GLOBALS['_CFG']['goods_name_length']) : $row['goods_name']; + $goods[$idx]['shop_price'] = price_format($row['shop_price']); + $goods[$idx]['thumb'] = get_image_path($row['goods_id'], $row['goods_thumb'], true); + $goods[$idx]['goods_img'] = get_image_path($row['goods_id'], $row['goods_img']); + $goods[$idx]['url'] = build_uri('goods', array('gid' => $row['goods_id']), $row['goods_name']); + } + + if ($from == 'web') + { + $GLOBALS['smarty']->assign('cat_goods_' . $cat_id, $goods); + } + elseif ($from == 'wap') + { + $cat['goods'] = $goods; + } + + /* 分类信息 */ + $sql = 'SELECT cat_name FROM ' . $GLOBALS['ecs']->table('category') . " WHERE cat_id = '$cat_id'"; + $cat['name'] = $GLOBALS['db']->getOne($sql); + $cat['url'] = build_uri('category', array('cid' => $cat_id), $cat['name']); + $cat['id'] = $cat_id; + + + + + /** + * zhangyh_100322 start + * 下面代码针对函数返回值做了修改,如果$return传入值是cat则返回$cat,如果是goods则返回 $goods + */ + $sql = 'SELECT cat_id,cat_name FROM ' . $GLOBALS['ecs']->table('category') . " WHERE parent_id = '$cat_id' order by sort_order limit 0,6"; + $cat['children']=$GLOBALS['db']->getAll($sql); //获得该大类下的小类 + + /* 得到第一个小类下的商品列表 */ + $children_2 = get_children($cat['children'][0]['cat_id']); + $sql = 'SELECT g.goods_id, g.goods_name, g.market_price, g.shop_price AS org_price, ' . + "IFNULL(mp.user_price, g.shop_price * '$_SESSION[discount]') AS shop_price, ". + 'g.promote_price, promote_start_date, promote_end_date, g.goods_brief, g.goods_thumb, g.goods_img ' . + "FROM " . $GLOBALS['ecs']->table('goods') . ' AS g '. + "LEFT JOIN " . $GLOBALS['ecs']->table('member_price') . " AS mp ". + "ON mp.goods_id = g.goods_id AND mp.user_rank = '$_SESSION[user_rank]' ". + 'WHERE g.is_on_sale = 1 AND g.is_alone_sale = 1 AND '. + 'g.is_delete = 0 AND (' . $children_2 . 'OR ' . get_extension_goods($children_2) . ') '; + $sql .= $order_rule; + if ($num > 0) + { + $sql .= ' LIMIT ' . $num; + } + $res_2 = $GLOBALS['db']->getAll($sql); + $goods_2 = array(); + foreach ($res_2 AS $idx => $row) + { + if ($row['promote_price'] > 0) + { + $promote_price = bargain_price($row['promote_price'], $row['promote_start_date'], $row['promote_end_date']); + $goods_2[$idx]['promote_price'] = $promote_price > 0 ? price_format($promote_price) : ''; + } + else + { + $goods_2[$idx]['promote_price'] = ''; + } + + $goods_2[$idx]['id'] = $row['goods_id']; + $goods_2[$idx]['name'] = $row['goods_name']; + $goods_2[$idx]['short_name'] = $GLOBALS['_CFG']['goods_name_length'] > 0 ? + sub_str($row['goods_name'], $GLOBALS['_CFG']['goods_name_length']) : $row['goods_name']; + $goods_2[$idx]['shop_price'] = price_format($row['shop_price']); + $goods_2[$idx]['thumb'] = get_image_path($row['goods_id'], $row['goods_thumb'], true); + $goods_2[$idx]['url'] = build_uri('goods', array('gid' => $row['goods_id']), $row['goods_name']); + } + $cat['children_goods']=$goods_2; + + + if ($return=='cat') + { + return $cat; + } + elseif ($return=='goods') + { + return $goods; + } + /* zhangyh_100322 end */ +} + +/** + * 获得指定的品牌下的商品 + * + * @access public + * @param integer $brand_id 品牌的ID + * @param integer $num 数量 + * @param integer $cat_id 分类编号 + * @param string $order_rule 指定商品排序规则 + * @return void + */ +function assign_brand_goods($brand_id, $num = 0, $cat_id = 0,$order_rule = '') +{ + $sql = 'SELECT g.goods_id, g.goods_name, g.market_price, g.shop_price AS org_price, ' . + "IFNULL(mp.user_price, g.shop_price * '$_SESSION[discount]') AS shop_price, ". + 'g.promote_price, g.promote_start_date, g.promote_end_date, g.goods_brief, g.goods_thumb, g.goods_img ' . + 'FROM ' . $GLOBALS['ecs']->table('goods') . ' AS g ' . + "LEFT JOIN " . $GLOBALS['ecs']->table('member_price') . " AS mp ". + "ON mp.goods_id = g.goods_id AND mp.user_rank = '$_SESSION[user_rank]' ". + "WHERE g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0 AND g.brand_id = '$brand_id'"; + + if ($cat_id > 0) + { + $sql .= get_children($cat_id); + } + + $order_rule = empty($order_rule) ? ' ORDER BY g.sort_order, g.goods_id DESC' : $order_rule; + $sql .= $order_rule; + if ($num > 0) + { + $res = $GLOBALS['db']->selectLimit($sql, $num); + } + else + { + $res = $GLOBALS['db']->query($sql); + } + + $idx = 0; + $goods = array(); + while ($row = $GLOBALS['db']->fetchRow($res)) + { + if ($row['promote_price'] > 0) + { + $promote_price = bargain_price($row['promote_price'], $row['promote_start_date'], $row['promote_end_date']); + } + else + { + $promote_price = 0; + } + + $goods[$idx]['id'] = $row['goods_id']; + $goods[$idx]['name'] = $row['goods_name']; + $goods[$idx]['short_name'] = $GLOBALS['_CFG']['goods_name_length'] > 0 ? + sub_str($row['goods_name'], $GLOBALS['_CFG']['goods_name_length']) : $row['goods_name']; + $goods[$idx]['market_price'] = price_format($row['market_price']); + $goods[$idx]['shop_price'] = price_format($row['shop_price']); + $goods[$idx]['promote_price'] = $promote_price > 0 ? price_format($promote_price) : ''; + $goods[$idx]['brief'] = $row['goods_brief']; + $goods[$idx]['thumb'] = get_image_path($row['goods_id'], $row['goods_thumb'], true); + $goods[$idx]['goods_img'] = get_image_path($row['goods_id'], $row['goods_img']); + $goods[$idx]['url'] = build_uri('goods', array('gid' => $row['goods_id']), $row['goods_name']); + + $idx++; + } + + /* 分类信息 */ + $sql = 'SELECT brand_name FROM ' . $GLOBALS['ecs']->table('brand') . " WHERE brand_id = '$brand_id'"; + + $brand['id'] = $brand_id; + $brand['name'] = $GLOBALS['db']->getOne($sql); + $brand['url'] = build_uri('brand', array('bid' => $brand_id), $brand['name']); + + $brand_goods = array('brand' => $brand, 'goods' => $goods); + + return $brand_goods; +} + +/** + * 获得所有扩展分类属于指定分类的所有商品ID + * + * @access public + * @param string $cat_id 分类查询字符串 + * @return string + */ +function get_extension_goods($cats) +{ + $extension_goods_array = ''; + $sql = 'SELECT goods_id FROM ' . $GLOBALS['ecs']->table('goods_cat') . " AS g WHERE $cats"; + $extension_goods_array = $GLOBALS['db']->getCol($sql); + return db_create_in($extension_goods_array, 'g.goods_id'); +} + +/** + * 判断某个商品是否正在特价促销期 + * + * @access public + * @param float $price 促销价格 + * @param string $start 促销开始日期 + * @param string $end 促销结束日期 + * @return float 如果还在促销期则返回促销价,否则返回0 + */ +function bargain_price($price, $start, $end) +{ + if ($price == 0) + { + return 0; + } + else + { + $time = gmtime(); + if ($time >= $start && $time <= $end) + { + return $price; + } + else + { + return 0; + } + } +} + +/** + * 获得指定的规格的价格 + * + * @access public + * @param mix $spec 规格ID的数组或者逗号分隔的字符串 + * @return void + */ +function spec_price($spec) +{ + if (!empty($spec)) + { + $where = db_create_in($spec, 'goods_attr_id'); + + $sql = 'SELECT SUM(attr_price) AS attr_price FROM ' . $GLOBALS['ecs']->table('goods_attr') . " WHERE $where"; + $price = floatval($GLOBALS['db']->getOne($sql)); + } + else + { + $price = 0; + } + + return $price; +} + +/** + * 取得团购活动信息 + * @param int $group_buy_id 团购活动id + * @param int $current_num 本次购买数量(计算当前价时要加上的数量) + * @return array + * status 状态: + */ +function group_buy_info($group_buy_id, $current_num = 0) +{ + /* 取得团购活动信息 */ + $group_buy_id = intval($group_buy_id); + $sql = "SELECT *, act_id AS group_buy_id, act_desc AS group_buy_desc, start_time AS start_date, end_time AS end_date " . + "FROM " . $GLOBALS['ecs']->table('goods_activity') . + "WHERE act_id = '$group_buy_id' " . + "AND act_type = '" . GAT_GROUP_BUY . "'"; + $group_buy = $GLOBALS['db']->getRow($sql); + + /* 如果为空,返回空数组 */ + if (empty($group_buy)) + { + return array(); + } + + $ext_info = unserialize($group_buy['ext_info']); + $group_buy = array_merge($group_buy, $ext_info); + + /* 格式化时间 */ + $group_buy['formated_start_date'] = local_date('Y-m-d H:i', $group_buy['start_time']); + $group_buy['formated_end_date'] = local_date('Y-m-d H:i', $group_buy['end_time']); + + /* 格式化保证金 */ + $group_buy['formated_deposit'] = price_format($group_buy['deposit'], false); + + /* 处理价格阶梯 */ + $price_ladder = $group_buy['price_ladder']; + if (!is_array($price_ladder) || empty($price_ladder)) + { + $price_ladder = array(array('amount' => 0, 'price' => 0)); + } + else + { + foreach ($price_ladder as $key => $amount_price) + { + $price_ladder[$key]['formated_price'] = price_format($amount_price['price'], false); + } + } + $group_buy['price_ladder'] = $price_ladder; + + /* 统计信息 */ + $stat = group_buy_stat($group_buy_id, $group_buy['deposit']); + $group_buy = array_merge($group_buy, $stat); + + /* 计算当前价 */ + $cur_price = $price_ladder[0]['price']; // 初始化 + $cur_amount = $stat['valid_goods'] + $current_num; // 当前数量 + foreach ($price_ladder as $amount_price) + { + if ($cur_amount >= $amount_price['amount']) + { + $cur_price = $amount_price['price']; + } + else + { + break; + } + } + $group_buy['cur_price'] = $cur_price; + $group_buy['formated_cur_price'] = price_format($cur_price, false); + + /* 最终价 */ + $group_buy['trans_price'] = $group_buy['cur_price']; + $group_buy['formated_trans_price'] = $group_buy['formated_cur_price']; + $group_buy['trans_amount'] = $group_buy['valid_goods']; + + /* 状态 */ + $group_buy['status'] = group_buy_status($group_buy); + if (isset($GLOBALS['_LANG']['gbs'][$group_buy['status']])) + { + $group_buy['status_desc'] = $GLOBALS['_LANG']['gbs'][$group_buy['status']]; + } + + $group_buy['start_time'] = $group_buy['formated_start_date']; + $group_buy['end_time'] = $group_buy['formated_end_date']; + + return $group_buy; +} + +/* + * 取得某团购活动统计信息 + * @param int $group_buy_id 团购活动id + * @param float $deposit 保证金 + * @return array 统计信息 + * total_order 总订单数 + * total_goods 总商品数 + * valid_order 有效订单数 + * valid_goods 有效商品数 + */ +function group_buy_stat($group_buy_id, $deposit) +{ + $group_buy_id = intval($group_buy_id); + + /* 取得团购活动商品ID */ + $sql = "SELECT goods_id " . + "FROM " . $GLOBALS['ecs']->table('goods_activity') . + "WHERE act_id = '$group_buy_id' " . + "AND act_type = '" . GAT_GROUP_BUY . "'"; + $group_buy_goods_id = $GLOBALS['db']->getOne($sql); + + /* 取得总订单数和总商品数 */ + $sql = "SELECT COUNT(*) AS total_order, SUM(g.goods_number) AS total_goods " . + "FROM " . $GLOBALS['ecs']->table('order_info') . " AS o, " . + $GLOBALS['ecs']->table('order_goods') . " AS g " . + " WHERE o.order_id = g.order_id " . + "AND o.extension_code = 'group_buy' " . + "AND o.extension_id = '$group_buy_id' " . + "AND g.goods_id = '$group_buy_goods_id' " . + "AND (order_status = '" . OS_CONFIRMED . "' OR order_status = '" . OS_UNCONFIRMED . "')"; + $stat = $GLOBALS['db']->getRow($sql); + if ($stat['total_order'] == 0) + { + $stat['total_goods'] = 0; + } + + /* 取得有效订单数和有效商品数 */ + $deposit = floatval($deposit); + if ($deposit > 0 && $stat['total_order'] > 0) + { + $sql .= " AND (o.money_paid + o.surplus) >= '$deposit'"; + $row = $GLOBALS['db']->getRow($sql); + $stat['valid_order'] = $row['total_order']; + if ($stat['valid_order'] == 0) + { + $stat['valid_goods'] = 0; + } + else + { + $stat['valid_goods'] = $row['total_goods']; + } + } + else + { + $stat['valid_order'] = $stat['total_order']; + $stat['valid_goods'] = $stat['total_goods']; + } + + return $stat; +} + +/** + * 获得团购的状态 + * + * @access public + * @param array + * @return integer + */ +function group_buy_status($group_buy) +{ + $now = gmtime(); + if ($group_buy['is_finished'] == 0) + { + /* 未处理 */ + if ($now < $group_buy['start_time']) + { + $status = GBS_PRE_START; + } + elseif ($now > $group_buy['end_time']) + { + $status = GBS_FINISHED; + } + else + { + if ($group_buy['restrict_amount'] == 0 || $group_buy['valid_goods'] < $group_buy['restrict_amount']) + { + $status = GBS_UNDER_WAY; + } + else + { + $status = GBS_FINISHED; + } + } + } + elseif ($group_buy['is_finished'] == GBS_SUCCEED) + { + /* 已处理,团购成功 */ + $status = GBS_SUCCEED; + } + elseif ($group_buy['is_finished'] == GBS_FAIL) + { + /* 已处理,团购失败 */ + $status = GBS_FAIL; + } + + return $status; +} + +/** + * 取得拍卖活动信息 + * @param int $act_id 活动id + * @return array + */ +function auction_info($act_id, $config = false) +{ + $sql = "SELECT * FROM " . $GLOBALS['ecs']->table('goods_activity') . " WHERE act_id = '$act_id'"; + $auction = $GLOBALS['db']->getRow($sql); + if ($auction['act_type'] != GAT_AUCTION) + { + return array(); + } + $auction['status_no'] = auction_status($auction); + if ($config == true) + { + + $auction['start_time'] = local_date('Y-m-d H:i', $auction['start_time']); + $auction['end_time'] = local_date('Y-m-d H:i', $auction['end_time']); + } + else + { + $auction['start_time'] = local_date($GLOBALS['_CFG']['time_format'], $auction['start_time']); + $auction['end_time'] = local_date($GLOBALS['_CFG']['time_format'], $auction['end_time']); + } + $ext_info = unserialize($auction['ext_info']); + $auction = array_merge($auction, $ext_info); + $auction['formated_start_price'] = price_format($auction['start_price']); + $auction['formated_end_price'] = price_format($auction['end_price']); + $auction['formated_amplitude'] = price_format($auction['amplitude']); + $auction['formated_deposit'] = price_format($auction['deposit']); + + /* 查询出价用户数和最后出价 */ + $sql = "SELECT COUNT(DISTINCT bid_user) FROM " . $GLOBALS['ecs']->table('auction_log') . + " WHERE act_id = '$act_id'"; + $auction['bid_user_count'] = $GLOBALS['db']->getOne($sql); + if ($auction['bid_user_count'] > 0) + { + $sql = "SELECT a.*, u.user_name " . + "FROM " . $GLOBALS['ecs']->table('auction_log') . " AS a, " . + $GLOBALS['ecs']->table('users') . " AS u " . + "WHERE a.bid_user = u.user_id " . + "AND act_id = '$act_id' " . + "ORDER BY a.log_id DESC"; + $row = $GLOBALS['db']->getRow($sql); + $row['formated_bid_price'] = price_format($row['bid_price'], false); + $row['bid_time'] = local_date($GLOBALS['_CFG']['time_format'], $row['bid_time']); + $auction['last_bid'] = $row; + } + + /* 查询已确认订单数 */ + if ($auction['status_no'] > 1) + { + $sql = "SELECT COUNT(*)" . + " FROM " . $GLOBALS['ecs']->table('order_info') . + " WHERE extension_code = 'auction'" . + " AND extension_id = '$act_id'" . + " AND order_status " . db_create_in(array(OS_CONFIRMED, OS_UNCONFIRMED)); + $auction['order_count'] = $GLOBALS['db']->getOne($sql); + } + else + { + $auction['order_count'] = 0; + } + + /* 当前价 */ + $auction['current_price'] = isset($auction['last_bid']) ? $auction['last_bid']['bid_price'] : $auction['start_price']; + $auction['formated_current_price'] = price_format($auction['current_price'], false); + + return $auction; +} + +/** + * 取得拍卖活动出价记录 + * @param int $act_id 活动id + * @return array + */ +function auction_log($act_id) +{ + $log = array(); + $sql = "SELECT a.*, u.user_name " . + "FROM " . $GLOBALS['ecs']->table('auction_log') . " AS a," . + $GLOBALS['ecs']->table('users') . " AS u " . + "WHERE a.bid_user = u.user_id " . + "AND act_id = '$act_id' " . + "ORDER BY a.log_id DESC"; + $res = $GLOBALS['db']->query($sql); + while ($row = $GLOBALS['db']->fetchRow($res)) + { + $row['bid_time'] = local_date($GLOBALS['_CFG']['time_format'], $row['bid_time']); + $row['formated_bid_price'] = price_format($row['bid_price'], false); + $log[] = $row; + } + + return $log; +} + +/** + * 计算拍卖活动状态(注意参数一定是原始信息) + * @param array $auction 拍卖活动原始信息 + * @return int + */ +function auction_status($auction) +{ + $now = gmtime(); + if ($auction['is_finished'] == 0) + { + if ($now < $auction['start_time']) + { + return PRE_START; // 未开始 + } + elseif ($now > $auction['end_time']) + { + return FINISHED; // 已结束,未处理 + } + else + { + return UNDER_WAY; // 进行中 + } + } + elseif ($auction['is_finished'] == 1) + { + return FINISHED; // 已结束,未处理 + } + else + { + return SETTLED; // 已结束,已处理 + } +} + +/** + * 取得商品信息 + * @param int $goods_id 商品id + * @return array + */ +function goods_info($goods_id) +{ + $sql = "SELECT g.*, b.brand_name " . + "FROM " . $GLOBALS['ecs']->table('goods') . " AS g " . + "LEFT JOIN " . $GLOBALS['ecs']->table('brand') . " AS b ON g.brand_id = b.brand_id " . + "WHERE g.goods_id = '$goods_id'"; + $row = $GLOBALS['db']->getRow($sql); + if (!empty($row)) + { + /* 修正重量显示 */ + $row['goods_weight'] = (intval($row['goods_weight']) > 0) ? + $row['goods_weight'] . $GLOBALS['_LANG']['kilogram'] : + ($row['goods_weight'] * 1000) . $GLOBALS['_LANG']['gram']; + + /* 修正图片 */ + $row['goods_img'] = get_image_path($goods_id, $row['goods_img']); + } + + return $row; +} + +/** + * 取得优惠活动信息 + * @param int $act_id 活动id + * @return array + */ +function favourable_info($act_id) +{ + $sql = "SELECT * FROM " . $GLOBALS['ecs']->table('favourable_activity') . + " WHERE act_id = '$act_id'"; + $row = $GLOBALS['db']->getRow($sql); + if (!empty($row)) + { + $row['start_time'] = local_date($GLOBALS['_CFG']['time_format'], $row['start_time']); + $row['end_time'] = local_date($GLOBALS['_CFG']['time_format'], $row['end_time']); + $row['formated_min_amount'] = price_format($row['min_amount']); + $row['formated_max_amount'] = price_format($row['max_amount']); + $row['gift'] = unserialize($row['gift']); + if ($row['act_type'] == FAT_GOODS) + { + $row['act_type_ext'] = round($row['act_type_ext']); + } + } + + return $row; +} + +/** + * 批发信息 + * @param int $act_id 活动id + * @return array + */ +function wholesale_info($act_id) +{ + $sql = "SELECT * FROM " . $GLOBALS['ecs']->table('wholesale') . + " WHERE act_id = '$act_id'"; + $row = $GLOBALS['db']->getRow($sql); + if (!empty($row)) + { + $row['price_list'] = unserialize($row['prices']); + } + + return $row; +} + +/** + * 添加商品名样式 + * @param string $goods_name 商品名称 + * @param string $style 样式参数 + * @return string + */ +function add_style($goods_name, $style) +{ + $goods_style_name = $goods_name; + + $arr = explode('+', $style); + + $font_color = !empty($arr[0]) ? $arr[0] : ''; + $font_style = !empty($arr[1]) ? $arr[1] : ''; + + if ($font_color!='') + { + $goods_style_name = '' . $goods_style_name . ''; + } + if ($font_style != '') + { + $goods_style_name = '<' . $font_style .'>' . $goods_style_name . ''; + } + return $goods_style_name; +} + +/** + * 取得商品属性 + * @param int $goods_id 商品id + * @return array + */ +function get_goods_attr($goods_id) +{ + $attr_list = array(); + $sql = "SELECT a.attr_id, a.attr_name " . + "FROM " . $GLOBALS['ecs']->table('goods') . " AS g, " . $GLOBALS['ecs']->table('attribute') . " AS a " . + "WHERE g.goods_id = '$goods_id' " . + "AND g.goods_type = a.cat_id " . + "AND a.attr_type = 1"; + $attr_id_list = $GLOBALS['db']->getCol($sql); + $res = $GLOBALS['db']->query($sql); + while ($attr = $GLOBALS['db']->fetchRow($res)) + { + if (defined('ECS_ADMIN')) + { + $attr['goods_attr_list'] = array(0 => $GLOBALS['_LANG']['select_please']); + } + else + { + $attr['goods_attr_list'] = array(); + } + $attr_list[$attr['attr_id']] = $attr; + } + + $sql = "SELECT attr_id, goods_attr_id, attr_value " . + "FROM " . $GLOBALS['ecs']->table('goods_attr') . + " WHERE goods_id = '$goods_id' " . + "AND attr_id " . db_create_in($attr_id_list); + $res = $GLOBALS['db']->query($sql); + while ($goods_attr = $GLOBALS['db']->fetchRow($res)) + { + $attr_list[$goods_attr['attr_id']]['goods_attr_list'][$goods_attr['goods_attr_id']] = $goods_attr['attr_value']; + } + + return $attr_list; +} + +/** + * 获得购物车中商品的配件 + * + * @access public + * @param array $goods_list + * @return array + */ +function get_goods_fittings($goods_list = array()) +{ + $temp_index = 0; + $arr = array(); + + $sql = 'SELECT gg.parent_id, ggg.goods_name AS parent_name, gg.goods_id, gg.goods_price, g.goods_name, g.goods_thumb, g.goods_img, g.shop_price AS org_price, ' . + "IFNULL(mp.user_price, g.shop_price * '$_SESSION[discount]') AS shop_price ". + 'FROM ' . $GLOBALS['ecs']->table('group_goods') . ' AS gg ' . + 'LEFT JOIN ' . $GLOBALS['ecs']->table('goods') . 'AS g ON g.goods_id = gg.goods_id ' . + "LEFT JOIN " . $GLOBALS['ecs']->table('member_price') . " AS mp ". + "ON mp.goods_id = gg.goods_id AND mp.user_rank = '$_SESSION[user_rank]' ". + "LEFT JOIN " . $GLOBALS['ecs']->table('goods') . " AS ggg ON ggg.goods_id = gg.parent_id ". + "WHERE gg.parent_id " . db_create_in($goods_list) . " AND g.is_delete = 0 AND g.is_on_sale = 1 ". + "ORDER BY gg.parent_id, gg.goods_id"; + + $res = $GLOBALS['db']->query($sql); + + while ($row = $GLOBALS['db']->fetchRow($res)) + { + $arr[$temp_index]['parent_id'] = $row['parent_id'];//配件的基本件ID + $arr[$temp_index]['parent_name'] = $row['parent_name'];//配件的基本件的名称 + $arr[$temp_index]['parent_short_name'] = $GLOBALS['_CFG']['goods_name_length'] > 0 ? + sub_str($row['parent_name'], $GLOBALS['_CFG']['goods_name_length']) : $row['parent_name'];//配件的基本件显示的名称 + $arr[$temp_index]['goods_id'] = $row['goods_id'];//配件的商品ID + $arr[$temp_index]['goods_name'] = $row['goods_name'];//配件的名称 + $arr[$temp_index]['short_name'] = $GLOBALS['_CFG']['goods_name_length'] > 0 ? + sub_str($row['goods_name'], $GLOBALS['_CFG']['goods_name_length']) : $row['goods_name'];//配件显示的名称 + $arr[$temp_index]['fittings_price'] = price_format($row['goods_price']);//配件价格 + $arr[$temp_index]['shop_price'] = price_format($row['shop_price']);//配件原价格 + $arr[$temp_index]['goods_thumb'] = get_image_path($row['goods_id'], $row['goods_thumb'], true); + $arr[$temp_index]['goods_img'] = get_image_path($row['goods_id'], $row['goods_img']); + $arr[$temp_index]['url'] = build_uri('goods', array('gid'=>$row['goods_id']), $row['goods_name']); + $temp_index ++; + } + + return $arr; +} + +/** + * 取指定规格的货品信息 + * + * @access public + * @param string $goods_id + * @param array $spec_goods_attr_id + * @return array + */ +function get_products_info($goods_id, $spec_goods_attr_id) +{ + $return_array = array(); + + if (empty($spec_goods_attr_id) || !is_array($spec_goods_attr_id) || empty($goods_id)) + { + return $return_array; + } + + $goods_attr_array = sort_goods_attr_id_array($spec_goods_attr_id); + + if(isset($goods_attr_array['sort'])) + { + $goods_attr = implode('|', $goods_attr_array['sort']); + + $sql = "SELECT * FROM " .$GLOBALS['ecs']->table('products'). " WHERE goods_id = '$goods_id' AND goods_attr = '$goods_attr' LIMIT 0, 1"; + $return_array = $GLOBALS['db']->getRow($sql); + } + return $return_array; +} +?> \ No newline at end of file diff --git a/includes/lib_insert.php b/includes/lib_insert.php new file mode 100644 index 0000000..c6f6c60 --- /dev/null +++ b/includes/lib_insert.php @@ -0,0 +1,390 @@ +queryTime == '') + { + $query_time = 0; + } + else + { + if (PHP_VERSION >= '5.0.0') + { + $query_time = number_format(microtime(true) - $GLOBALS['db']->queryTime, 6); + } + else + { + list($now_usec, $now_sec) = explode(' ', microtime()); + list($start_usec, $start_sec) = explode(' ', $GLOBALS['db']->queryTime); + $query_time = number_format(($now_sec - $start_sec) + ($now_usec - $start_usec), 6); + } + } + + /* 内存占用情况 */ + if ($GLOBALS['_LANG']['memory_info'] && function_exists('memory_get_usage')) + { + $memory_usage = sprintf($GLOBALS['_LANG']['memory_info'], memory_get_usage() / 1048576); + } + else + { + $memory_usage = ''; + } + + /* 是否启用了 gzip */ + $gzip_enabled = gzip_enabled() ? $GLOBALS['_LANG']['gzip_enabled'] : $GLOBALS['_LANG']['gzip_disabled']; + + $online_count = $GLOBALS['db']->getOne("SELECT COUNT(*) FROM " . $GLOBALS['ecs']->table('sessions')); + + /* 加入触发cron代码 */ + $cron_method = empty($GLOBALS['_CFG']['cron_method']) ? '' : ''; + + return sprintf($GLOBALS['_LANG']['query_info'], $GLOBALS['db']->queryCount, $query_time, $online_count) . $gzip_enabled . $memory_usage . $cron_method; +} + +/** + * 调用浏览历史 + * + * @access public + * @return string + */ +function insert_history() +{ + $str = ''; + if (!empty($_COOKIE['ECS']['history'])) + { + $where = db_create_in($_COOKIE['ECS']['history'], 'goods_id'); + $sql = 'SELECT goods_id, goods_name, goods_thumb, shop_price FROM ' . $GLOBALS['ecs']->table('goods') . + " WHERE $where AND is_on_sale = 1 AND is_alone_sale = 1 AND is_delete = 0"; + $query = $GLOBALS['db']->query($sql); + $res = array(); + while ($row = $GLOBALS['db']->fetch_array($query)) + { + $goods['goods_id'] = $row['goods_id']; + $goods['goods_name'] = $row['goods_name']; + $goods['short_name'] = $GLOBALS['_CFG']['goods_name_length'] > 0 ? sub_str($row['goods_name'], $GLOBALS['_CFG']['goods_name_length']) : $row['goods_name']; + $goods['goods_thumb'] = get_image_path($row['goods_id'], $row['goods_thumb'], true); + $goods['shop_price'] = price_format($row['shop_price']); + $goods['url'] = build_uri('goods', array('gid'=>$row['goods_id']), $row['goods_name']); + $str.=''; + } + $str .= '
    '; + } + return $str; +} + +/** + * 调用购物车信息 + * + * @access public + * @return string + */ +function insert_cart_info() +{ + $sql = 'SELECT c.*,g.goods_name,g.goods_thumb,g.goods_id,c.goods_number,c.goods_price' . + ' FROM ' . $GLOBALS['ecs']->table('cart') ." AS c ". + " LEFT JOIN ".$GLOBALS['ecs']->table('goods')." AS g ON g.goods_id=c.goods_id ". + " WHERE session_id = '" . SESS_ID . "' AND rec_type = '" . CART_GENERAL_GOODS . "'"; + $row = $GLOBALS['db']->GetAll($sql); + $arr = array(); + foreach($row AS $k=>$v) + { + $arr[$k]['goods_thumb'] =get_image_path($v['goods_id'], $v['goods_thumb'], true); + $arr[$k]['short_name'] = $GLOBALS['_CFG']['goods_name_length'] > 0 ? + sub_str($v['goods_name'], $GLOBALS['_CFG']['goods_name_length']) : $v['goods_name']; + $arr[$k]['url'] = build_uri('goods', array('gid' => $v['goods_id']), $v['goods_name']); + $arr[$k]['goods_number'] = $v['goods_number']; + $arr[$k]['goods_name'] = $v['goods_name']; + $arr[$k]['goods_price'] = price_format($v['goods_price']); + $arr[$k]['rec_id'] = $v['rec_id']; + } + $sql = 'SELECT SUM(goods_number) AS number, SUM(goods_price * goods_number) AS amount' . + ' FROM ' . $GLOBALS['ecs']->table('cart') . + " WHERE session_id = '" . SESS_ID . "' AND rec_type = '" . CART_GENERAL_GOODS . "'"; + $row = $GLOBALS['db']->GetRow($sql); + + if ($row) + { + $number = intval($row['number']); + $amount = floatval($row['amount']); + } + else + { + $number = 0; + $amount = 0; + } + + $GLOBALS['smarty']->assign('str',sprintf($GLOBALS['_LANG']['cart_info'], $number, price_format($amount, false))); + $GLOBALS['smarty']->assign('goods',$arr); + $GLOBALS['smarty']->assign('goods_number',$number); + $GLOBALS['smarty']->assign('order_amount',$amount); + $GLOBALS['smarty']->assign('cart_list_amount',price_format($amount)); + $output = $GLOBALS['smarty']->fetch('library/cart_info.lbi'); + return $output; +} + +/** + * 调用指定的广告位的广告 + * + * @access public + * @param integer $id 广告位ID + * @param integer $num 广告数量 + * @return string + */ +function insert_ads($arr) +{ + static $static_res = NULL; + + $time = gmtime(); + if (!empty($arr['num']) && $arr['num'] != 1) + { + $sql = 'SELECT a.ad_id, a.position_id, a.media_type, a.ad_link, a.ad_code, a.ad_name, p.ad_width, ' . + 'p.ad_height, p.position_style, RAND() AS rnd ' . + 'FROM ' . $GLOBALS['ecs']->table('ad') . ' AS a '. + 'LEFT JOIN ' . $GLOBALS['ecs']->table('ad_position') . ' AS p ON a.position_id = p.position_id ' . + "WHERE enabled = 1 AND start_time <= '" . $time . "' AND end_time >= '" . $time . "' ". + "AND a.position_id = '" . $arr['id'] . "' " . + 'ORDER BY rnd LIMIT ' . $arr['num']; + $res = $GLOBALS['db']->GetAll($sql); + } + else + { + if ($static_res[$arr['id']] === NULL) + { + $sql = 'SELECT a.ad_id, a.position_id, a.media_type, a.ad_link, a.ad_code, a.ad_name, p.ad_width, '. + 'p.ad_height, p.position_style, RAND() AS rnd ' . + 'FROM ' . $GLOBALS['ecs']->table('ad') . ' AS a '. + 'LEFT JOIN ' . $GLOBALS['ecs']->table('ad_position') . ' AS p ON a.position_id = p.position_id ' . + "WHERE enabled = 1 AND a.position_id = '" . $arr['id'] . + "' AND start_time <= '" . $time . "' AND end_time >= '" . $time . "' " . + 'ORDER BY rnd LIMIT 1'; + $static_res[$arr['id']] = $GLOBALS['db']->GetAll($sql); + } + $res = $static_res[$arr['id']]; + } + $ads = array(); + $position_style = ''; + + foreach ($res AS $row) + { + if ($row['position_id'] != $arr['id']) + { + continue; + } + $position_style = $row['position_style']; + switch ($row['media_type']) + { + case 0: // 图片广告 + $src = (strpos($row['ad_code'], 'http://') === false && strpos($row['ad_code'], 'https://') === false) ? + DATA_DIR . "/afficheimg/$row[ad_code]" : $row['ad_code']; + $ads[] = ""; + break; + case 1: // Flash + $src = (strpos($row['ad_code'], 'http://') === false && strpos($row['ad_code'], 'https://') === false) ? + DATA_DIR . "/afficheimg/$row[ad_code]" : $row['ad_code']; + $ads[] = " + + + + "; + break; + case 2: // CODE + $ads[] = $row['ad_code']; + break; + case 3: // TEXT + $ads[] = "" .htmlspecialchars($row['ad_code']). ''; + break; + } + } + $position_style = 'str:' . $position_style; + + $need_cache = $GLOBALS['smarty']->caching; + $GLOBALS['smarty']->caching = false; + + $GLOBALS['smarty']->assign('ads', $ads); + $val = $GLOBALS['smarty']->fetch($position_style); + + $GLOBALS['smarty']->caching = $need_cache; + + return $val; +} + +/** + * 调用会员信息 + * + * @access public + * @return string + */ +function insert_member_info() +{ + $need_cache = $GLOBALS['smarty']->caching; + $GLOBALS['smarty']->caching = false; + + if ($_SESSION['user_id'] > 0) + { + $GLOBALS['smarty']->assign('user_info', get_user_info()); + } + else + { + if (!empty($_COOKIE['ECS']['username'])) + { + $GLOBALS['smarty']->assign('ecs_username', stripslashes($_COOKIE['ECS']['username'])); + } + $captcha = intval($GLOBALS['_CFG']['captcha']); + if (($captcha & CAPTCHA_LOGIN) && (!($captcha & CAPTCHA_LOGIN_FAIL) || (($captcha & CAPTCHA_LOGIN_FAIL) && $_SESSION['login_fail'] > 2)) && gd_version() > 0) + { + $GLOBALS['smarty']->assign('enabled_captcha', 1); + $GLOBALS['smarty']->assign('rand', mt_rand()); + } + } + $output = $GLOBALS['smarty']->fetch('library/member_info.lbi'); + + $GLOBALS['smarty']->caching = $need_cache; + + return $output; +} + +/** + * 调用评论信息 + * + * @access public + * @return string + */ +function insert_comments($arr) +{ + $need_cache = $GLOBALS['smarty']->caching; + $need_compile = $GLOBALS['smarty']->force_compile; + + $GLOBALS['smarty']->caching = false; + $GLOBALS['smarty']->force_compile = true; + + /* 验证码相关设置 */ + if ((intval($GLOBALS['_CFG']['captcha']) & CAPTCHA_COMMENT) && gd_version() > 0) + { + $GLOBALS['smarty']->assign('enabled_captcha', 1); + $GLOBALS['smarty']->assign('rand', mt_rand()); + } + $GLOBALS['smarty']->assign('username', stripslashes($_SESSION['user_name'])); + $GLOBALS['smarty']->assign('email', $_SESSION['email']); + $GLOBALS['smarty']->assign('comment_type', $arr['type']); + $GLOBALS['smarty']->assign('id', $arr['id']); + $cmt = assign_comment($arr['id'], $arr['type']); + $GLOBALS['smarty']->assign('comments', $cmt['comments']); + $GLOBALS['smarty']->assign('pager', $cmt['pager']); + + + $val = $GLOBALS['smarty']->fetch('library/comments_list.lbi'); + + $GLOBALS['smarty']->caching = $need_cache; + $GLOBALS['smarty']->force_compile = $need_compile; + + return $val; +} + + +/** + * 调用商品购买记录 + * + * @access public + * @return string + */ +function insert_bought_notes($arr) +{ + $need_cache = $GLOBALS['smarty']->caching; + $need_compile = $GLOBALS['smarty']->force_compile; + + $GLOBALS['smarty']->caching = false; + $GLOBALS['smarty']->force_compile = true; + + /* 商品购买记录 */ + $sql = 'SELECT u.user_name, og.goods_number, oi.add_time, IF(oi.order_status IN (2, 3, 4), 0, 1) AS order_status ' . + 'FROM ' . $GLOBALS['ecs']->table('order_info') . ' AS oi LEFT JOIN ' . $GLOBALS['ecs']->table('users') . ' AS u ON oi.user_id = u.user_id, ' . $GLOBALS['ecs']->table('order_goods') . ' AS og ' . + 'WHERE oi.order_id = og.order_id AND ' . time() . ' - oi.add_time < 2592000 AND og.goods_id = ' . $arr['id'] . ' ORDER BY oi.add_time DESC LIMIT 5'; + $bought_notes = $GLOBALS['db']->getAll($sql); + + foreach ($bought_notes as $key => $val) + { + $bought_notes[$key]['add_time'] = local_date("Y-m-d G:i:s", $val['add_time']); + } + + $sql = 'SELECT count(*) ' . + 'FROM ' . $GLOBALS['ecs']->table('order_info') . ' AS oi LEFT JOIN ' . $GLOBALS['ecs']->table('users') . ' AS u ON oi.user_id = u.user_id, ' . $GLOBALS['ecs']->table('order_goods') . ' AS og ' . + 'WHERE oi.order_id = og.order_id AND ' . time() . ' - oi.add_time < 2592000 AND og.goods_id = ' . $arr['id']; + $count = $GLOBALS['db']->getOne($sql); + + + /* 商品购买记录分页样式 */ + $pager = array(); + $pager['page'] = $page = 1; + $pager['size'] = $size = 5; + $pager['record_count'] = $count; + $pager['page_count'] = $page_count = ($count > 0) ? intval(ceil($count / $size)) : 1;; + $pager['page_first'] = "javascript:gotoBuyPage(1,$arr[id])"; + $pager['page_prev'] = $page > 1 ? "javascript:gotoBuyPage(" .($page-1). ",$arr[id])" : 'javascript:;'; + $pager['page_next'] = $page < $page_count ? 'javascript:gotoBuyPage(' .($page + 1) . ",$arr[id])" : 'javascript:;'; + $pager['page_last'] = $page < $page_count ? 'javascript:gotoBuyPage(' .$page_count. ",$arr[id])" : 'javascript:;'; + + $GLOBALS['smarty']->assign('notes', $bought_notes); + $GLOBALS['smarty']->assign('pager', $pager); + + + $val= $GLOBALS['smarty']->fetch('library/bought_notes.lbi'); + + $GLOBALS['smarty']->caching = $need_cache; + $GLOBALS['smarty']->force_compile = $need_compile; + + return $val; +} + + +/** + * 调用在线调查信息 + * + * @access public + * @return string + */ +function insert_vote() +{ + $vote = get_vote(); + if (!empty($vote)) + { + $GLOBALS['smarty']->assign('vote_id', $vote['id']); + $GLOBALS['smarty']->assign('vote', $vote['content']); + } + $val = $GLOBALS['smarty']->fetch('library/vote.lbi'); + + return $val; +} + +?> \ No newline at end of file diff --git a/includes/lib_license.php b/includes/lib_license.php new file mode 100644 index 0000000..40a123f --- /dev/null +++ b/includes/lib_license.php @@ -0,0 +1,287 @@ +table('shop_config') . " + WHERE code IN ('certificate_id', 'token', 'certi') + LIMIT 0,3"; + $license_info = $GLOBALS['db']->getAll($sql); + $license_info = is_array($license_info) ? $license_info : array(); + $license = array(); + foreach ($license_info as $value) + { + $license[$value['code']] = $value['value']; + } + + return $license; +} + +/** + * 功能:生成certi_ac验证字段 + * @param string POST传递参数 + * @param string 证书token + * @return string + */ +function make_shopex_ac($post_params, $token) +{ + if (!is_array($post_params)) + { + return; + } + + // core + ksort($post_params); + $str = ''; + foreach($post_params as $key=>$value){ + if($key != 'certi_ac') + { + $str .= $value; + } + } + + return md5($str . $token); +} + +/** + * 功能:与 ECShop 交换数据 + * + * @param array $certi 登录参数 + * @param array $license 网店license信息 + * @param bool $use_lib 使用哪一个json库,0为ec,1为shopex + * @return array + */ +function exchange_shop_license($certi, $license, $use_lib = 0) +{ + if (!is_array($certi)) + { + return array(); + } + + include_once(ROOT_PATH . 'includes/cls_transport.php'); + include_once(ROOT_PATH . 'includes/cls_json.php'); + + $params = ''; + foreach ($certi as $key => $value) + { + $params .= '&' . $key . '=' . $value; + } + $params = trim($params, '&'); + + $transport = new transport; + //$transport->connect_timeout = 1; + $request = $transport->request($license['certi'], $params, 'POST'); + $request_str = json_str_iconv($request['body']); + + if (empty($use_lib)) + { + $json = new JSON(); + $request_arr = $json->decode($request_str, 1); + } + else + { + include_once(ROOT_PATH . 'includes/shopex_json.php'); + $request_arr = json_decode($request_str, 1); + } + + return $request_arr; +} + +/** + * 功能:处理登录返回结果 + * + * @param array $cert_auth 登录返回的用户信息 + * @return array + */ +function process_login_license($cert_auth) +{ + if (!is_array($cert_auth)) + { + return array(); + } + + $cert_auth['auth_str'] = trim($cert_auth['auth_str']); + if (!empty($cert_auth['auth_str'])) + { + $cert_auth['auth_str'] = $GLOBALS['_LANG']['license_' . $cert_auth['auth_str']]; + } + + $cert_auth['auth_type'] = trim($cert_auth['auth_type']); + if (!empty($cert_auth['auth_type'])) + { + $cert_auth['auth_type'] = $GLOBALS['_LANG']['license_' . $cert_auth['auth_type']]; + } + + return $cert_auth; +} + +/** + * 功能:license 登录 + * + * @param array $certi_added 配置信息补充数组 array_key 登录信息的key;array_key => array_value; + * @return array $return_array['flag'] = login_succ、login_fail、login_ping_fail、login_param_fail; + * $return_array['request']; + */ +function license_login($certi_added = '') +{ + // 登录信息配置 + $certi['certi_app'] = ''; // 证书方法 + $certi['app_id'] = 'ecshop_b2c'; // 说明客户端来源 + $certi['app_instance_id'] = ''; // 应用服务ID + $certi['version'] = LICENSE_VERSION; // license接口版本号 + $certi['shop_version'] = VERSION . '#' . RELEASE; // 网店软件版本号 + $certi['certi_url'] = sprintf($GLOBALS['ecs']->url()); // 网店URL + $certi['certi_session'] = $GLOBALS['sess']->get_session_id(); // 网店SESSION标识 + $certi['certi_validate_url'] = sprintf($GLOBALS['ecs']->url() . 'certi.php'); // 网店提供于官方反查接口 + $certi['format'] = 'json'; // 官方返回数据格式 + $certi['certificate_id'] = ''; // 网店证书ID + // 标识 + $certi_back['succ'] = 'succ'; + $certi_back['fail'] = 'fail'; + // return 返回数组 + $return_array = array(); + + if (is_array($certi_added)) + { + foreach ($certi_added as $key => $value) + { + $certi[$key] = $value; + } + } + + // 取出网店 license + $license = get_shop_license(); + + // 检测网店 license + if (!empty($license['certificate_id']) && !empty($license['token']) && !empty($license['certi'])) + { + // 登录 + $certi['certi_app'] = 'certi.login'; // 证书方法 + $certi['app_instance_id'] = 'cert_auth'; // 应用服务ID + $certi['certificate_id'] = $license['certificate_id']; // 网店证书ID + $certi['certi_ac'] = make_shopex_ac($certi, $license['token']); // 网店验证字符串 + + $request_arr = exchange_shop_license($certi, $license); + if (is_array($request_arr) && $request_arr['res'] == $certi_back['succ']) + { + $return_array['flag'] = 'login_succ'; + $return_array['request'] = $request_arr; + } + elseif (is_array($request_arr) && $request_arr['res'] == $certi_back['fail']) + { + $return_array['flag'] = 'login_fail'; + $return_array['request'] = $request_arr; + } + else + { + $return_array['flag'] = 'login_ping_fail'; + $return_array['request'] = array('res' => 'fail'); + } + } + else + { + $return_array['flag'] = 'login_param_fail'; + $return_array['request'] = array('res' => 'fail'); + } + + return $return_array; +} + +/** + * 功能:license 注册 + * + * @param array $certi_added 配置信息补充数组 array_key 登录信息的key;array_key => array_value; + * @return array $return_array['flag'] = reg_succ、reg_fail、reg_ping_fail; + * $return_array['request']; + */ +function license_reg($certi_added = '') +{ + // 登录信息配置 + $certi['certi_app'] = ''; // 证书方法 + $certi['app_id'] = 'ecshop_b2c'; // 说明客户端来源 + $certi['app_instance_id'] = ''; // 应用服务ID + $certi['version'] = LICENSE_VERSION; // license接口版本号 + $certi['shop_version'] = VERSION . '#' . RELEASE; // 网店软件版本号 + $certi['certi_url'] = sprintf($GLOBALS['ecs']->url()); // 网店URL + $certi['certi_session'] = $GLOBALS['sess']->get_session_id(); // 网店SESSION标识 + $certi['certi_validate_url'] = sprintf($GLOBALS['ecs']->url() . 'certi.php'); // 网店提供于官方反查接口 + $certi['format'] = 'json'; // 官方返回数据格式 + $certi['certificate_id'] = ''; // 网店证书ID + // 标识 + $certi_back['succ'] = 'succ'; + $certi_back['fail'] = 'fail'; + // return 返回数组 + $return_array = array(); + + if (is_array($certi_added)) + { + foreach ($certi_added as $key => $value) + { + $certi[$key] = $value; + } + } + + // 取出网店 license + $license = get_shop_license(); + + // 注册 + $certi['certi_app'] = 'certi.reg'; // 证书方法 + $certi['certi_ac'] = make_shopex_ac($certi, ''); // 网店验证字符串 + unset($certi['certificate_id']); + + $request_arr = exchange_shop_license($certi, $license); + if (is_array($request_arr) && $request_arr['res'] == $certi_back['succ']) + { + // 注册信息入库 + $sql = "UPDATE " . $GLOBALS['ecs']->table('shop_config') . " + SET value = '" . $request_arr['info']['certificate_id'] . "' WHERE code = 'certificate_id'"; + $GLOBALS['db']->query($sql); + $sql = "UPDATE " . $GLOBALS['ecs']->table('shop_config') . " + SET value = '" . $request_arr['info']['token'] . "' WHERE code = 'token'"; + $GLOBALS['db']->query($sql); + + $return_array['flag'] = 'reg_succ'; + $return_array['request'] = $request_arr; + clear_cache_files(); + } + elseif (is_array($request_arr) && $request_arr['res'] == $certi_back['fail']) + { + $return_array['flag'] = 'reg_fail'; + $return_array['request'] = $request_arr; + } + else + { + $return_array['flag'] = 'reg_ping_fail'; + $return_array['request'] = array('res' => 'fail'); + } + + return $return_array; +} +?> \ No newline at end of file diff --git a/includes/lib_main.php b/includes/lib_main.php new file mode 100644 index 0000000..251dc69 --- /dev/null +++ b/includes/lib_main.php @@ -0,0 +1,2071 @@ +table('users'). ' AS u ' . + ' LEFT JOIN ' .$GLOBALS['ecs']->table('user_bonus'). ' AS ub'. + ' ON ub.user_id = u.user_id AND ub.used_time = 0 ' . + ' LEFT JOIN ' .$GLOBALS['ecs']->table('bonus_type'). ' AS b'. + " ON b.type_id = ub.bonus_type_id AND b.use_start_date <= '$time' AND b.use_end_date >= '$time' ". + " WHERE u.user_id = '$_SESSION[user_id]'"; + if ($row = $GLOBALS['db']->getRow($sql)) + { + /* 更新SESSION */ + $_SESSION['last_time'] = $row['last_login']; + $_SESSION['last_ip'] = $row['last_ip']; + $_SESSION['login_fail'] = 0; + $_SESSION['email'] = $row['email']; + + /*判断是否是特殊等级,可能后台把特殊会员组更改普通会员组*/ + if($row['user_rank'] >0) + { + $sql="SELECT special_rank from ".$GLOBALS['ecs']->table('user_rank')."where rank_id='$row[user_rank]'"; + if($GLOBALS['db']->getOne($sql)==='0' || $GLOBALS['db']->getOne($sql)===null) + { + $sql="update ".$GLOBALS['ecs']->table('users')."set user_rank='0' where user_id='$_SESSION[user_id]'"; + $GLOBALS['db']->query($sql); + $row['user_rank']=0; + } + } + + /* 取得用户等级和折扣 */ + if ($row['user_rank'] == 0) + { + // 非特殊等级,根据等级积分计算用户等级(注意:不包括特殊等级) + $sql = 'SELECT rank_id, discount FROM ' . $GLOBALS['ecs']->table('user_rank') . " WHERE special_rank = '0' AND min_points <= " . intval($row['rank_points']) . ' AND max_points > ' . intval($row['rank_points']); + if ($row = $GLOBALS['db']->getRow($sql)) + { + $_SESSION['user_rank'] = $row['rank_id']; + $_SESSION['discount'] = $row['discount'] / 100.00; + } + else + { + $_SESSION['user_rank'] = 0; + $_SESSION['discount'] = 1; + } + } + else + { + // 特殊等级 + $sql = 'SELECT rank_id, discount FROM ' . $GLOBALS['ecs']->table('user_rank') . " WHERE rank_id = '$row[user_rank]'"; + if ($row = $GLOBALS['db']->getRow($sql)) + { + $_SESSION['user_rank'] = $row['rank_id']; + $_SESSION['discount'] = $row['discount'] / 100.00; + } + else + { + $_SESSION['user_rank'] = 0; + $_SESSION['discount'] = 1; + } + } + } + + /* 更新登录时间,登录次数及登录ip */ + $sql = "UPDATE " .$GLOBALS['ecs']->table('users'). " SET". + " visit_count = visit_count + 1, ". + " last_ip = '" .real_ip(). "',". + " last_login = '" .gmtime(). "'". + " WHERE user_id = '" . $_SESSION['user_id'] . "'"; + $GLOBALS['db']->query($sql); +} + +/** + * 获取用户信息数组 + * + * @access public + * @param + * + * @return array $user 用户信息数组 + */ +function get_user_info($id=0) +{ + if ($id == 0) + { + $id = $_SESSION['user_id']; + } + $time = date('Y-m-d'); + $sql = 'SELECT u.user_id, u.email, u.user_name, u.user_money, u.pay_points'. + ' FROM ' .$GLOBALS['ecs']->table('users'). ' AS u ' . + " WHERE u.user_id = '$id'"; + $user = $GLOBALS['db']->getRow($sql); + $bonus = get_user_bonus($id); + + $user['username'] = $user['user_name']; + $user['user_points'] = $user['pay_points'] . $GLOBALS['_CFG']['integral_name']; + $user['user_money'] = price_format($user['user_money'], false); + $user['user_bonus'] = price_format($bonus['bonus_value'], false); + + return $user; +} +/** + * 取得当前位置和页面标题 + * + * @access public + * @param integer $cat 分类编号(只有商品及分类、文章及分类用到) + * @param string $str 商品名、文章标题或其他附加的内容(无链接) + * @return array + */ +function assign_ur_here($cat = 0, $str = '') +{ + /* 判断是否重写,取得文件名 */ + $cur_url = basename(PHP_SELF); + if (intval($GLOBALS['_CFG']['rewrite'])) + { + $filename = strpos($cur_url,'-') ? substr($cur_url, 0, strpos($cur_url,'-')) : substr($cur_url, 0, -4); + } + else + { + $filename = substr($cur_url, 0, -4); + } + + /* 初始化“页面标题”和“当前位置” */ + $page_title = $GLOBALS['_CFG']['shop_title'] . ' - ' . 'Powered by ECShop'; + $ur_here = '' . $GLOBALS['_LANG']['home'] . ''; + + /* 根据文件名分别处理中间的部分 */ + if ($filename != 'index') + { + /* 处理有分类的 */ + if (in_array($filename, array('category', 'goods', 'article_cat', 'article', 'brand'))) + { + /* 商品分类或商品 */ + if ('category' == $filename || 'goods' == $filename || 'brand' == $filename) + { + if ($cat > 0) + { + $cat_arr = get_parent_cats($cat); + + $key = 'cid'; + $type = 'category'; + } + else + { + $cat_arr = array(); + } + } + /* 文章分类或文章 */ + elseif ('article_cat' == $filename || 'article' == $filename) + { + if ($cat > 0) + { + $cat_arr = get_article_parent_cats($cat); + + $key = 'acid'; + $type = 'article_cat'; + } + else + { + $cat_arr = array(); + } + } + + /* 循环分类 */ + if (!empty($cat_arr)) + { + krsort($cat_arr); + foreach ($cat_arr AS $val) + { + $page_title = htmlspecialchars($val['cat_name']) . '_' . $page_title; + $args = array($key => $val['cat_id']); + $ur_here .= ' > ' . + htmlspecialchars($val['cat_name']) . ''; + } + } + } + /* 处理无分类的 */ + else + { + /* 团购 */ + if ('group_buy' == $filename) + { + $page_title = $GLOBALS['_LANG']['group_buy_goods'] . '_' . $page_title; + $args = array('gbid' => '0'); + $ur_here .= ' > ' . + $GLOBALS['_LANG']['group_buy_goods'] . ''; + } + /* 拍卖 */ + elseif ('auction' == $filename) + { + $page_title = $GLOBALS['_LANG']['auction'] . '_' . $page_title; + $args = array('auid' => '0'); + $ur_here .= ' > ' . + $GLOBALS['_LANG']['auction'] . ''; + } + /* 夺宝 */ + elseif ('snatch' == $filename) + { + $page_title = $GLOBALS['_LANG']['snatch'] . '_' . $page_title; + $args = array('id' => '0'); + $ur_here .= ' > ' . $GLOBALS['_LANG']['snatch_list'] . ''; + } + /* 批发 */ + elseif ('wholesale' == $filename) + { + $page_title = $GLOBALS['_LANG']['wholesale'] . '_' . $page_title; + $args = array('wsid' => '0'); + $ur_here .= ' > ' . + $GLOBALS['_LANG']['wholesale'] . ''; + } + /* 积分兑换 */ + elseif ('exchange' == $filename) + { + $page_title = $GLOBALS['_LANG']['exchange'] . '_' . $page_title; + $args = array('wsid' => '0'); + $ur_here .= ' > ' . + $GLOBALS['_LANG']['exchange'] . ''; + } + /* 其他的在这里补充 */ + } + } + + /* 处理最后一部分 */ + if (!empty($str)) + { + $page_title = $str . '_' . $page_title; + $ur_here .= ' > ' . $str; + } + + /* 返回值 */ + return array('title' => $page_title, 'ur_here' => $ur_here); +} + +/** + * 获得指定分类的所有上级分类 + * + * @access public + * @param integer $cat 分类编号 + * @return array + */ +function get_parent_cats($cat) +{ + if ($cat == 0) + { + return array(); + } + + $arr = $GLOBALS['db']->GetAll('SELECT cat_id, cat_name, parent_id FROM ' . $GLOBALS['ecs']->table('category')); + + if (empty($arr)) + { + return array(); + } + + $index = 0; + $cats = array(); + + while (1) + { + foreach ($arr AS $row) + { + if ($cat == $row['cat_id']) + { + $cat = $row['parent_id']; + + $cats[$index]['cat_id'] = $row['cat_id']; + $cats[$index]['cat_name'] = $row['cat_name']; + + $index++; + break; + } + } + + if ($index == 0 || $cat == 0) + { + break; + } + } + + return $cats; +} + +/** + * 根据提供的数组编译成页面标题 + * + * @access public + * @param string $type 类型 + * @param array $arr 分类数组 + * @return string + */ +function build_pagetitle($arr, $type = 'category') +{ + $str = ''; + + foreach ($arr AS $val) + { + $str .= htmlspecialchars($val['cat_name']) . '_'; + } + + return $str; +} + +/** + * 根据提供的数组编译成当前位置 + * + * @access public + * @param string $type 类型 + * @param array $arr 分类数组 + * @return void + */ +function build_urhere($arr, $type = 'category') +{ + krsort($arr); + + $str = ''; + foreach ($arr AS $val) + { + switch ($type) + { + case 'category': + case 'brand': + $args = array('cid' => $val['cat_id']); + break; + case 'article_cat': + $args = array('acid' => $val['cat_id']); + break; + } + + $str .= ' > ' . htmlspecialchars($val['cat_name']) . ''; + } + + return $str; +} + +/** + * 获得指定页面的动态内容 + * + * @access public + * @param string $tmp 模板名称 + * @return void + */ +function assign_dynamic($tmp) +{ + $sql = 'SELECT id, number, type FROM ' . $GLOBALS['ecs']->table('template') . + " WHERE filename = '$tmp' AND type > 0 AND remarks ='' AND theme='" . $GLOBALS['_CFG']['template'] . "'"; + $res = $GLOBALS['db']->getAll($sql); + + foreach ($res AS $row) + { + switch ($row['type']) + { + case 1: + /* 分类下的商品 */ + $GLOBALS['smarty']->assign('goods_cat_' . $row['id'], assign_cat_goods($row['id'], $row['number'])); + break; + case 2: + /* 品牌的商品 */ + $brand_goods = assign_brand_goods($row['id'], $row['number']); + + $GLOBALS['smarty']->assign('brand_goods_' . $row['id'], $brand_goods['goods']); + $GLOBALS['smarty']->assign('goods_brand_' . $row['id'], $brand_goods['brand']); + break; + case 3: + /* 文章列表 */ + $cat_articles = assign_articles($row['id'], $row['number']); + + $GLOBALS['smarty']->assign('articles_cat_' . $row['id'], $cat_articles['cat']); + $GLOBALS['smarty']->assign('articles_' . $row['id'], $cat_articles['arr']); + break; + } + } +} + +/** + * 分配文章列表给smarty + * + * @access public + * @param integer $id 文章分类的编号 + * @param integer $num 文章数量 + * @return array + */ +function assign_articles($id, $num) +{ + $sql = 'SELECT cat_name FROM ' . $GLOBALS['ecs']->table('article_cat') . " WHERE cat_id = '" . $id ."'"; + + $cat['id'] = $id; + $cat['name'] = $GLOBALS['db']->getOne($sql); + $cat['url'] = build_uri('article_cat', array('acid' => $id), $cat['name']); + + $articles['cat'] = $cat; + $articles['arr'] = get_cat_articles($id, 1, $num); + + return $articles; +} + +/** + * 分配帮助信息 + * + * @access public + * @return array + */ +function get_shop_help() +{ + $sql = 'SELECT c.cat_id, c.cat_name, c.sort_order, a.article_id, a.title, a.file_url, a.open_type ' . + 'FROM ' .$GLOBALS['ecs']->table('article'). ' AS a ' . + 'LEFT JOIN ' .$GLOBALS['ecs']->table('article_cat'). ' AS c ' . + 'ON a.cat_id = c.cat_id WHERE c.cat_type = 5 AND a.is_open = 1 ' . + 'ORDER BY c.sort_order ASC, a.article_id'; + $res = $GLOBALS['db']->getAll($sql); + + $arr = array(); + foreach ($res AS $key => $row) + { + $arr[$row['cat_id']]['cat_id'] = build_uri('article_cat', array('acid'=> $row['cat_id']), $row['cat_name']); + $arr[$row['cat_id']]['cat_name'] = $row['cat_name']; + $arr[$row['cat_id']]['article'][$key]['article_id'] = $row['article_id']; + $arr[$row['cat_id']]['article'][$key]['title'] = $row['title']; + $arr[$row['cat_id']]['article'][$key]['short_title'] = $GLOBALS['_CFG']['article_title_length'] > 0 ? + sub_str($row['title'], $GLOBALS['_CFG']['article_title_length']) : $row['title']; + $arr[$row['cat_id']]['article'][$key]['url'] = $row['open_type'] != 1 ? + build_uri('article', array('aid' => $row['article_id']), $row['title']) : trim($row['file_url']); + } + + return $arr; +} + +/** + * 创建分页信息 + * + * @access public + * @param string $app 程序名称,如category + * @param string $cat 分类ID + * @param string $record_count 记录总数 + * @param string $size 每页记录数 + * @param string $sort 排序类型 + * @param string $order 排序顺序 + * @param string $page 当前页 + * @param string $keywords 查询关键字 + * @param string $brand 品牌 + * @param string $price_min 最小价格 + * @param string $price_max 最高价格 + * @return void + */ +function assign_pager($app, $cat, $record_count, $size, $sort, $order, $page = 1, + $keywords = '', $brand = 0, $price_min = 0, $price_max = 0, $display_type = 'list', $filter_attr='', $url_format='', $sch_array='') +{ + $sch = array('keywords' => $keywords, + 'sort' => $sort, + 'order' => $order, + 'cat' => $cat, + 'brand' => $brand, + 'price_min' => $price_min, + 'price_max' => $price_max, + 'filter_attr'=>$filter_attr, + 'display' => $display_type + ); + + $page = intval($page); + if ($page < 1) + { + $page = 1; + } + + $page_count = $record_count > 0 ? intval(ceil($record_count / $size)) : 1; + + $pager['page'] = $page; + $pager['size'] = $size; + $pager['sort'] = $sort; + $pager['order'] = $order; + $pager['record_count'] = $record_count; + $pager['page_count'] = $page_count; + $pager['display'] = $display_type; + + switch ($app) + { + case 'category': + $uri_args = array('cid' => $cat, 'bid' => $brand, 'price_min'=>$price_min, 'price_max'=>$price_max, 'filter_attr'=>$filter_attr, 'sort' => $sort, 'order' => $order, 'display' => $display_type); + break; + case 'article_cat': + $uri_args = array('acid' => $cat, 'sort' => $sort, 'order' => $order); + break; + case 'brand': + $uri_args = array('cid' => $cat, 'bid' => $brand, 'sort' => $sort, 'order' => $order, 'display' => $display_type); + break; + case 'search': + $uri_args = array('cid' => $cat, 'bid' => $brand, 'sort' => $sort, 'order' => $order); + break; + case 'exchange': + $uri_args = array('cid' => $cat, 'integral_min'=>$price_min, 'integral_max'=>$price_max, 'sort' => $sort, 'order' => $order, 'display' => $display_type); + break; + } + /* 分页样式 */ + $pager['styleid'] = isset($GLOBALS['_CFG']['page_style'])? intval($GLOBALS['_CFG']['page_style']) : 0; + + $page_prev = ($page > 1) ? $page - 1 : 1; + $page_next = ($page < $page_count) ? $page + 1 : $page_count; + if ($pager['styleid'] == 0) + { + if (!empty($url_format)) + { + $pager['page_first'] = $url_format . 1; + $pager['page_prev'] = $url_format . $page_prev; + $pager['page_next'] = $url_format . $page_next; + $pager['page_last'] = $url_format . $page_count; + } + else + { + $pager['page_first'] = build_uri($app, $uri_args, '', 1, $keywords); + $pager['page_prev'] = build_uri($app, $uri_args, '', $page_prev, $keywords); + $pager['page_next'] = build_uri($app, $uri_args, '', $page_next, $keywords); + $pager['page_last'] = build_uri($app, $uri_args, '', $page_count, $keywords); + } + $pager['array'] = array(); + + for ($i = 1; $i <= $page_count; $i++) + { + $pager['array'][$i] = $i; + } + } + else + { + $_pagenum = 10; // 显示的页码 + $_offset = 2; // 当前页偏移值 + $_from = $_to = 0; // 开始页, 结束页 + if($_pagenum > $page_count) + { + $_from = 1; + $_to = $page_count; + } + else + { + $_from = $page - $_offset; + $_to = $_from + $_pagenum - 1; + if($_from < 1) + { + $_to = $page + 1 - $_from; + $_from = 1; + if($_to - $_from < $_pagenum) + { + $_to = $_pagenum; + } + } + elseif($_to > $page_count) + { + $_from = $page_count - $_pagenum + 1; + $_to = $page_count; + } + } + if (!empty($url_format)) + { + $pager['page_first'] = ($page - $_offset > 1 && $_pagenum < $page_count) ? $url_format . 1 : ''; + $pager['page_prev'] = ($page > 1) ? $url_format . $page_prev : ''; + $pager['page_next'] = ($page < $page_count) ? $url_format . $page_next : ''; + $pager['page_last'] = ($_to < $page_count) ? $url_format . $page_count : ''; + $pager['page_kbd'] = ($_pagenum < $page_count) ? true : false; + $pager['page_number'] = array(); + for ($i=$_from;$i<=$_to;++$i) + { + $pager['page_number'][$i] = $url_format . $i; + } + } + else + { + $pager['page_first'] = ($page - $_offset > 1 && $_pagenum < $page_count) ? build_uri($app, $uri_args, '', 1, $keywords) : ''; + $pager['page_prev'] = ($page > 1) ? build_uri($app, $uri_args, '', $page_prev, $keywords) : ''; + $pager['page_next'] = ($page < $page_count) ? build_uri($app, $uri_args, '', $page_next, $keywords) : ''; + $pager['page_last'] = ($_to < $page_count) ? build_uri($app, $uri_args, '', $page_count, $keywords) : ''; + $pager['page_kbd'] = ($_pagenum < $page_count) ? true : false; + $pager['page_number'] = array(); + for ($i=$_from;$i<=$_to;++$i) + { + $pager['page_number'][$i] = build_uri($app, $uri_args, '', $i, $keywords); + } + } + } + if (!empty($sch_array)) + { + $pager['search'] = $sch_array; + } + else + { + $pager['search']['category'] = $cat; + foreach ($sch AS $key => $row) + { + $pager['search'][$key] = $row; + } + } + + $GLOBALS['smarty']->assign('pager', $pager); +} + +/** + * 生成给pager.lbi赋值的数组 + * + * @access public + * @param string $url 分页的链接地址(必须是带有参数的地址,若不是可以伪造一个无用参数) + * @param array $param 链接参数 key为参数名,value为参数值 + * @param int $record 记录总数量 + * @param int $page 当前页数 + * @param int $size 每页大小 + * + * @return array $pager + */ +function get_pager($url, $param, $record_count, $page = 1, $size = 10) +{ + $size = intval($size); + if ($size < 1) + { + $size = 10; + } + + $page = intval($page); + if ($page < 1) + { + $page = 1; + } + + $record_count = intval($record_count); + + $page_count = $record_count > 0 ? intval(ceil($record_count / $size)) : 1; + if ($page > $page_count) + { + $page = $page_count; + } + /* 分页样式 */ + $pager['styleid'] = isset($GLOBALS['_CFG']['page_style'])? intval($GLOBALS['_CFG']['page_style']) : 0; + + $page_prev = ($page > 1) ? $page - 1 : 1; + $page_next = ($page < $page_count) ? $page + 1 : $page_count; + + /* 将参数合成url字串 */ + $param_url = '?'; + foreach ($param AS $key => $value) + { + $param_url .= $key . '=' . $value . '&'; + } + + $pager['url'] = $url; + $pager['start'] = ($page -1) * $size; + $pager['page'] = $page; + $pager['size'] = $size; + $pager['record_count'] = $record_count; + $pager['page_count'] = $page_count; + + if ($pager['styleid'] == 0) + { + $pager['page_first'] = $url . $param_url . 'page=1'; + $pager['page_prev'] = $url . $param_url . 'page=' . $page_prev; + $pager['page_next'] = $url . $param_url . 'page=' . $page_next; + $pager['page_last'] = $url . $param_url . 'page=' . $page_count; + $pager['array'] = array(); + for ($i = 1; $i <= $page_count; $i++) + { + $pager['array'][$i] = $i; + } + } + else + { + $_pagenum = 10; // 显示的页码 + $_offset = 2; // 当前页偏移值 + $_from = $_to = 0; // 开始页, 结束页 + if($_pagenum > $page_count) + { + $_from = 1; + $_to = $page_count; + } + else + { + $_from = $page - $_offset; + $_to = $_from + $_pagenum - 1; + if($_from < 1) + { + $_to = $page + 1 - $_from; + $_from = 1; + if($_to - $_from < $_pagenum) + { + $_to = $_pagenum; + } + } + elseif($_to > $page_count) + { + $_from = $page_count - $_pagenum + 1; + $_to = $page_count; + } + } + $url_format = $url . $param_url . 'page='; + $pager['page_first'] = ($page - $_offset > 1 && $_pagenum < $page_count) ? $url_format . 1 : ''; + $pager['page_prev'] = ($page > 1) ? $url_format . $page_prev : ''; + $pager['page_next'] = ($page < $page_count) ? $url_format . $page_next : ''; + $pager['page_last'] = ($_to < $page_count) ? $url_format . $page_count : ''; + $pager['page_kbd'] = ($_pagenum < $page_count) ? true : false; + $pager['page_number'] = array(); + for ($i=$_from;$i<=$_to;++$i) + { + $pager['page_number'][$i] = $url_format . $i; + } + } + $pager['search'] = $param; + + return $pager; +} + +/** + * 调用调查内容 + * + * @access public + * @param integer $id 调查的编号 + * @return array + */ +function get_vote($id = '') +{ + /* 随机取得一个调查的主题 */ + if (empty($id)) + { + $time = gmtime(); + $sql = 'SELECT vote_id, vote_name, can_multi, vote_count, RAND() AS rnd' . + ' FROM ' . $GLOBALS['ecs']->table('vote') . + " WHERE start_time <= '$time' AND end_time >= '$time' ". + ' ORDER BY rnd LIMIT 1'; + } + else + { + $sql = 'SELECT vote_id, vote_name, can_multi, vote_count' . + ' FROM ' . $GLOBALS['ecs']->table('vote'). + " WHERE vote_id = '$id'"; + } + + $vote_arr = $GLOBALS['db']->getRow($sql); + + if ($vote_arr !== false && !empty($vote_arr)) + { + /* 通过调查的ID,查询调查选项 */ + $sql_option = 'SELECT v.*, o.option_id, o.vote_id, o.option_name, o.option_count ' . + 'FROM ' . $GLOBALS['ecs']->table('vote') . ' AS v, ' . + $GLOBALS['ecs']->table('vote_option') . ' AS o ' . + "WHERE o.vote_id = v.vote_id AND o.vote_id = '$vote_arr[vote_id]' ORDER BY o.option_order ASC, o.option_id DESC"; + $res = $GLOBALS['db']->getAll($sql_option); + + /* 总票数 */ + $sql = 'SELECT SUM(option_count) AS all_option FROM ' . $GLOBALS['ecs']->table('vote_option') . + " WHERE vote_id = '" . $vote_arr['vote_id'] . "' GROUP BY vote_id"; + $option_num = $GLOBALS['db']->getOne($sql); + + $arr = array(); + $count = 100; + foreach ($res AS $idx => $row) + { + if ($option_num > 0 && $idx == count($res) - 1) + { + $percent = $count; + } + else + { + $percent = ($row['vote_count'] > 0 && $option_num > 0) ? round(($row['option_count'] / $option_num) * 100) : 0; + + $count -= $percent; + } + $arr[$row['vote_id']]['options'][$row['option_id']]['percent'] = $percent; + + $arr[$row['vote_id']]['vote_id'] = $row['vote_id']; + $arr[$row['vote_id']]['vote_name'] = $row['vote_name']; + $arr[$row['vote_id']]['can_multi'] = $row['can_multi']; + $arr[$row['vote_id']]['vote_count'] = $row['vote_count']; + + $arr[$row['vote_id']]['options'][$row['option_id']]['option_id'] = $row['option_id']; + $arr[$row['vote_id']]['options'][$row['option_id']]['option_name'] = $row['option_name']; + $arr[$row['vote_id']]['options'][$row['option_id']]['option_count'] = $row['option_count']; + } + + $vote_arr['vote_id'] = (!empty($vote_arr['vote_id'])) ? $vote_arr['vote_id'] : ''; + + $vote = array('id' => $vote_arr['vote_id'], 'content' => $arr); + + return $vote; + } +} + +/** + * 获得浏览器名称和版本 + * + * @access public + * @return string + */ +function get_user_browser() +{ + if (empty($_SERVER['HTTP_USER_AGENT'])) + { + return ''; + } + + $agent = $_SERVER['HTTP_USER_AGENT']; + $browser = ''; + $browser_ver = ''; + + if (preg_match('/MSIE\s([^\s|;]+)/i', $agent, $regs)) + { + $browser = 'Internet Explorer'; + $browser_ver = $regs[1]; + } + elseif (preg_match('/FireFox\/([^\s]+)/i', $agent, $regs)) + { + $browser = 'FireFox'; + $browser_ver = $regs[1]; + } + elseif (preg_match('/Maxthon/i', $agent, $regs)) + { + $browser = '(Internet Explorer ' .$browser_ver. ') Maxthon'; + $browser_ver = ''; + } + elseif (preg_match('/Opera[\s|\/]([^\s]+)/i', $agent, $regs)) + { + $browser = 'Opera'; + $browser_ver = $regs[1]; + } + elseif (preg_match('/OmniWeb\/(v*)([^\s|;]+)/i', $agent, $regs)) + { + $browser = 'OmniWeb'; + $browser_ver = $regs[2]; + } + elseif (preg_match('/Netscape([\d]*)\/([^\s]+)/i', $agent, $regs)) + { + $browser = 'Netscape'; + $browser_ver = $regs[2]; + } + elseif (preg_match('/safari\/([^\s]+)/i', $agent, $regs)) + { + $browser = 'Safari'; + $browser_ver = $regs[1]; + } + elseif (preg_match('/NetCaptor\s([^\s|;]+)/i', $agent, $regs)) + { + $browser = '(Internet Explorer ' .$browser_ver. ') NetCaptor'; + $browser_ver = $regs[1]; + } + elseif (preg_match('/Lynx\/([^\s]+)/i', $agent, $regs)) + { + $browser = 'Lynx'; + $browser_ver = $regs[1]; + } + + if (!empty($browser)) + { + return addslashes($browser . ' ' . $browser_ver); + } + else + { + return 'Unknow browser'; + } +} + +/** + * 判断是否为搜索引擎蜘蛛 + * + * @access public + * @return string + */ +function is_spider($record = true) +{ + static $spider = NULL; + + if ($spider !== NULL) + { + return $spider; + } + + if (empty($_SERVER['HTTP_USER_AGENT'])) + { + $spider = ''; + + return ''; + } + + $searchengine_bot = array( + 'googlebot', + 'mediapartners-google', + 'baiduspider+', + 'msnbot', + 'yodaobot', + 'yahoo! slurp;', + 'yahoo! slurp china;', + 'iaskspider', + 'sogou web spider', + 'sogou push spider' + ); + + $searchengine_name = array( + 'GOOGLE', + 'GOOGLE ADSENSE', + 'BAIDU', + 'MSN', + 'YODAO', + 'YAHOO', + 'Yahoo China', + 'IASK', + 'SOGOU', + 'SOGOU' + ); + + $spider = strtolower($_SERVER['HTTP_USER_AGENT']); + + foreach ($searchengine_bot AS $key => $value) + { + if (strpos($spider, $value) !== false) + { + $spider = $searchengine_name[$key]; + + if ($record === true) + { + $GLOBALS['db']->autoReplace($GLOBALS['ecs']->table('searchengine'), array('date' => local_date('Y-m-d'), 'searchengine' => $spider, 'count' => 1), array('count' => 1)); + } + + return $spider; + } + } + + $spider = ''; + + return ''; +} + +/** + * 获得客户端的操作系统 + * + * @access private + * @return void + */ +function get_os() +{ + if (empty($_SERVER['HTTP_USER_AGENT'])) + { + return 'Unknown'; + } + + $agent = strtolower($_SERVER['HTTP_USER_AGENT']); + $os = ''; + + if (strpos($agent, 'win') !== false) + { + if (strpos($agent, 'nt 5.1') !== false) + { + $os = 'Windows XP'; + } + elseif (strpos($agent, 'nt 5.2') !== false) + { + $os = 'Windows 2003'; + } + elseif (strpos($agent, 'nt 5.0') !== false) + { + $os = 'Windows 2000'; + } + elseif (strpos($agent, 'nt 6.0') !== false) + { + $os = 'Windows Vista'; + } + elseif (strpos($agent, 'nt') !== false) + { + $os = 'Windows NT'; + } + elseif (strpos($agent, 'win 9x') !== false && strpos($agent, '4.90') !== false) + { + $os = 'Windows ME'; + } + elseif (strpos($agent, '98') !== false) + { + $os = 'Windows 98'; + } + elseif (strpos($agent, '95') !== false) + { + $os = 'Windows 95'; + } + elseif (strpos($agent, '32') !== false) + { + $os = 'Windows 32'; + } + elseif (strpos($agent, 'ce') !== false) + { + $os = 'Windows CE'; + } + } + elseif (strpos($agent, 'linux') !== false) + { + $os = 'Linux'; + } + elseif (strpos($agent, 'unix') !== false) + { + $os = 'Unix'; + } + elseif (strpos($agent, 'sun') !== false && strpos($agent, 'os') !== false) + { + $os = 'SunOS'; + } + elseif (strpos($agent, 'ibm') !== false && strpos($agent, 'os') !== false) + { + $os = 'IBM OS/2'; + } + elseif (strpos($agent, 'mac') !== false && strpos($agent, 'pc') !== false) + { + $os = 'Macintosh'; + } + elseif (strpos($agent, 'powerpc') !== false) + { + $os = 'PowerPC'; + } + elseif (strpos($agent, 'aix') !== false) + { + $os = 'AIX'; + } + elseif (strpos($agent, 'hpux') !== false) + { + $os = 'HPUX'; + } + elseif (strpos($agent, 'netbsd') !== false) + { + $os = 'NetBSD'; + } + elseif (strpos($agent, 'bsd') !== false) + { + $os = 'BSD'; + } + elseif (strpos($agent, 'osf1') !== false) + { + $os = 'OSF1'; + } + elseif (strpos($agent, 'irix') !== false) + { + $os = 'IRIX'; + } + elseif (strpos($agent, 'freebsd') !== false) + { + $os = 'FreeBSD'; + } + elseif (strpos($agent, 'teleport') !== false) + { + $os = 'teleport'; + } + elseif (strpos($agent, 'flashget') !== false) + { + $os = 'flashget'; + } + elseif (strpos($agent, 'webzip') !== false) + { + $os = 'webzip'; + } + elseif (strpos($agent, 'offline') !== false) + { + $os = 'offline'; + } + else + { + $os = 'Unknown'; + } + + return $os; +} + +/** + * 统计访问信息 + * + * @access public + * @return void + */ +function visit_stats() +{ + if (isset($GLOBALS['_CFG']['visit_stats']) && $GLOBALS['_CFG']['visit_stats'] == 'off') + { + return; + } + $time = gmtime(); + /* 检查客户端是否存在访问统计的cookie */ + $visit_times = (!empty($_COOKIE['ECS']['visit_times'])) ? intval($_COOKIE['ECS']['visit_times']) + 1 : 1; + setcookie('ECS[visit_times]', $visit_times, $time + 86400 * 365, '/'); + + $browser = get_user_browser(); + $os = get_os(); + $ip = real_ip(); + $area = ecs_geoip($ip); + + /* 语言 */ + if (!empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])) + { + $pos = strpos($_SERVER['HTTP_ACCEPT_LANGUAGE'], ';'); + $lang = addslashes(($pos !== false) ? substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, $pos) : $_SERVER['HTTP_ACCEPT_LANGUAGE']); + } + else + { + $lang = ''; + } + + /* 来源 */ + if (!empty($_SERVER['HTTP_REFERER']) && strlen($_SERVER['HTTP_REFERER']) > 9) + { + $pos = strpos($_SERVER['HTTP_REFERER'], '/', 9); + if ($pos !== false) + { + $domain = substr($_SERVER['HTTP_REFERER'], 0, $pos); + $path = substr($_SERVER['HTTP_REFERER'], $pos); + + /* 来源关键字 */ + if (!empty($domain) && !empty($path)) + { + save_searchengine_keyword($domain, $path); + } + } + else + { + $domain = $path = ''; + } + } + else + { + $domain = $path = ''; + } + + $sql = 'INSERT INTO ' . $GLOBALS['ecs']->table('stats') . ' ( ' . + 'ip_address, visit_times, browser, system, language, area, ' . + 'referer_domain, referer_path, access_url, access_time' . + ') VALUES (' . + "'$ip', '$visit_times', '$browser', '$os', '$lang', '$area', ". + "'" . addslashes($domain) ."', '" . addslashes($path) ."', '" . addslashes(PHP_SELF) ."', '" . $time . "')"; + $GLOBALS['db']->query($sql); +} + +/** + * 保存搜索引擎关键字 + * + * @access public + * @return void + */ +function save_searchengine_keyword($domain, $path) +{ + if (strpos($domain, 'google.com.tw') !== false && preg_match('/q=([^&]*)/i', $path, $regs)) + { + $searchengine = 'GOOGLE TAIWAN'; + $keywords = urldecode($regs[1]); // google taiwan + } + if (strpos($domain, 'google.cn') !== false && preg_match('/q=([^&]*)/i', $path, $regs)) + { + $searchengine = 'GOOGLE CHINA'; + $keywords = urldecode($regs[1]); // google china + } + if (strpos($domain, 'google.com') !== false && preg_match('/q=([^&]*)/i', $path, $regs)) + { + $searchengine = 'GOOGLE'; + $keywords = urldecode($regs[1]); // google + } + elseif (strpos($domain, 'baidu.') !== false && preg_match('/wd=([^&]*)/i', $path, $regs)) + { + $searchengine = 'BAIDU'; + $keywords = urldecode($regs[1]); // baidu + } + elseif (strpos($domain, 'baidu.') !== false && preg_match('/word=([^&]*)/i', $path, $regs)) + { + $searchengine = 'BAIDU'; + $keywords = urldecode($regs[1]); // baidu + } + elseif (strpos($domain, '114.vnet.cn') !== false && preg_match('/kw=([^&]*)/i', $path, $regs)) + { + $searchengine = 'CT114'; + $keywords = urldecode($regs[1]); // ct114 + } + elseif (strpos($domain, 'iask.com') !== false && preg_match('/k=([^&]*)/i', $path, $regs)) + { + $searchengine = 'IASK'; + $keywords = urldecode($regs[1]); // iask + } + elseif (strpos($domain, 'soso.com') !== false && preg_match('/w=([^&]*)/i', $path, $regs)) + { + $searchengine = 'SOSO'; + $keywords = urldecode($regs[1]); // soso + } + elseif (strpos($domain, 'sogou.com') !== false && preg_match('/query=([^&]*)/i', $path, $regs)) + { + $searchengine = 'SOGOU'; + $keywords = urldecode($regs[1]); // sogou + } + elseif (strpos($domain, 'so.163.com') !== false && preg_match('/q=([^&]*)/i', $path, $regs)) + { + $searchengine = 'NETEASE'; + $keywords = urldecode($regs[1]); // netease + } + elseif (strpos($domain, 'yodao.com') !== false && preg_match('/q=([^&]*)/i', $path, $regs)) + { + $searchengine = 'YODAO'; + $keywords = urldecode($regs[1]); // yodao + } + elseif (strpos($domain, 'zhongsou.com') !== false && preg_match('/word=([^&]*)/i', $path, $regs)) + { + $searchengine = 'ZHONGSOU'; + $keywords = urldecode($regs[1]); // zhongsou + } + elseif (strpos($domain, 'search.tom.com') !== false && preg_match('/w=([^&]*)/i', $path, $regs)) + { + $searchengine = 'TOM'; + $keywords = urldecode($regs[1]); // tom + } + elseif (strpos($domain, 'live.com') !== false && preg_match('/q=([^&]*)/i', $path, $regs)) + { + $searchengine = 'MSLIVE'; + $keywords = urldecode($regs[1]); // MSLIVE + } + elseif (strpos($domain, 'tw.search.yahoo.com') !== false && preg_match('/p=([^&]*)/i', $path, $regs)) + { + $searchengine = 'YAHOO TAIWAN'; + $keywords = urldecode($regs[1]); // yahoo taiwan + } + elseif (strpos($domain, 'cn.yahoo.') !== false && preg_match('/p=([^&]*)/i', $path, $regs)) + { + $searchengine = 'YAHOO CHINA'; + $keywords = urldecode($regs[1]); // yahoo china + } + elseif (strpos($domain, 'yahoo.') !== false && preg_match('/p=([^&]*)/i', $path, $regs)) + { + $searchengine = 'YAHOO'; + $keywords = urldecode($regs[1]); // yahoo + } + elseif (strpos($domain, 'msn.com.tw') !== false && preg_match('/q=([^&]*)/i', $path, $regs)) + { + $searchengine = 'MSN TAIWAN'; + $keywords = urldecode($regs[1]); // msn taiwan + } + elseif (strpos($domain, 'msn.com.cn') !== false && preg_match('/q=([^&]*)/i', $path, $regs)) + { + $searchengine = 'MSN CHINA'; + $keywords = urldecode($regs[1]); // msn china + } + elseif (strpos($domain, 'msn.com') !== false && preg_match('/q=([^&]*)/i', $path, $regs)) + { + $searchengine = 'MSN'; + $keywords = urldecode($regs[1]); // msn + } + + if (!empty($keywords)) + { + $gb_search = array('YAHOO CHINA', 'TOM', 'ZHONGSOU', 'NETEASE', 'SOGOU', 'SOSO', 'IASK', 'CT114', 'BAIDU'); + if (EC_CHARSET == 'utf-8' && in_array($searchengine, $gb_search)) + { + $keywords = ecs_iconv('GBK', 'UTF8', $keywords); + } + if (EC_CHARSET == 'gbk' && !in_array($searchengine, $gb_search)) + { + $keywords = ecs_iconv('UTF8', 'GBK', $keywords); + } + + $GLOBALS['db']->autoReplace($GLOBALS['ecs']->table('keywords'), array('date' => local_date('Y-m-d'), 'searchengine' => $searchengine, 'keyword' => addslashes($keywords), 'count' => 1), array('count' => 1)); + } +} + +/** + * 获得指定用户、商品的所有标记 + * + * @access public + * @param integer $goods_id + * @param integer $user_id + * @return array + */ +function get_tags($goods_id = 0, $user_id = 0) +{ + $where = ''; + if ($goods_id > 0) + { + $where .= " goods_id = '$goods_id'"; + } + + if ($user_id > 0) + { + if ($goods_id > 0) + { + $where .= " AND"; + } + $where .= " user_id = '$user_id'"; + } + + if ($where > '') + { + $where = ' WHERE' . $where; + } + + $sql = 'SELECT tag_id, user_id, tag_words, COUNT(tag_id) AS tag_count' . + ' FROM ' . $GLOBALS['ecs']->table('tag') . + "$where GROUP BY tag_words"; + $arr = $GLOBALS['db']->getAll($sql); + + return $arr; +} + +/** + * 获取指定主题某个模板的主题的动态模块 + * + * @access public + * @param string $theme 模板主题 + * @param string $tmp 模板名称 + * + * @return array() + */ +function get_dyna_libs($theme, $tmp) +{ + $ext = end(explode('.', $tmp)); + $tmp = basename($tmp,".$ext"); + $sql = 'SELECT region, library, sort_order, id, number, type' . + ' FROM ' . $GLOBALS['ecs']->table('template') . + " WHERE theme = '$theme' AND filename = '" . $tmp . "' AND type > 0 AND remarks=''". + ' ORDER BY region, library, sort_order'; + $res = $GLOBALS['db']->getAll($sql); + + $dyna_libs = array(); + foreach ($res AS $row) + { + $dyna_libs[$row['region']][$row['library']][] = array( + 'id' => $row['id'], + 'number' => $row['number'], + 'type' => $row['type'] + ); + } + + return $dyna_libs; +} + +/** + * 替换动态模块 + * + * @access public + * @param string $matches 匹配内容 + * + * @return string 结果 + */ +function dyna_libs_replace($matches) +{ + $key = '/' . $matches[1]; + + if ($row = array_shift($GLOBALS['libs'][$key])) + { + $str = ''; + switch($row['type']) + { + case 1: + // 分类的商品 + $str = '{assign var="cat_goods" value=$cat_goods_' .$row['id']. '}{assign var="goods_cat" value=$goods_cat_' .$row['id']. '}'; + break; + case 2: + // 品牌的商品 + $str = '{assign var="brand_goods" value=$brand_goods_' .$row['id']. '}{assign var="goods_brand" value=$goods_brand_' .$row['id']. '}'; + break; + case 3: + // 文章列表 + $str = '{assign var="articles" value=$articles_' .$row['id']. '}{assign var="articles_cat" value=$articles_cat_' .$row['id']. '}'; + break; + case 4: + //广告位 + $str = '{assign var="ads_id" value=' . $row['id'] . '}{assign var="ads_num" value=' . $row['number'] . '}'; + break; + } + return $str . $matches[0]; + } + else + { + return $matches[0]; + } +} + +/** + * 处理上传文件,并返回上传图片名(上传失败时返回图片名为空) + * + * @access public + * @param array $upload $_FILES 数组 + * @param array $type 图片所属类别,即data目录下的文件夹名 + * + * @return string 上传图片名 + */ +function upload_file($upload, $type) +{ + if (!empty($upload['tmp_name'])) + { + $ftype = check_file_type($upload['tmp_name'], $upload['name'], '|png|jpg|jpeg|gif|doc|xls|txt|zip|ppt|pdf|rar|docx|xlsx|pptx|'); + if (!empty($ftype)) + { + $name = date('Ymd'); + for ($i = 0; $i < 6; $i++) + { + $name .= chr(mt_rand(97, 122)); + } + + $name = $_SESSION['user_id'] . '_' . $name . '.' . $ftype; + + $target = ROOT_PATH . DATA_DIR . '/' . $type . '/' . $name; + if (!move_upload_file($upload['tmp_name'], $target)) + { + $GLOBALS['err']->add($GLOBALS['_LANG']['upload_file_error'], 1); + + return false; + } + else + { + return $name; + } + } + else + { + $GLOBALS['err']->add($GLOBALS['_LANG']['upload_file_type'], 1); + + return false; + } + } + else + { + $GLOBALS['err']->add($GLOBALS['_LANG']['upload_file_error']); + return false; + } +} + +/** + * 显示一个提示信息 + * + * @access public + * @param string $content + * @param string $link + * @param string $href + * @param string $type 信息类型:warning, error, info + * @param string $auto_redirect 是否自动跳转 + * @return void + */ +function show_message($content, $links = '', $hrefs = '', $type = 'info', $auto_redirect = true) +{ + assign_template(); + + $msg['content'] = $content; + if (is_array($links) && is_array($hrefs)) + { + if (!empty($links) && count($links) == count($hrefs)) + { + foreach($links as $key =>$val) + { + $msg['url_info'][$val] = $hrefs[$key]; + } + $msg['back_url'] = $hrefs['0']; + } + } + else + { + $link = empty($links) ? $GLOBALS['_LANG']['back_up_page'] : $links; + $href = empty($hrefs) ? 'javascript:history.back()' : $hrefs; + $msg['url_info'][$link] = $href; + $msg['back_url'] = $href; + } + + $msg['type'] = $type; + $position = assign_ur_here(0, $GLOBALS['_LANG']['sys_msg']); + $GLOBALS['smarty']->assign('page_title', $position['title']); // 页面标题 + $GLOBALS['smarty']->assign('ur_here', $position['ur_here']); // 当前位置 + + if (is_null($GLOBALS['smarty']->get_template_vars('helps'))) + { + $GLOBALS['smarty']->assign('helps', get_shop_help()); // 网店帮助 + } + + $GLOBALS['smarty']->assign('auto_redirect', $auto_redirect); + $GLOBALS['smarty']->assign('message', $msg); + $GLOBALS['smarty']->display('message.dwt'); + + exit; +} + +/** + * 将一个形如+10, 10, -10, 10%的字串转换为相应数字,并返回操作符号 + * + * @access public + * @param string str 要格式化的数据 + * @param char operate 操作符号,只能返回‘+’或‘*’; + * @return float value 浮点数 + */ +function parse_rate_value($str, &$operate) +{ + $operate = '+'; + $is_rate = false; + + $str = trim($str); + if (empty($str)) + { + return 0; + } + if ($str[strlen($str) - 1] == '%') + { + $value = floatval($str); + if ($value > 0) + { + $operate = '*'; + + return $value / 100; + } + else + { + return 0; + } + } + else + { + return floatval($str); + } +} + +/** + * 重新计算购物车中的商品价格:目的是当用户登录时享受会员价格,当用户退出登录时不享受会员价格 + * 如果商品有促销,价格不变 + * + * @access public + * @return void + */ +function recalculate_price() +{ + /* 取得有可能改变价格的商品:除配件和赠品之外的商品 */ + $sql = 'SELECT c.rec_id, c.goods_id, c.goods_attr_id, g.promote_price, g.promote_start_date, c.goods_number,'. + "g.promote_end_date, IFNULL(mp.user_price, g.shop_price * '$_SESSION[discount]') AS member_price ". + 'FROM ' . $GLOBALS['ecs']->table('cart') . ' AS c '. + 'LEFT JOIN ' . $GLOBALS['ecs']->table('goods') . ' AS g ON g.goods_id = c.goods_id '. + "LEFT JOIN " . $GLOBALS['ecs']->table('member_price') . " AS mp ". + "ON mp.goods_id = g.goods_id AND mp.user_rank = '" . $_SESSION['user_rank'] . "' ". + "WHERE session_id = '" .SESS_ID. "' AND c.parent_id = 0 AND c.is_gift = 0 AND c.goods_id > 0 " . + "AND c.rec_type = '" . CART_GENERAL_GOODS . "' AND c.extension_code <> 'package_buy'"; + + $res = $GLOBALS['db']->getAll($sql); + + foreach ($res AS $row) + { + $attr_id = empty($row['goods_attr_id']) ? array() : explode(',', $row['goods_attr_id']); + + + $goods_price = get_final_price($row['goods_id'], $row['goods_number'], true, $attr_id); + + + $goods_sql = "UPDATE " .$GLOBALS['ecs']->table('cart'). " SET goods_price = '$goods_price' ". + "WHERE goods_id = '" . $row['goods_id'] . "' AND session_id = '" . SESS_ID . "' AND rec_id = '" . $row['rec_id'] . "'"; + + $GLOBALS['db']->query($goods_sql); + } + + /* 删除赠品,重新选择 */ + $GLOBALS['db']->query('DELETE FROM ' . $GLOBALS['ecs']->table('cart') . + " WHERE session_id = '" . SESS_ID . "' AND is_gift > 0"); +} + +/** + * 查询评论内容 + * + * @access public + * @params integer $id + * @params integer $type + * @params integer $page + * @return array + */ +function assign_comment($id, $type, $page = 1) +{ + /* 取得评论列表 */ + $count = $GLOBALS['db']->getOne('SELECT COUNT(*) FROM ' .$GLOBALS['ecs']->table('comment'). + " WHERE id_value = '$id' AND comment_type = '$type' AND status = 1 AND parent_id = 0"); + $size = !empty($GLOBALS['_CFG']['comments_number']) ? $GLOBALS['_CFG']['comments_number'] : 5; + + $page_count = ($count > 0) ? intval(ceil($count / $size)) : 1; + + $sql = 'SELECT * FROM ' . $GLOBALS['ecs']->table('comment') . + " WHERE id_value = '$id' AND comment_type = '$type' AND status = 1 AND parent_id = 0". + ' ORDER BY comment_id DESC'; + $res = $GLOBALS['db']->selectLimit($sql, $size, ($page-1) * $size); + + $arr = array(); + $ids = ''; + while ($row = $GLOBALS['db']->fetchRow($res)) + { + $ids .= $ids ? ",$row[comment_id]" : $row['comment_id']; + $arr[$row['comment_id']]['id'] = $row['comment_id']; + $arr[$row['comment_id']]['email'] = $row['email']; + $arr[$row['comment_id']]['username'] = $row['user_name']; + $arr[$row['comment_id']]['content'] = str_replace('\r\n', '
    ', htmlspecialchars($row['content'])); + $arr[$row['comment_id']]['content'] = nl2br(str_replace('\n', '
    ', $arr[$row['comment_id']]['content'])); + $arr[$row['comment_id']]['rank'] = $row['comment_rank']; + $arr[$row['comment_id']]['add_time'] = local_date($GLOBALS['_CFG']['time_format'], $row['add_time']); + } + /* 取得已有回复的评论 */ + if ($ids) + { + $sql = 'SELECT * FROM ' . $GLOBALS['ecs']->table('comment') . + " WHERE parent_id IN( $ids )"; + $res = $GLOBALS['db']->query($sql); + while ($row = $GLOBALS['db']->fetch_array($res)) + { + $arr[$row['parent_id']]['re_content'] = nl2br(str_replace('\n', '
    ', htmlspecialchars($row['content']))); + $arr[$row['parent_id']]['re_add_time'] = local_date($GLOBALS['_CFG']['time_format'], $row['add_time']); + $arr[$row['parent_id']]['re_email'] = $row['email']; + $arr[$row['parent_id']]['re_username'] = $row['user_name']; + } + } + /* 分页样式 */ + //$pager['styleid'] = isset($GLOBALS['_CFG']['page_style'])? intval($GLOBALS['_CFG']['page_style']) : 0; + $pager['page'] = $page; + $pager['size'] = $size; + $pager['record_count'] = $count; + $pager['page_count'] = $page_count; + $pager['page_first'] = "javascript:gotoPage(1,$id,$type)"; + $pager['page_prev'] = $page > 1 ? "javascript:gotoPage(" .($page-1). ",$id,$type)" : 'javascript:;'; + $pager['page_next'] = $page < $page_count ? 'javascript:gotoPage(' .($page + 1) . ",$id,$type)" : 'javascript:;'; + $pager['page_last'] = $page < $page_count ? 'javascript:gotoPage(' .$page_count. ",$id,$type)" : 'javascript:;'; + + $cmt = array('comments' => $arr, 'pager' => $pager); + + return $cmt; +} + +function assign_template($ctype = '', $catlist = array()) +{ + global $smarty; + + $smarty->assign('image_width', $GLOBALS['_CFG']['image_width']); + $smarty->assign('image_height', $GLOBALS['_CFG']['image_height']); + $smarty->assign('points_name', $GLOBALS['_CFG']['integral_name']); + $smarty->assign('qq', explode(',', $GLOBALS['_CFG']['qq'])); + $smarty->assign('ww', explode(',', $GLOBALS['_CFG']['ww'])); + $smarty->assign('ym', explode(',', $GLOBALS['_CFG']['ym'])); + $smarty->assign('msn', explode(',', $GLOBALS['_CFG']['msn'])); + $smarty->assign('skype', explode(',', $GLOBALS['_CFG']['skype'])); + $smarty->assign('stats_code', $GLOBALS['_CFG']['stats_code']); + $smarty->assign('copyright', sprintf($GLOBALS['_LANG']['copyright'], date('Y'), $GLOBALS['_CFG']['shop_name'])); + $smarty->assign('shop_name', $GLOBALS['_CFG']['shop_name']); + $smarty->assign('service_email', $GLOBALS['_CFG']['service_email']); + $smarty->assign('service_phone', $GLOBALS['_CFG']['service_phone']); + $smarty->assign('shop_address', $GLOBALS['_CFG']['shop_address']); + $smarty->assign('licensed', license_info()); + $smarty->assign('ecs_version', VERSION); + $smarty->assign('icp_number', $GLOBALS['_CFG']['icp_number']); + $smarty->assign('username', !empty($_SESSION['user_name']) ? $_SESSION['user_name'] : ''); + $smarty->assign('category_list', cat_list(0, 0, true, 2, false)); + $smarty->assign('catalog_list', cat_list(0, 0, false, 1, false)); + $smarty->assign('navigator_list', get_navigator($ctype, $catlist)); //自定义导航栏 + + if (!empty($GLOBALS['_CFG']['search_keywords'])) + { + $searchkeywords = explode(',', trim($GLOBALS['_CFG']['search_keywords'])); + } + else + { + $searchkeywords = array(); + } + $smarty->assign('searchkeywords', $searchkeywords); +} + +/** + * 将一个本地时间戳转成GMT时间戳 + * + * @access public + * @param int $time + * + * @return int $gmt_time; + */ +function time2gmt($time) +{ + return strtotime(gmdate('Y-m-d H:i:s', $time)); +} + +/** + * 查询会员的红包金额 + * + * @access public + * @param integer $user_id + * @return void + */ +function get_user_bonus($user_id = 0) +{ + if ($user_id == 0) + { + $user_id = $_SESSION['user_id']; + } + + $sql = "SELECT SUM(bt.type_money) AS bonus_value, COUNT(*) AS bonus_count ". + "FROM " .$GLOBALS['ecs']->table('user_bonus'). " AS ub, ". + $GLOBALS['ecs']->table('bonus_type') . " AS bt ". + "WHERE ub.user_id = '$user_id' AND ub.bonus_type_id = bt.type_id AND ub.order_id = 0"; + $row = $GLOBALS['db']->getRow($sql); + + return $row; +} + +/** + * 保存推荐uid + * + * @access public + * @param void + * + * @return void + * @author xuanyan + **/ +function set_affiliate() +{ + $config = unserialize($GLOBALS['_CFG']['affiliate']); + if (!empty($_GET['u']) && $config['on'] == 1) + { + if(!empty($config['config']['expire'])) + { + if($config['config']['expire_unit'] == 'hour') + { + $c = 1; + } + elseif($config['config']['expire_unit'] == 'day') + { + $c = 24; + } + elseif($config['config']['expire_unit'] == 'week') + { + $c = 24 * 7; + } + else + { + $c = 1; + } + setcookie('ecshop_affiliate_uid', intval($_GET['u']), gmtime() + 3600 * $config['config']['expire'] * $c); + } + else + { + setcookie('ecshop_affiliate_uid', intval($_GET['u']), gmtime() + 3600 * 24); // 过期时间为 1 天 + } + } +} + +/** + * 获取推荐uid + * + * @access public + * @param void + * + * @return int + * @author xuanyan + **/ +function get_affiliate() +{ + if (!empty($_COOKIE['ecshop_affiliate_uid'])) + { + $uid = intval($_COOKIE['ecshop_affiliate_uid']); + if ($GLOBALS['db']->getOne('SELECT user_id FROM ' . $GLOBALS['ecs']->table('users') . "WHERE user_id = '$uid'")) + { + return $uid; + } + else + { + setcookie('ecshop_affiliate_uid', '', 1); + } + } + + return 0; +} + +/** + * 获得指定分类同级的所有分类以及该分类下的子分类 + * + * @access public + * @param integer $cat_id 分类编号 + * @return array + */ +function article_categories_tree($cat_id = 0) +{ + if ($cat_id > 0) + { + $sql = 'SELECT parent_id FROM ' . $GLOBALS['ecs']->table('article_cat') . " WHERE cat_id = '$cat_id'"; + $parent_id = $GLOBALS['db']->getOne($sql); + } + else + { + $parent_id = 0; + } + + /* + 判断当前分类中全是是否是底级分类, + 如果是取出底级分类上级分类, + 如果不是取当前分类及其下的子分类 + */ + $sql = 'SELECT count(*) FROM ' . $GLOBALS['ecs']->table('article_cat') . " WHERE parent_id = '$parent_id'"; + if ($GLOBALS['db']->getOne($sql)) + { + /* 获取当前分类及其子分类 */ + $sql = 'SELECT a.cat_id, a.cat_name, a.sort_order AS parent_order, a.cat_id, ' . + 'b.cat_id AS child_id, b.cat_name AS child_name, b.sort_order AS child_order ' . + 'FROM ' . $GLOBALS['ecs']->table('article_cat') . ' AS a ' . + 'LEFT JOIN ' . $GLOBALS['ecs']->table('article_cat') . ' AS b ON b.parent_id = a.cat_id ' . + "WHERE a.parent_id = '$parent_id' AND a.cat_type=1 ORDER BY parent_order ASC, a.cat_id ASC, child_order ASC"; + } + else + { + /* 获取当前分类及其父分类 */ + $sql = 'SELECT a.cat_id, a.cat_name, b.cat_id AS child_id, b.cat_name AS child_name, b.sort_order ' . + 'FROM ' . $GLOBALS['ecs']->table('article_cat') . ' AS a ' . + 'LEFT JOIN ' . $GLOBALS['ecs']->table('article_cat') . ' AS b ON b.parent_id = a.cat_id ' . + "WHERE b.parent_id = '$parent_id' AND b.cat_type = 1 ORDER BY sort_order ASC"; + } + $res = $GLOBALS['db']->getAll($sql); + + $cat_arr = array(); + foreach ($res AS $row) + { + $cat_arr[$row['cat_id']]['id'] = $row['cat_id']; + $cat_arr[$row['cat_id']]['name'] = $row['cat_name']; + $cat_arr[$row['cat_id']]['url'] = build_uri('article_cat', array('acid' => $row['cat_id']), $row['cat_name']); + + if ($row['child_id'] != NULL) + { + $cat_arr[$row['cat_id']]['children'][$row['child_id']]['id'] = $row['child_id']; + $cat_arr[$row['cat_id']]['children'][$row['child_id']]['name'] = $row['child_name']; + $cat_arr[$row['cat_id']]['children'][$row['child_id']]['url'] = build_uri('article_cat', array('acid' => $row['child_id']), $row['child_name']); + } + } + + return $cat_arr; +} + +/** + * 获得指定文章分类的所有上级分类 + * + * @access public + * @param integer $cat 分类编号 + * @return array + */ +function get_article_parent_cats($cat) +{ + if ($cat == 0) + { + return array(); + } + + $arr = $GLOBALS['db']->GetAll('SELECT cat_id, cat_name, parent_id FROM ' . $GLOBALS['ecs']->table('article_cat')); + + if (empty($arr)) + { + return array(); + } + + $index = 0; + $cats = array(); + + while (1) + { + foreach ($arr AS $row) + { + if ($cat == $row['cat_id']) + { + $cat = $row['parent_id']; + + $cats[$index]['cat_id'] = $row['cat_id']; + $cats[$index]['cat_name'] = $row['cat_name']; + + $index++; + break; + } + } + + if ($index == 0 || $cat == 0) + { + break; + } + } + + return $cats; +} + +/** + * 取得某模板某库设置的数量 + * @param string $template 模板名,如index + * @param string $library 库名,如recommend_best + * @param int $def_num 默认数量:如果没有设置模板,显示的数量 + * @return int 数量 + */ +function get_library_number($library, $template = null) +{ + global $page_libs; + + if (empty($template)) + { + $template = basename(PHP_SELF); + $template = substr($template, 0, strrpos($template, '.')); + } + $template = addslashes($template); + + static $lib_list = array(); + + /* 如果没有该模板的信息,取得该模板的信息 */ + if (!isset($lib_list[$template])) + { + $lib_list[$template] = array(); + $sql = "SELECT library, number FROM " . $GLOBALS['ecs']->table('template') . + " WHERE theme = '" . $GLOBALS['_CFG']['template'] . "'" . + " AND filename = '$template' AND remarks='' "; + $res = $GLOBALS['db']->query($sql); + while ($row = $GLOBALS['db']->fetchRow($res)) + { + $lib = basename(strtolower(substr($row['library'], 0, strpos($row['library'], '.')))); + $lib_list[$template][$lib] = $row['number']; + } + } + + $num = 0; + if (isset($lib_list[$template][$library])) + { + $num = intval($lib_list[$template][$library]); + } + else + { + /* 模板设置文件查找默认值 */ + include_once(ROOT_PATH . ADMIN_PATH . '/includes/lib_template.php'); + static $static_page_libs = null; + if ($static_page_libs == null) + { + $static_page_libs = $page_libs; + } + $lib = '/library/' . $library . '.lbi'; + + $num = isset($static_page_libs[$template][$lib]) ? $static_page_libs[$template][$lib] : 3; + } + + return $num; +} + +/** + * 取得自定义导航栏列表 + * @param string $type 位置,如top、bottom、middle + * @return array 列表 + */ +function get_navigator($ctype = '', $catlist = array()) +{ + $sql = 'SELECT * FROM '. $GLOBALS['ecs']->table('nav') . ' + WHERE ifshow = \'1\' ORDER BY type, vieworder'; + $res = $GLOBALS['db']->query($sql); + + $cur_url = substr(strrchr($_SERVER['REQUEST_URI'],'/'),1); + + if (intval($GLOBALS['_CFG']['rewrite'])) + { + if(strpos($cur_url, '-')) + { + preg_match('/([a-z]*)-([0-9]*)/',$cur_url,$matches); + $cur_url = $matches[1].'.php?id='.$matches[2]; + } + } + else + { + $cur_url = substr(strrchr($_SERVER['REQUEST_URI'],'/'),1); + } + + $noindex = false; + $active = 0; + $navlist = array( + 'top' => array(), + 'middle' => array(), + 'bottom' => array() + ); + while ($row = $GLOBALS['db']->fetchRow($res)) + { + $navlist[$row['type']][] = array( + 'name' => $row['name'], + 'opennew' => $row['opennew'], + 'url' => $row['url'], + 'ctype' => $row['ctype'], + 'cid' => $row['cid'], + ); + } + + /*遍历自定义是否存在currentPage*/ + foreach($navlist['middle'] as $k=>$v) + { + $condition = empty($ctype) ? (strpos($cur_url, $v['url']) === 0) : (strpos($cur_url, $v['url']) === 0 && strlen($cur_url) == strlen($v['url'])); + if ($condition) + { + $navlist['middle'][$k]['active'] = 1; + $noindex = true; + $active += 1; + } + } + + if(!empty($ctype) && $active < 1) + { + foreach($catlist as $key => $val) + { + foreach($navlist['middle'] as $k=>$v) + { + if(!empty($v['ctype']) && $v['ctype'] == $ctype && $v['cid'] == $val && $active < 1) + { + $navlist['middle'][$k]['active'] = 1; + $noindex = true; + $active += 1; + } + } + } + } + + if ($noindex == false) { + $navlist['config']['index'] = 1; + } + + return $navlist; +} + +/** + * 授权信息内容 + * + * @return str + */ +function license_info() +{ + if($GLOBALS['_CFG']['licensed'] > 0) + { + /* 获取HOST */ + if (isset($_SERVER['HTTP_X_FORWARDED_HOST'])) + { + $host = $_SERVER['HTTP_X_FORWARDED_HOST']; + } + elseif (isset($_SERVER['HTTP_HOST'])) + { + $host = $_SERVER['HTTP_HOST']; + } + $url_domain=url_domain(); + $host = 'http://' . $host .$url_domain ; + $license = '  Licensed'; + return $license; + } + else + { + return ''; + } +} +function url_domain() +{ + $curr = strpos(PHP_SELF, ADMIN_PATH . '/') !== false ? + preg_replace('/(.*)(' . ADMIN_PATH . ')(\/?)(.)*/i', '\1', dirname(PHP_SELF)) : + dirname(PHP_SELF); + + $root = str_replace('\\', '/', $curr); + + if (substr($root, -1) != '/') + { + $root .= '/'; + } + + return $root; +} + +?> \ No newline at end of file diff --git a/includes/lib_order.php b/includes/lib_order.php new file mode 100644 index 0000000..1ce22ff --- /dev/null +++ b/includes/lib_order.php @@ -0,0 +1,2996 @@ + $val) + { + $config[$val['name']] = $val['value']; + } + + return $config; + } + else + { + return false; + } +} +/** + * 取得已安装的配送方式 + * @return array 已安装的配送方式 + */ +function shipping_list() +{ + $sql = 'SELECT shipping_id, shipping_name ' . + 'FROM ' . $GLOBALS['ecs']->table('shipping') . + ' WHERE enabled = 1'; + + return $GLOBALS['db']->getAll($sql); +} + +/** + * 取得配送方式信息 + * @param int $shipping_id 配送方式id + * @return array 配送方式信息 + */ +function shipping_info($shipping_id) +{ + $sql = 'SELECT * FROM ' . $GLOBALS['ecs']->table('shipping') . + " WHERE shipping_id = '$shipping_id' " . + 'AND enabled = 1'; + + return $GLOBALS['db']->getRow($sql); +} + +/** + * 取得可用的配送方式列表 + * @param array $region_id_list 收货人地区id数组(包括国家、省、市、区) + * @return array 配送方式数组 + */ +function available_shipping_list($region_id_list) +{ + $sql = 'SELECT s.shipping_id, s.shipping_code, s.shipping_name, ' . + 's.shipping_desc, s.insure, s.support_cod, a.configure ' . + 'FROM ' . $GLOBALS['ecs']->table('shipping') . ' AS s, ' . + $GLOBALS['ecs']->table('shipping_area') . ' AS a, ' . + $GLOBALS['ecs']->table('area_region') . ' AS r ' . + 'WHERE r.region_id ' . db_create_in($region_id_list) . + ' AND r.shipping_area_id = a.shipping_area_id AND a.shipping_id = s.shipping_id AND s.enabled = 1 ORDER BY s.shipping_order'; + + return $GLOBALS['db']->getAll($sql); +} + +/** + * 取得某配送方式对应于某收货地址的区域信息 + * @param int $shipping_id 配送方式id + * @param array $region_id_list 收货人地区id数组 + * @return array 配送区域信息(config 对应着反序列化的 configure) + */ +function shipping_area_info($shipping_id, $region_id_list) +{ + $sql = 'SELECT s.shipping_code, s.shipping_name, ' . + 's.shipping_desc, s.insure, s.support_cod, a.configure ' . + 'FROM ' . $GLOBALS['ecs']->table('shipping') . ' AS s, ' . + $GLOBALS['ecs']->table('shipping_area') . ' AS a, ' . + $GLOBALS['ecs']->table('area_region') . ' AS r ' . + "WHERE s.shipping_id = '$shipping_id' " . + 'AND r.region_id ' . db_create_in($region_id_list) . + ' AND r.shipping_area_id = a.shipping_area_id AND a.shipping_id = s.shipping_id AND s.enabled = 1'; + $row = $GLOBALS['db']->getRow($sql); + + if (!empty($row)) + { + $shipping_config = unserialize_config($row['configure']); + if (isset($shipping_config['pay_fee'])) + { + if (strpos($shipping_config['pay_fee'], '%') !== false) + { + $row['pay_fee'] = floatval($shipping_config['pay_fee']) . '%'; + } + else + { + $row['pay_fee'] = floatval($shipping_config['pay_fee']); + } + } + else + { + $row['pay_fee'] = 0.00; + } + } + + return $row; +} + +/** + * 计算运费 + * @param string $shipping_code 配送方式代码 + * @param mix $shipping_config 配送方式配置信息 + * @param float $goods_weight 商品重量 + * @param float $goods_amount 商品金额 + * @param float $goods_number 商品数量 + * @return float 运费 + */ +function shipping_fee($shipping_code, $shipping_config, $goods_weight, $goods_amount, $goods_number='') +{ + if (!is_array($shipping_config)) + { + $shipping_config = unserialize($shipping_config); + } + + $filename = ROOT_PATH . 'includes/modules/shipping/' . $shipping_code . '.php'; + if (file_exists($filename)) + { + include_once($filename); + + $obj = new $shipping_code($shipping_config); + + return $obj->calculate($goods_weight, $goods_amount, $goods_number); + } + else + { + return 0; + } +} + +/** + * 获取指定配送的保价费用 + * + * @access public + * @param string $shipping_code 配送方式的code + * @param float $goods_amount 保价金额 + * @param mix $insure 保价比例 + * @return float + */ +function shipping_insure_fee($shipping_code, $goods_amount, $insure) +{ + if (strpos($insure, '%') === false) + { + /* 如果保价费用不是百分比则直接返回该数值 */ + return floatval($insure); + } + else + { + $path = ROOT_PATH . 'includes/modules/shipping/' . $shipping_code . '.php'; + + if (file_exists($path)) + { + include_once($path); + + $shipping = new $shipping_code; + $insure = floatval($insure) / 100; + + if (method_exists($shipping, 'calculate_insure')) + { + return $shipping->calculate_insure($goods_amount, $insure); + } + else + { + return ceil($goods_amount * $insure); + } + } + else + { + return false; + } + } +} + +/** + * 取得已安装的支付方式列表 + * @return array 已安装的配送方式列表 + */ +function payment_list() +{ + $sql = 'SELECT pay_id, pay_name ' . + 'FROM ' . $GLOBALS['ecs']->table('payment') . + ' WHERE enabled = 1'; + + return $GLOBALS['db']->getAll($sql); +} + +/** + * 取得支付方式信息 + * @param int $pay_id 支付方式id + * @return array 支付方式信息 + */ +function payment_info($pay_id) +{ + $sql = 'SELECT * FROM ' . $GLOBALS['ecs']->table('payment') . + " WHERE pay_id = '$pay_id' AND enabled = 1"; + + return $GLOBALS['db']->getRow($sql); +} + +/** + * 获得订单需要支付的支付费用 + * + * @access public + * @param integer $payment_id + * @param float $order_amount + * @param mix $cod_fee + * @return float + */ +function pay_fee($payment_id, $order_amount, $cod_fee=null) +{ + $pay_fee = 0; + $payment = payment_info($payment_id); + $rate = ($payment['is_cod'] && !is_null($cod_fee)) ? $cod_fee : $payment['pay_fee']; + + if (strpos($rate, '%') !== false) + { + /* 支付费用是一个比例 */ + $val = floatval($rate) / 100; + $pay_fee = $val > 0 ? $order_amount * $val /(1- $val) : 0; + } + else + { + $pay_fee = floatval($rate); + } + + return round($pay_fee, 2); +} + +/** + * 取得可用的支付方式列表 + * @param bool $support_cod 配送方式是否支持货到付款 + * @param int $cod_fee 货到付款手续费(当配送方式支持货到付款时才传此参数) + * @param int $is_online 是否支持在线支付 + * @return array 配送方式数组 + */ +function available_payment_list($support_cod, $cod_fee = 0, $is_online = false) +{ + $sql = 'SELECT pay_id, pay_code, pay_name, pay_fee, pay_desc, pay_config, is_cod' . + ' FROM ' . $GLOBALS['ecs']->table('payment') . + ' WHERE enabled = 1 '; + if (!$support_cod) + { + $sql .= 'AND is_cod = 0 '; // 如果不支持货到付款 + } + if ($is_online) + { + $sql .= "AND is_online = '1' "; + } + $sql .= 'ORDER BY pay_order'; // 排序 + $res = $GLOBALS['db']->query($sql); + + $pay_list = array(); + while ($row = $GLOBALS['db']->fetchRow($res)) + { + if ($row['is_cod'] == '1') + { + $row['pay_fee'] = $cod_fee; + } + + $row['format_pay_fee'] = strpos($row['pay_fee'], '%') !== false ? $row['pay_fee'] : + price_format($row['pay_fee'], false); + $modules[] = $row; + } + + include_once(ROOT_PATH.'includes/lib_compositor.php'); + + if(isset($modules)) + { + return $modules; + } +} + +/** + * 取得包装列表 + * @return array 包装列表 + */ +function pack_list() +{ + $sql = 'SELECT * FROM ' . $GLOBALS['ecs']->table('pack'); + $res = $GLOBALS['db']->query($sql); + + $list = array(); + while ($row = $GLOBALS['db']->fetchRow($res)) + { + $row['format_pack_fee'] = price_format($row['pack_fee'], false); + $row['format_free_money'] = price_format($row['free_money'], false); + $list[] = $row; + } + + return $list; +} + +/** + * 取得包装信息 + * @param int $pack_id 包装id + * @return array 包装信息 + */ +function pack_info($pack_id) +{ + $sql = "SELECT * FROM " . $GLOBALS['ecs']->table('pack') . + " WHERE pack_id = '$pack_id'"; + + return $GLOBALS['db']->getRow($sql); +} + +/** + * 根据订单中的商品总额来获得包装的费用 + * + * @access public + * @param integer $pack_id + * @param float $goods_amount + * @return float + */ +function pack_fee($pack_id, $goods_amount) +{ + $pack = pack_info($pack_id); + + $val = (floatval($pack['free_money']) <= $goods_amount && $pack['free_money'] > 0) ? 0 : floatval($pack['pack_fee']); + + return $val; +} + +/** + * 取得贺卡列表 + * @return array 贺卡列表 + */ +function card_list() +{ + $sql = "SELECT * FROM " . $GLOBALS['ecs']->table('card'); + $res = $GLOBALS['db']->query($sql); + + $list = array(); + while ($row = $GLOBALS['db']->fetchRow($res)) + { + $row['format_card_fee'] = price_format($row['card_fee'], false); + $row['format_free_money'] = price_format($row['free_money'], false); + $list[] = $row; + } + + return $list; +} + +/** + * 取得贺卡信息 + * @param int $card_id 贺卡id + * @return array 贺卡信息 + */ +function card_info($card_id) +{ + $sql = "SELECT * FROM " . $GLOBALS['ecs']->table('card') . + " WHERE card_id = '$card_id'"; + + return $GLOBALS['db']->getRow($sql); +} + +/** + * 根据订单中商品总额获得需要支付的贺卡费用 + * + * @access public + * @param integer $card_id + * @param float $goods_amount + * @return float + */ +function card_fee($card_id, $goods_amount) +{ + $card = card_info($card_id); + + return ($card['free_money'] <= $goods_amount && $card['free_money'] > 0) ? 0 : $card['card_fee']; +} + +/** + * 取得订单信息 + * @param int $order_id 订单id(如果order_id > 0 就按id查,否则按sn查) + * @param string $order_sn 订单号 + * @return array 订单信息(金额都有相应格式化的字段,前缀是formated_) + */ +function order_info($order_id, $order_sn = '') +{ + /* 计算订单各种费用之和的语句 */ + $total_fee = " (goods_amount - discount + tax + shipping_fee + insure_fee + pay_fee + pack_fee + card_fee) AS total_fee "; + $order_id = intval($order_id); + if ($order_id > 0) + { + $sql = "SELECT *, " . $total_fee . " FROM " . $GLOBALS['ecs']->table('order_info') . + " WHERE order_id = '$order_id'"; + } + else + { + $sql = "SELECT *, " . $total_fee . " FROM " . $GLOBALS['ecs']->table('order_info') . + " WHERE order_sn = '$order_sn'"; + } + $order = $GLOBALS['db']->getRow($sql); + + /* 格式化金额字段 */ + if ($order) + { + $order['formated_goods_amount'] = price_format($order['goods_amount'], false); + $order['formated_discount'] = price_format($order['discount'], false); + $order['formated_tax'] = price_format($order['tax'], false); + $order['formated_shipping_fee'] = price_format($order['shipping_fee'], false); + $order['formated_insure_fee'] = price_format($order['insure_fee'], false); + $order['formated_pay_fee'] = price_format($order['pay_fee'], false); + $order['formated_pack_fee'] = price_format($order['pack_fee'], false); + $order['formated_card_fee'] = price_format($order['card_fee'], false); + $order['formated_total_fee'] = price_format($order['total_fee'], false); + $order['formated_money_paid'] = price_format($order['money_paid'], false); + $order['formated_bonus'] = price_format($order['bonus'], false); + $order['formated_integral_money'] = price_format($order['integral_money'], false); + $order['formated_surplus'] = price_format($order['surplus'], false); + $order['formated_order_amount'] = price_format(abs($order['order_amount']), false); + $order['formated_add_time'] = local_date($GLOBALS['_CFG']['time_format'], $order['add_time']); + } + + return $order; +} + +/** + * 判断订单是否已完成 + * @param array $order 订单信息 + * @return bool + */ +function order_finished($order) +{ + return $order['order_status'] == OS_CONFIRMED && + ($order['shipping_status'] == SS_SHIPPED || $order['shipping_status'] == SS_RECEIVED) && + ($order['pay_status'] == PS_PAYED || $order['pay_status'] == PS_PAYING); +} + +/** + * 取得订单商品 + * @param int $order_id 订单id + * @return array 订单商品数组 + */ +function order_goods($order_id) +{ + $sql = "SELECT rec_id, goods_id, goods_name, goods_sn, market_price, goods_number, " . + "goods_price, goods_attr, is_real, parent_id, is_gift, " . + "goods_price * goods_number AS subtotal, extension_code " . + "FROM " . $GLOBALS['ecs']->table('order_goods') . + " WHERE order_id = '$order_id'"; + + $res = $GLOBALS['db']->query($sql); + + while ($row = $GLOBALS['db']->fetchRow($res)) + { + if ($row['extension_code'] == 'package_buy') + { + $row['package_goods_list'] = get_package_goods($row['goods_id']); + } + $goods_list[] = $row; + } + + //return $GLOBALS['db']->getAll($sql); + return $goods_list; +} + +/** + * 取得订单总金额 + * @param int $order_id 订单id + * @param bool $include_gift 是否包括赠品 + * @return float 订单总金额 + */ +function order_amount($order_id, $include_gift = true) +{ + $sql = "SELECT SUM(goods_price * goods_number) " . + "FROM " . $GLOBALS['ecs']->table('order_goods') . + " WHERE order_id = '$order_id'"; + if (!$include_gift) + { + $sql .= " AND is_gift = 0"; + } + + return floatval($GLOBALS['db']->getOne($sql)); +} + +/** + * 取得某订单商品总重量和总金额(对应 cart_weight_price) + * @param int $order_id 订单id + * @return array ('weight' => **, 'amount' => **, 'formated_weight' => **) + */ +function order_weight_price($order_id) +{ + $sql = "SELECT SUM(g.goods_weight * o.goods_number) AS weight, " . + "SUM(o.goods_price * o.goods_number) AS amount ," . + "SUM(o.goods_number) AS number " . + "FROM " . $GLOBALS['ecs']->table('order_goods') . " AS o, " . + $GLOBALS['ecs']->table('goods') . " AS g " . + "WHERE o.order_id = '$order_id' " . + "AND o.goods_id = g.goods_id"; + + $row = $GLOBALS['db']->getRow($sql); + $row['weight'] = floatval($row['weight']); + $row['amount'] = floatval($row['amount']); + $row['number'] = intval($row['number']); + + /* 格式化重量 */ + $row['formated_weight'] = formated_weight($row['weight']); + + return $row; +} + +/** + * 获得订单中的费用信息 + * + * @access public + * @param array $order + * @param array $goods + * @param array $consignee + * @param bool $is_gb_deposit 是否团购保证金(如果是,应付款金额只计算商品总额和支付费用,可以获得的积分取 $gift_integral) + * @return array + */ +function order_fee($order, $goods, $consignee) +{ + /* 初始化订单的扩展code */ + if (!isset($order['extension_code'])) + { + $order['extension_code'] = ''; + } + + if ($order['extension_code'] == 'group_buy') + { + $group_buy = group_buy_info($order['extension_id']); + } + + $total = array('real_goods_count' => 0, + 'gift_amount' => 0, + 'goods_price' => 0, + 'market_price' => 0, + 'discount' => 0, + 'pack_fee' => 0, + 'card_fee' => 0, + 'shipping_fee' => 0, + 'shipping_insure' => 0, + 'integral_money' => 0, + 'bonus' => 0, + 'surplus' => 0, + 'cod_fee' => 0, + 'pay_fee' => 0, + 'tax' => 0); + $weight = 0; + + /* 商品总价 */ + foreach ($goods AS $val) + { + /* 统计实体商品的个数 */ + if ($val['is_real']) + { + $total['real_goods_count']++; + } + + $total['goods_price'] += $val['goods_price'] * $val['goods_number']; + $total['market_price'] += $val['market_price'] * $val['goods_number']; + } + + $total['saving'] = $total['market_price'] - $total['goods_price']; + $total['save_rate'] = $total['market_price'] ? round($total['saving'] * 100 / $total['market_price']) . '%' : 0; + + $total['goods_price_formated'] = price_format($total['goods_price'], false); + $total['market_price_formated'] = price_format($total['market_price'], false); + $total['saving_formated'] = price_format($total['saving'], false); + + /* 折扣 */ + if ($order['extension_code'] != 'group_buy') + { + $discount = compute_discount(); + $total['discount'] = $discount['discount']; + if ($total['discount'] > $total['goods_price']) + { + $total['discount'] = $total['goods_price']; + } + } + $total['discount_formated'] = price_format($total['discount'], false); + + /* 税额 */ + if (!empty($order['need_inv']) && $order['inv_type'] != '') + { + /* 查税率 */ + $rate = 0; + foreach ($GLOBALS['_CFG']['invoice_type']['type'] as $key => $type) + { + if ($type == $order['inv_type']) + { + $rate = floatval($GLOBALS['_CFG']['invoice_type']['rate'][$key]) / 100; + break; + } + } + if ($rate > 0) + { + $total['tax'] = $rate * $total['goods_price']; + } + } + $total['tax_formated'] = price_format($total['tax'], false); + + /* 包装费用 */ + if (!empty($order['pack_id'])) + { + $total['pack_fee'] = pack_fee($order['pack_id'], $total['goods_price']); + } + $total['pack_fee_formated'] = price_format($total['pack_fee'], false); + + /* 贺卡费用 */ + if (!empty($order['card_id'])) + { + $total['card_fee'] = card_fee($order['card_id'], $total['goods_price']); + } + $total['card_fee_formated'] = price_format($total['card_fee'], false); + + /* 红包 */ + + if (!empty($order['bonus_id'])) + { + $bonus = bonus_info($order['bonus_id']); + $total['bonus'] = $bonus['type_money']; + } + $total['bonus_formated'] = price_format($total['bonus'], false); + + /* 线下红包 */ + if (!empty($order['bonus_kill'])) + { + $bonus = bonus_info(0,$order['bonus_kill']); + $total['bonus_kill'] = $order['bonus_kill']; + $total['bonus_kill_formated'] = price_format($total['bonus_kill'], false); + } + + + + /* 配送费用 */ + $shipping_cod_fee = NULL; + + if ($order['shipping_id'] > 0 && $total['real_goods_count'] > 0) + { + $region['country'] = $consignee['country']; + $region['province'] = $consignee['province']; + $region['city'] = $consignee['city']; + $region['district'] = $consignee['district']; + $shipping_info = shipping_area_info($order['shipping_id'], $region); + + if (!empty($shipping_info)) + { + if ($order['extension_code'] == 'group_buy') + { + $weight_price = cart_weight_price(CART_GROUP_BUY_GOODS); + } + else + { + $weight_price = cart_weight_price(); + } + + // 查看购物车中是否全为免运费商品,若是则把运费赋为零 + $sql = 'SELECT count(*) FROM ' . $GLOBALS['ecs']->table('cart') . " WHERE `session_id` = '" . SESS_ID. "' AND `extension_code` != 'package_buy' AND `is_shipping` = 0"; + $shipping_count = $GLOBALS['db']->getOne($sql); + + $total['shipping_fee'] = ($shipping_count == 0 AND $weight_price['free_shipping'] == 1) ?0 : shipping_fee($shipping_info['shipping_code'],$shipping_info['configure'], $weight_price['weight'], $total['goods_price'], $weight_price['number']); + + if (!empty($order['need_insure']) && $shipping_info['insure'] > 0) + { + $total['shipping_insure'] = shipping_insure_fee($shipping_info['shipping_code'], + $total['goods_price'], $shipping_info['insure']); + } + else + { + $total['shipping_insure'] = 0; + } + + if ($shipping_info['support_cod']) + { + $shipping_cod_fee = $shipping_info['pay_fee']; + } + } + } + + $total['shipping_fee_formated'] = price_format($total['shipping_fee'], false); + $total['shipping_insure_formated'] = price_format($total['shipping_insure'], false); + + // 购物车中的商品能享受红包支付的总额 + $bonus_amount = compute_discount_amount(); + // 红包和积分最多能支付的金额为商品总额 + $max_amount = $total['goods_price'] == 0 ? $total['goods_price'] : $total['goods_price'] - $bonus_amount; + + /* 计算订单总额 */ + if ($order['extension_code'] == 'group_buy' && $group_buy['deposit'] > 0) + { + $total['amount'] = $total['goods_price']; + } + else + { + $total['amount'] = $total['goods_price'] - $total['discount'] + $total['tax'] + $total['pack_fee'] + $total['card_fee'] + + $total['shipping_fee'] + $total['shipping_insure'] + $total['cod_fee']; + + // 减去红包金额 + $use_bonus = min($total['bonus'], $max_amount); // 实际减去的红包金额 + if(isset($total['bonus_kill'])) + { + $use_bonus_kill = min($total['bonus_kill'], $max_amount); + $total['amount'] -= $price = number_format($total['bonus_kill'], 2, '.', ''); // 还需要支付的订单金额 + } + + $total['bonus'] = $use_bonus; + $total['bonus_formated'] = price_format($total['bonus'], false); + + $total['amount'] -= $use_bonus; // 还需要支付的订单金额 + $max_amount -= $use_bonus; // 积分最多还能支付的金额 + + } + + /* 余额 */ + $order['surplus'] = $order['surplus'] > 0 ? $order['surplus'] : 0; + if ($total['amount'] > 0) + { + if (isset($order['surplus']) && $order['surplus'] > $total['amount']) + { + $order['surplus'] = $total['amount']; + $total['amount'] = 0; + } + else + { + $total['amount'] -= floatval($order['surplus']); + } + } + else + { + $order['surplus'] = 0; + $total['amount'] = 0; + } + $total['surplus'] = $order['surplus']; + $total['surplus_formated'] = price_format($order['surplus'], false); + + /* 积分 */ + $order['integral'] = $order['integral'] > 0 ? $order['integral'] : 0; + if ($total['amount'] > 0 && $max_amount > 0 && $order['integral'] > 0) + { + $integral_money = value_of_integral($order['integral']); + + // 使用积分支付 + $use_integral = min($total['amount'], $max_amount, $integral_money); // 实际使用积分支付的金额 + $total['amount'] -= $use_integral; + $total['integral_money'] = $use_integral; + $order['integral'] = integral_of_value($use_integral); + } + else + { + $total['integral_money'] = 0; + $order['integral'] = 0; + } + $total['integral'] = $order['integral']; + $total['integral_formated'] = price_format($total['integral_money'], false); + + /* 保存订单信息 */ + $_SESSION['flow_order'] = $order; + + $se_flow_type = isset($_SESSION['flow_type']) ? $_SESSION['flow_type'] : ''; + + /* 支付费用 */ + if (!empty($order['pay_id']) && ($total['real_goods_count'] > 0 || $se_flow_type != CART_EXCHANGE_GOODS)) + { + $total['pay_fee'] = pay_fee($order['pay_id'], $total['amount'], $shipping_cod_fee); + } + + $total['pay_fee_formated'] = price_format($total['pay_fee'], false); + + $total['amount'] += $total['pay_fee']; // 订单总额累加上支付费用 + $total['amount_formated'] = price_format($total['amount'], false); + + /* 取得可以得到的积分和红包 */ + if ($order['extension_code'] == 'group_buy') + { + $total['will_get_integral'] = $group_buy['gift_integral']; + } + elseif ($order['extension_code'] == 'exchange_goods') + { + $total['will_get_integral'] = 0; + } + else + { + $total['will_get_integral'] = get_give_integral($goods); + } + $total['will_get_bonus'] = $order['extension_code'] == 'exchange_goods' ? 0 : price_format(get_total_bonus(), false); + $total['formated_goods_price'] = price_format($total['goods_price'], false); + $total['formated_market_price'] = price_format($total['market_price'], false); + $total['formated_saving'] = price_format($total['saving'], false); + + if ($order['extension_code'] == 'exchange_goods') + { + $sql = 'SELECT SUM(eg.exchange_integral) '. + 'FROM ' . $GLOBALS['ecs']->table('cart') . ' AS c,' . $GLOBALS['ecs']->table('exchange_goods') . 'AS eg '. + "WHERE c.goods_id = eg.goods_id AND c.session_id= '" . SESS_ID . "' " . + " AND c.rec_type = '" . CART_EXCHANGE_GOODS . "' " . + ' AND c.is_gift = 0 AND c.goods_id > 0 ' . + 'GROUP BY eg.goods_id'; + $exchange_integral = $GLOBALS['db']->getOne($sql); + $total['exchange_integral'] = $exchange_integral; + } + + return $total; +} + +/** + * 修改订单 + * @param int $order_id 订单id + * @param array $order key => value + * @return bool + */ +function update_order($order_id, $order) +{ + return $GLOBALS['db']->autoExecute($GLOBALS['ecs']->table('order_info'), + $order, 'UPDATE', "order_id = '$order_id'"); +} + +/** + * 得到新订单号 + * @return string + */ +function get_order_sn() +{ + /* 选择一个随机的方案 */ + mt_srand((double) microtime() * 1000000); + + return date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT); +} + +/** + * 取得购物车商品 + * @param int $type 类型:默认普通商品 + * @return array 购物车商品数组 + */ +function cart_goods($type = CART_GENERAL_GOODS) +{ + $sql = "SELECT rec_id, user_id, goods_id, goods_name, goods_sn, goods_number, " . + "market_price, goods_price, goods_attr, is_real, extension_code, parent_id, is_gift, is_shipping, " . + "goods_price * goods_number AS subtotal " . + "FROM " . $GLOBALS['ecs']->table('cart') . + " WHERE session_id = '" . SESS_ID . "' " . + "AND rec_type = '$type'"; + + $arr = $GLOBALS['db']->getAll($sql); + + /* 格式化价格及礼包商品 */ + foreach ($arr as $key => $value) + { + $arr[$key]['formated_market_price'] = price_format($value['market_price'], false); + $arr[$key]['formated_goods_price'] = price_format($value['goods_price'], false); + $arr[$key]['formated_subtotal'] = price_format($value['subtotal'], false); + + if ($value['extension_code'] == 'package_buy') + { + $arr[$key]['package_goods_list'] = get_package_goods($value['goods_id']); + } + } + + return $arr; +} + +/** + * 取得购物车总金额 + * @params boolean $include_gift 是否包括赠品 + * @param int $type 类型:默认普通商品 + * @return float 购物车总金额 + */ +function cart_amount($include_gift = true, $type = CART_GENERAL_GOODS) +{ + $sql = "SELECT SUM(goods_price * goods_number) " . + " FROM " . $GLOBALS['ecs']->table('cart') . + " WHERE session_id = '" . SESS_ID . "' " . + "AND rec_type = '$type' "; + + if (!$include_gift) + { + $sql .= ' AND is_gift = 0 AND goods_id > 0'; + } + + return floatval($GLOBALS['db']->getOne($sql)); +} + +/** + * 检查某商品是否已经存在于购物车 + * + * @access public + * @param integer $id + * @param array $spec + * @param int $type 类型:默认普通商品 + * @return boolean + */ +function cart_goods_exists($id, $spec, $type = CART_GENERAL_GOODS) +{ + /* 检查该商品是否已经存在在购物车中 */ + $sql = "SELECT COUNT(*) FROM " .$GLOBALS['ecs']->table('cart'). + "WHERE session_id = '" .SESS_ID. "' AND goods_id = '$id' ". + "AND parent_id = 0 AND goods_attr = '" .get_goods_attr_info($spec). "' " . + "AND rec_type = '$type'"; + + return ($GLOBALS['db']->getOne($sql) > 0); +} + +/** + * 获得购物车中商品的总重量、总价格、总数量 + * + * @access public + * @param int $type 类型:默认普通商品 + * @return array + */ +function cart_weight_price($type = CART_GENERAL_GOODS) +{ + $package_row['weight'] = 0; + $package_row['amount'] = 0; + $package_row['number'] = 0; + + $packages_row['free_shipping'] = 1; + + /* 计算超值礼包内商品的相关配送参数 */ + $sql = 'SELECT goods_id, goods_number, goods_price FROM ' . $GLOBALS['ecs']->table('cart') . " WHERE extension_code = 'package_buy' AND session_id = '" . SESS_ID . "'"; + $row = $GLOBALS['db']->getAll($sql); + + if ($row) + { + $packages_row['free_shipping'] = 0; + $free_shipping_count = 0; + + foreach ($row as $val) + { + // 如果商品全为免运费商品,设置一个标识变量 + $sql = 'SELECT count(*) FROM ' . + $GLOBALS['ecs']->table('package_goods') . ' AS pg, ' . + $GLOBALS['ecs']->table('goods') . ' AS g ' . + "WHERE g.goods_id = pg.goods_id AND g.is_shipping = 0 AND pg.package_id = '" . $val['goods_id'] . "'"; + $shipping_count = $GLOBALS['db']->getOne($sql); + + if ($shipping_count > 0) + { + // 循环计算每个超值礼包商品的重量和数量,注意一个礼包中可能包换若干个同一商品 + $sql = 'SELECT SUM(g.goods_weight * pg.goods_number) AS weight, ' . + 'SUM(pg.goods_number) AS number FROM ' . + $GLOBALS['ecs']->table('package_goods') . ' AS pg, ' . + $GLOBALS['ecs']->table('goods') . ' AS g ' . + "WHERE g.goods_id = pg.goods_id AND g.is_shipping = 0 AND pg.package_id = '" . $val['goods_id'] . "'"; + + $goods_row = $GLOBALS['db']->getRow($sql); + $package_row['weight'] += floatval($goods_row['weight']) * $val['goods_number']; + $package_row['amount'] += floatval($val['goods_price']) * $val['goods_number']; + $package_row['number'] += intval($goods_row['number']) * $val['goods_number']; + } + else + { + $free_shipping_count++; + } + } + + $packages_row['free_shipping'] = $free_shipping_count == count($row) ? 1 : 0; + } + + /* 获得购物车中非超值礼包商品的总重量 */ + $sql = 'SELECT SUM(g.goods_weight * c.goods_number) AS weight, ' . + 'SUM(c.goods_price * c.goods_number) AS amount, ' . + 'SUM(c.goods_number) AS number '. + 'FROM ' . $GLOBALS['ecs']->table('cart') . ' AS c '. + 'LEFT JOIN ' . $GLOBALS['ecs']->table('goods') . ' AS g ON g.goods_id = c.goods_id '. + "WHERE c.session_id = '" . SESS_ID . "' " . + "AND rec_type = '$type' AND g.is_shipping = 0 AND c.extension_code != 'package_buy'"; + $row = $GLOBALS['db']->getRow($sql); + + $packages_row['weight'] = floatval($row['weight']) + $package_row['weight']; + $packages_row['amount'] = floatval($row['amount']) + $package_row['amount']; + $packages_row['number'] = intval($row['number']) + $package_row['number']; + /* 格式化重量 */ + $packages_row['formated_weight'] = formated_weight($packages_row['weight']); + + return $packages_row; +} + +/** + * 添加商品到购物车 + * + * @access public + * @param integer $goods_id 商品编号 + * @param integer $num 商品数量 + * @param array $spec 规格值对应的id数组 + * @param integer $parent 基本件 + * @return boolean + */ +function addto_cart($goods_id, $num = 1, $spec = array(), $parent = 0) +{ + $GLOBALS['err']->clean(); + $_parent_id = $parent; + + /* 取得商品信息 */ + $sql = "SELECT g.goods_name, g.goods_sn, g.is_on_sale, g.is_real, ". + "g.market_price, g.shop_price AS org_price, g.promote_price, g.promote_start_date, ". + "g.promote_end_date, g.goods_weight, g.integral, g.extension_code, ". + "g.goods_number, g.is_alone_sale, g.is_shipping,". + "IFNULL(mp.user_price, g.shop_price * '$_SESSION[discount]') AS shop_price ". + " FROM " .$GLOBALS['ecs']->table('goods'). " AS g ". + " LEFT JOIN " . $GLOBALS['ecs']->table('member_price') . " AS mp ". + "ON mp.goods_id = g.goods_id AND mp.user_rank = '$_SESSION[user_rank]' ". + " WHERE g.goods_id = '$goods_id'" . + " AND g.is_delete = 0"; + $goods = $GLOBALS['db']->getRow($sql); + + if (empty($goods)) + { + $GLOBALS['err']->add($GLOBALS['_LANG']['goods_not_exists'], ERR_NOT_EXISTS); + + return false; + } + + /* 如果是作为配件添加到购物车的,需要先检查购物车里面是否已经有基本件 */ + if ($parent > 0) + { + $sql = "SELECT COUNT(*) FROM " . $GLOBALS['ecs']->table('cart') . + " WHERE goods_id='$parent' AND session_id='" . SESS_ID . "' AND extension_code <> 'package_buy'"; + if ($GLOBALS['db']->getOne($sql) == 0) + { + $GLOBALS['err']->add($GLOBALS['_LANG']['no_basic_goods'], ERR_NO_BASIC_GOODS); + + return false; + } + } + + /* 是否正在销售 */ + if ($goods['is_on_sale'] == 0) + { + $GLOBALS['err']->add($GLOBALS['_LANG']['not_on_sale'], ERR_NOT_ON_SALE); + + return false; + } + + /* 不是配件时检查是否允许单独销售 */ + if (empty($parent) && $goods['is_alone_sale'] == 0) + { + $GLOBALS['err']->add($GLOBALS['_LANG']['cannt_alone_sale'], ERR_CANNT_ALONE_SALE); + + return false; + } + + /* 如果商品有规格则取规格商品信息 配件除外 */ + $sql = "SELECT * FROM " .$GLOBALS['ecs']->table('products'). " WHERE goods_id = '$goods_id' LIMIT 0, 1"; + $prod = $GLOBALS['db']->getRow($sql); + + if (is_spec($spec) && !empty($prod)) + { + $product_info = get_products_info($goods_id, $spec); + } + if (empty($product_info)) + { + $product_info = array('product_number' => '', 'product_id' => 0); + } + + /* 检查:库存 */ + if ($GLOBALS['_CFG']['use_storage'] == 1) + { + //检查:商品购买数量是否大于总库存 + if ($num > $goods['goods_number']) + { + $GLOBALS['err']->add(sprintf($GLOBALS['_LANG']['shortage'], $goods['goods_number']), ERR_OUT_OF_STOCK); + + return false; + } + + //商品存在规格 是货品 检查该货品库存 + if (is_spec($spec) && !empty($prod)) + { + if (!empty($spec)) + { + /* 取规格的货品库存 */ + if ($num > $product_info['product_number']) + { + $GLOBALS['err']->add(sprintf($GLOBALS['_LANG']['shortage'], $product_info['product_number']), ERR_OUT_OF_STOCK); + + return false; + } + } + } + } + + /* 计算商品的促销价格 */ + $spec_price = spec_price($spec); + $goods_price = get_final_price($goods_id, $num, true, $spec); + $goods['market_price'] += $spec_price; + $goods_attr = get_goods_attr_info($spec); + $goods_attr_id = join(',', $spec); + + /* 初始化要插入购物车的基本件数据 */ + $parent = array( + 'user_id' => $_SESSION['user_id'], + 'session_id' => SESS_ID, + 'goods_id' => $goods_id, + 'goods_sn' => addslashes($goods['goods_sn']), + 'product_id' => $product_info['product_id'], + 'goods_name' => addslashes($goods['goods_name']), + 'market_price' => $goods['market_price'], + 'goods_attr' => addslashes($goods_attr), + 'goods_attr_id' => $goods_attr_id, + 'is_real' => $goods['is_real'], + 'extension_code'=> $goods['extension_code'], + 'is_gift' => 0, + 'is_shipping' => $goods['is_shipping'], + 'rec_type' => CART_GENERAL_GOODS + ); + + /* 如果该配件在添加为基本件的配件时,所设置的“配件价格”比原价低,即此配件在价格上提供了优惠, */ + /* 则按照该配件的优惠价格卖,但是每一个基本件只能购买一个优惠价格的“该配件”,多买的“该配件”不享 */ + /* 受此优惠 */ + $basic_list = array(); + $sql = "SELECT parent_id, goods_price " . + "FROM " . $GLOBALS['ecs']->table('group_goods') . + " WHERE goods_id = '$goods_id'" . + " AND goods_price < '$goods_price'" . + " AND parent_id = '$_parent_id'" . + " ORDER BY goods_price"; + $res = $GLOBALS['db']->query($sql); + while ($row = $GLOBALS['db']->fetchRow($res)) + { + $basic_list[$row['parent_id']] = $row['goods_price']; + } + + /* 取得购物车中该商品每个基本件的数量 */ + $basic_count_list = array(); + if ($basic_list) + { + $sql = "SELECT goods_id, SUM(goods_number) AS count " . + "FROM " . $GLOBALS['ecs']->table('cart') . + " WHERE session_id = '" . SESS_ID . "'" . + " AND parent_id = 0" . + " AND extension_code <> 'package_buy' " . + " AND goods_id " . db_create_in(array_keys($basic_list)) . + " GROUP BY goods_id"; + $res = $GLOBALS['db']->query($sql); + while ($row = $GLOBALS['db']->fetchRow($res)) + { + $basic_count_list[$row['goods_id']] = $row['count']; + } + } + + /* 取得购物车中该商品每个基本件已有该商品配件数量,计算出每个基本件还能有几个该商品配件 */ + /* 一个基本件对应一个该商品配件 */ + if ($basic_count_list) + { + $sql = "SELECT parent_id, SUM(goods_number) AS count " . + "FROM " . $GLOBALS['ecs']->table('cart') . + " WHERE session_id = '" . SESS_ID . "'" . + " AND goods_id = '$goods_id'" . + " AND extension_code <> 'package_buy' " . + " AND parent_id " . db_create_in(array_keys($basic_count_list)) . + " GROUP BY parent_id"; + $res = $GLOBALS['db']->query($sql); + while ($row = $GLOBALS['db']->fetchRow($res)) + { + $basic_count_list[$row['parent_id']] -= $row['count']; + } + } + + /* 循环插入配件 如果是配件则用其添加数量依次为购物车中所有属于其的基本件添加足够数量的该配件 */ + foreach ($basic_list as $parent_id => $fitting_price) + { + /* 如果已全部插入,退出 */ + if ($num <= 0) + { + break; + } + + /* 如果该基本件不再购物车中,执行下一个 */ + if (!isset($basic_count_list[$parent_id])) + { + continue; + } + + /* 如果该基本件的配件数量已满,执行下一个基本件 */ + if ($basic_count_list[$parent_id] <= 0) + { + continue; + } + + /* 作为该基本件的配件插入 */ + $parent['goods_price'] = max($fitting_price, 0) + $spec_price; //允许该配件优惠价格为0 + $parent['goods_number'] = min($num, $basic_count_list[$parent_id]); + $parent['parent_id'] = $parent_id; + + /* 添加 */ + $GLOBALS['db']->autoExecute($GLOBALS['ecs']->table('cart'), $parent, 'INSERT'); + + /* 改变数量 */ + $num -= $parent['goods_number']; + } + + /* 如果数量不为0,作为基本件插入 */ + if ($num > 0) + { + /* 检查该商品是否已经存在在购物车中 */ + $sql = "SELECT goods_number FROM " .$GLOBALS['ecs']->table('cart'). + " WHERE session_id = '" .SESS_ID. "' AND goods_id = '$goods_id' ". + " AND parent_id = 0 AND goods_attr = '" .get_goods_attr_info($spec). "' " . + " AND extension_code <> 'package_buy' " . + " AND rec_type = 'CART_GENERAL_GOODS'"; + + $row = $GLOBALS['db']->getRow($sql); + + if($row) //如果购物车已经有此物品,则更新 + { + $num += $row['goods_number']; + if(is_spec($spec) && !empty($prod) ) + { + $goods_storage=$product_info['product_number']; + } + else + { + $goods_storage=$goods['goods_number']; + } + if ($GLOBALS['_CFG']['use_storage'] == 0 || $num <= $goods_storage) + { + $goods_price = get_final_price($goods_id, $num, true, $spec); + $sql = "UPDATE " . $GLOBALS['ecs']->table('cart') . " SET goods_number = '$num'" . + " , goods_price = '$goods_price'". + " WHERE session_id = '" .SESS_ID. "' AND goods_id = '$goods_id' ". + " AND parent_id = 0 AND goods_attr = '" .get_goods_attr_info($spec). "' " . + " AND extension_code <> 'package_buy' " . + "AND rec_type = 'CART_GENERAL_GOODS'"; + $GLOBALS['db']->query($sql); + } + else + { + $GLOBALS['err']->add(sprintf($GLOBALS['_LANG']['shortage'], $num), ERR_OUT_OF_STOCK); + + return false; + } + } + else //购物车没有此物品,则插入 + { + $goods_price = get_final_price($goods_id, $num, true, $spec); + $parent['goods_price'] = max($goods_price, 0); + $parent['goods_number'] = $num; + $parent['parent_id'] = 0; + $GLOBALS['db']->autoExecute($GLOBALS['ecs']->table('cart'), $parent, 'INSERT'); + } + } + + /* 把赠品删除 */ + $sql = "DELETE FROM " . $GLOBALS['ecs']->table('cart') . " WHERE session_id = '" . SESS_ID . "' AND is_gift <> 0"; + $GLOBALS['db']->query($sql); + + return true; +} + +/** + * 清空购物车 + * @param int $type 类型:默认普通商品 + */ +function clear_cart($type = CART_GENERAL_GOODS) +{ + $sql = "DELETE FROM " . $GLOBALS['ecs']->table('cart') . + " WHERE session_id = '" . SESS_ID . "' AND rec_type = '$type'"; + $GLOBALS['db']->query($sql); +} + +/** + * 获得指定的商品属性 + * + * @access public + * @param array $arr 规格、属性ID数组 + * @param type $type 设置返回结果类型:pice,显示价格,默认;no,不显示价格 + * + * @return string + */ +function get_goods_attr_info($arr, $type = 'pice') +{ + $attr = ''; + + if (!empty($arr)) + { + $fmt = "%s:%s[%s] \n"; + + $sql = "SELECT a.attr_name, ga.attr_value, ga.attr_price ". + "FROM ".$GLOBALS['ecs']->table('goods_attr')." AS ga, ". + $GLOBALS['ecs']->table('attribute')." AS a ". + "WHERE " .db_create_in($arr, 'ga.goods_attr_id')." AND a.attr_id = ga.attr_id"; + $res = $GLOBALS['db']->query($sql); + + while ($row = $GLOBALS['db']->fetchRow($res)) + { + $attr_price = round(floatval($row['attr_price']), 2); + $attr .= sprintf($fmt, $row['attr_name'], $row['attr_value'], $attr_price); + } + + $attr = str_replace('[0]', '', $attr); + } + + return $attr; +} + +/** + * 取得用户信息 + * @param int $user_id 用户id + * @return array 用户信息 + */ +function user_info($user_id) +{ + $sql = "SELECT * FROM " . $GLOBALS['ecs']->table('users') . + " WHERE user_id = '$user_id'"; + $user = $GLOBALS['db']->getRow($sql); + + unset($user['question']); + unset($user['answer']); + + /* 格式化帐户余额 */ + if ($user) + { +// if ($user['user_money'] < 0) +// { +// $user['user_money'] = 0; +// } + $user['formated_user_money'] = price_format($user['user_money'], false); + $user['formated_frozen_money'] = price_format($user['frozen_money'], false); + } + + return $user; +} + +/** + * 修改用户 + * @param int $user_id 订单id + * @param array $user key => value + * @return bool + */ +function update_user($user_id, $user) +{ + return $GLOBALS['db']->autoExecute($GLOBALS['ecs']->table('users'), + $user, 'UPDATE', "user_id = '$user_id'"); +} + +/** + * 取得用户地址列表 + * @param int $user_id 用户id + * @return array + */ +function address_list($user_id) +{ + $sql = "SELECT * FROM " . $GLOBALS['ecs']->table('user_address') . + " WHERE user_id = '$user_id'"; + + return $GLOBALS['db']->getAll($sql); +} + +/** + * 取得用户地址信息 + * @param int $address_id 地址id + * @return array + */ +function address_info($address_id) +{ + $sql = "SELECT * FROM " . $GLOBALS['ecs']->table('user_address') . + " WHERE address_id = '$address_id'"; + + return $GLOBALS['db']->getRow($sql); +} + +/** + * 取得用户当前可用红包 + * @param int $user_id 用户id + * @param float $goods_amount 订单商品金额 + * @return array 红包数组 + */ +function user_bonus($user_id, $goods_amount = 0) +{ + $day = getdate(); + $today = local_mktime(23, 59, 59, $day['mon'], $day['mday'], $day['year']); + + $sql = "SELECT t.type_id, t.type_name, t.type_money, b.bonus_id " . + "FROM " . $GLOBALS['ecs']->table('bonus_type') . " AS t," . + $GLOBALS['ecs']->table('user_bonus') . " AS b " . + "WHERE t.type_id = b.bonus_type_id " . + "AND t.use_start_date <= '$today' " . + "AND t.use_end_date >= '$today' " . + "AND t.min_goods_amount <= '$goods_amount' " . + "AND b.user_id<>0 " . + "AND b.user_id = '$user_id' " . + "AND b.order_id = 0"; + return $GLOBALS['db']->getAll($sql); +} + +/** + * 取得红包信息 + * @param int $bonus_id 红包id + * @param string $bonus_sn 红包序列号 + * @param array 红包信息 + */ +function bonus_info($bonus_id, $bonus_sn = '') +{ + $sql = "SELECT t.*, b.* " . + "FROM " . $GLOBALS['ecs']->table('bonus_type') . " AS t," . + $GLOBALS['ecs']->table('user_bonus') . " AS b " . + "WHERE t.type_id = b.bonus_type_id "; + if ($bonus_id > 0) + { + $sql .= "AND b.bonus_id = '$bonus_id'"; + } + else + { + $sql .= "AND b.bonus_sn = '$bonus_sn'"; + } + + return $GLOBALS['db']->getRow($sql); +} + +/** + * 检查红包是否已使用 + * @param int $bonus_id 红包id + * @return bool + */ +function bonus_used($bonus_id) +{ + $sql = "SELECT order_id FROM " . $GLOBALS['ecs']->table('user_bonus') . + " WHERE bonus_id = '$bonus_id'"; + + return $GLOBALS['db']->getOne($sql) > 0; +} + +/** + * 设置红包为已使用 + * @param int $bonus_id 红包id + * @param int $order_id 订单id + * @return bool + */ +function use_bonus($bonus_id, $order_id) +{ + $sql = "UPDATE " . $GLOBALS['ecs']->table('user_bonus') . + " SET order_id = '$order_id', used_time = '" . gmtime() . "' " . + "WHERE bonus_id = '$bonus_id' LIMIT 1"; + + return $GLOBALS['db']->query($sql); +} + +/** + * 设置红包为未使用 + * @param int $bonus_id 红包id + * @param int $order_id 订单id + * @return bool + */ +function unuse_bonus($bonus_id) +{ + $sql = "UPDATE " . $GLOBALS['ecs']->table('user_bonus') . + " SET order_id = 0, used_time = 0 " . + "WHERE bonus_id = '$bonus_id' LIMIT 1"; + + return $GLOBALS['db']->query($sql); +} + +/** + * 计算积分的价值(能抵多少钱) + * @param int $integral 积分 + * @return float 积分价值 + */ +function value_of_integral($integral) +{ + $scale = floatval($GLOBALS['_CFG']['integral_scale']); + + return $scale > 0 ? round(($integral / 100) * $scale, 2) : 0; +} + +/** + * 计算指定的金额需要多少积分 + * + * @access public + * @param integer $value 金额 + * @return void + */ +function integral_of_value($value) +{ + $scale = floatval($GLOBALS['_CFG']['integral_scale']); + + return $scale > 0 ? round($value / $scale * 100) : 0; +} + +/** + * 订单退款 + * @param array $order 订单 + * @param int $refund_type 退款方式 1 到帐户余额 2 到退款申请(先到余额,再申请提款) 3 不处理 + * @param string $refund_note 退款说明 + * @param float $refund_amount 退款金额(如果为0,取订单已付款金额) + * @return bool + */ +function order_refund($order, $refund_type, $refund_note, $refund_amount = 0) +{ + /* 检查参数 */ + $user_id = $order['user_id']; + if ($user_id == 0 && $refund_type == 1) + { + die('anonymous, cannot return to account balance'); + } + + $amount = $refund_amount > 0 ? $refund_amount : $order['money_paid']; + if ($amount <= 0) + { + return true; + } + + if (!in_array($refund_type, array(1, 2, 3))) + { + die('invalid params'); + } + + /* 备注信息 */ + if ($refund_note) + { + $change_desc = $refund_note; + } + else + { + include_once(ROOT_PATH . 'languages/' .$GLOBALS['_CFG']['lang']. '/admin/order.php'); + $change_desc = sprintf($GLOBALS['_LANG']['order_refund'], $order['order_sn']); + } + + /* 处理退款 */ + if (1 == $refund_type) + { + log_account_change($user_id, $amount, 0, 0, 0, $change_desc); + + return true; + } + elseif (2 == $refund_type) + { + /* 如果非匿名,退回余额 */ + if ($user_id > 0) + { + log_account_change($user_id, $amount, 0, 0, 0, $change_desc); + } + + /* user_account 表增加提款申请记录 */ + $account = array( + 'user_id' => $user_id, + 'amount' => (-1) * $amount, + 'add_time' => gmtime(), + 'user_note' => $refund_note, + 'process_type' => SURPLUS_RETURN, + 'admin_user' => $_SESSION['admin_name'], + 'admin_note' => sprintf($GLOBALS['_LANG']['order_refund'], $order['order_sn']), + 'is_paid' => 0 + ); + $GLOBALS['db']->autoExecute($GLOBALS['ecs']->table('user_account'), $account, 'INSERT'); + + return true; + } + else + { + return true; + } +} + +/** + * 获得购物车中的商品 + * + * @access public + * @return array + */ +function get_cart_goods() +{ + /* 初始化 */ + $goods_list = array(); + $total = array( + 'goods_price' => 0, // 本店售价合计(有格式) + 'market_price' => 0, // 市场售价合计(有格式) + 'saving' => 0, // 节省金额(有格式) + 'save_rate' => 0, // 节省百分比 + 'goods_amount' => 0, // 本店售价合计(无格式) + ); + + /* 循环、统计 */ + $sql = "SELECT *, IF(parent_id, parent_id, goods_id) AS pid " . + " FROM " . $GLOBALS['ecs']->table('cart') . " " . + " WHERE session_id = '" . SESS_ID . "' AND rec_type = '" . CART_GENERAL_GOODS . "'" . + " ORDER BY pid, parent_id"; + $res = $GLOBALS['db']->query($sql); + + /* 用于统计购物车中实体商品和虚拟商品的个数 */ + $virtual_goods_count = 0; + $real_goods_count = 0; + + while ($row = $GLOBALS['db']->fetchRow($res)) + { + $total['goods_price'] += $row['goods_price'] * $row['goods_number']; + $total['market_price'] += $row['market_price'] * $row['goods_number']; + + $row['subtotal'] = price_format($row['goods_price'] * $row['goods_number'], false); + $row['goods_price'] = price_format($row['goods_price'], false); + $row['market_price'] = price_format($row['market_price'], false); + + /* 统计实体商品和虚拟商品的个数 */ + if ($row['is_real']) + { + $real_goods_count++; + } + else + { + $virtual_goods_count++; + } + + /* 查询规格 */ + if (trim($row['goods_attr']) != '') + { + $sql = "SELECT attr_value FROM " . $GLOBALS['ecs']->table('goods_attr') . " WHERE goods_attr_id " . + db_create_in($row['goods_attr']); + $attr_list = $GLOBALS['db']->getCol($sql); + foreach ($attr_list AS $attr) + { + $row['goods_name'] .= ' [' . $attr . '] '; + } + } + /* 增加是否在购物车里显示商品图 */ + if (($GLOBALS['_CFG']['show_goods_in_cart'] == "2" || $GLOBALS['_CFG']['show_goods_in_cart'] == "3") && $row['extension_code'] != 'package_buy') + { + $goods_thumb = $GLOBALS['db']->getOne("SELECT `goods_thumb` FROM " . $GLOBALS['ecs']->table('goods') . " WHERE `goods_id`='{$row['goods_id']}'"); + $row['goods_thumb'] = get_image_path($row['goods_id'], $goods_thumb, true); + } + if ($row['extension_code'] == 'package_buy') + { + $row['package_goods_list'] = get_package_goods($row['goods_id']); + } + $goods_list[] = $row; + } + $total['goods_amount'] = $total['goods_price']; + $total['saving'] = price_format($total['market_price'] - $total['goods_price'], false); + if ($total['market_price'] > 0) + { + $total['save_rate'] = $total['market_price'] ? round(($total['market_price'] - $total['goods_price']) * + 100 / $total['market_price']).'%' : 0; + } + $total['goods_price'] = price_format($total['goods_price'], false); + $total['market_price'] = price_format($total['market_price'], false); + $total['real_goods_count'] = $real_goods_count; + $total['virtual_goods_count'] = $virtual_goods_count; + + return array('goods_list' => $goods_list, 'total' => $total); +} + +/** + * 取得收货人信息 + * @param int $user_id 用户编号 + * @return array + */ +function get_consignee($user_id) +{ + if (isset($_SESSION['flow_consignee'])) + { + /* 如果存在session,则直接返回session中的收货人信息 */ + + return $_SESSION['flow_consignee']; + } + else + { + /* 如果不存在,则取得用户的默认收货人信息 */ + $arr = array(); + + if ($user_id > 0) + { + /* 取默认地址 */ + $sql = "SELECT ua.*". + " FROM " . $GLOBALS['ecs']->table('user_address') . "AS ua, ".$GLOBALS['ecs']->table('users').' AS u '. + " WHERE u.user_id='$user_id' AND ua.address_id = u.address_id"; + + $arr = $GLOBALS['db']->getRow($sql); + } + + return $arr; + } +} + +/** + * 查询购物车(订单id为0)或订单中是否有实体商品 + * @param int $order_id 订单id + * @param int $flow_type 购物流程类型 + * @return bool + */ +function exist_real_goods($order_id = 0, $flow_type = CART_GENERAL_GOODS) +{ + if ($order_id <= 0) + { + $sql = "SELECT COUNT(*) FROM " . $GLOBALS['ecs']->table('cart') . + " WHERE session_id = '" . SESS_ID . "' AND is_real = 1 " . + "AND rec_type = '$flow_type'"; + } + else + { + $sql = "SELECT COUNT(*) FROM " . $GLOBALS['ecs']->table('order_goods') . + " WHERE order_id = '$order_id' AND is_real = 1"; + } + + return $GLOBALS['db']->getOne($sql) > 0; +} + +/** + * 检查收货人信息是否完整 + * @param array $consignee 收货人信息 + * @param int $flow_type 购物流程类型 + * @return bool true 完整 false 不完整 + */ +function check_consignee_info($consignee, $flow_type) +{ + if (exist_real_goods(0, $flow_type)) + { + /* 如果存在实体商品 */ + $res = !empty($consignee['consignee']) && + !empty($consignee['country']) && + !empty($consignee['email']) && + !empty($consignee['tel']); + + if ($res) + { + if (empty($consignee['province'])) + { + /* 没有设置省份,检查当前国家下面有没有设置省份 */ + $pro = get_regions(1, $consignee['country']); + $res = empty($pro); + } + elseif (empty($consignee['city'])) + { + /* 没有设置城市,检查当前省下面有没有城市 */ + $city = get_regions(2, $consignee['province']); + $res = empty($city); + } + elseif (empty($consignee['district'])) + { + $dist = get_regions(3, $consignee['city']); + $res = empty($dist); + } + } + + return $res; + } + else + { + /* 如果不存在实体商品 */ + return !empty($consignee['consignee']) && + !empty($consignee['email']) && + !empty($consignee['tel']); + } +} + +/** + * 获得上一次用户采用的支付和配送方式 + * + * @access public + * @return void + */ +function last_shipping_and_payment() +{ + $sql = "SELECT shipping_id, pay_id " . + " FROM " . $GLOBALS['ecs']->table('order_info') . + " WHERE user_id = '$_SESSION[user_id]' " . + " ORDER BY order_id DESC LIMIT 1"; + $row = $GLOBALS['db']->getRow($sql); + + if (empty($row)) + { + /* 如果获得是一个空数组,则返回默认值 */ + $row = array('shipping_id' => 0, 'pay_id' => 0); + } + + return $row; +} + +/** + * 取得当前用户应该得到的红包总额 + */ +function get_total_bonus() +{ + $day = getdate(); + $today = local_mktime(23, 59, 59, $day['mon'], $day['mday'], $day['year']); + + /* 按商品发的红包 */ + $sql = "SELECT SUM(c.goods_number * t.type_money)" . + "FROM " . $GLOBALS['ecs']->table('cart') . " AS c, " + . $GLOBALS['ecs']->table('bonus_type') . " AS t, " + . $GLOBALS['ecs']->table('goods') . " AS g " . + "WHERE c.session_id = '" . SESS_ID . "' " . + "AND c.is_gift = 0 " . + "AND c.goods_id = g.goods_id " . + "AND g.bonus_type_id = t.type_id " . + "AND t.send_type = '" . SEND_BY_GOODS . "' " . + "AND t.send_start_date <= '$today' " . + "AND t.send_end_date >= '$today' " . + "AND c.rec_type = '" . CART_GENERAL_GOODS . "'"; + $goods_total = floatval($GLOBALS['db']->getOne($sql)); + + /* 取得购物车中非赠品总金额 */ + $sql = "SELECT SUM(goods_price * goods_number) " . + "FROM " . $GLOBALS['ecs']->table('cart') . + " WHERE session_id = '" . SESS_ID . "' " . + " AND is_gift = 0 " . + " AND rec_type = '" . CART_GENERAL_GOODS . "'"; + $amount = floatval($GLOBALS['db']->getOne($sql)); + + /* 按订单发的红包 */ + $sql = "SELECT FLOOR('$amount' / min_amount) * type_money " . + "FROM " . $GLOBALS['ecs']->table('bonus_type') . + " WHERE send_type = '" . SEND_BY_ORDER . "' " . + " AND send_start_date <= '$today' " . + "AND send_end_date >= '$today' " . + "AND min_amount > 0 "; + $order_total = floatval($GLOBALS['db']->getOne($sql)); + + return $goods_total + $order_total; +} + +/** + * 处理红包(下订单时设为使用,取消(无效,退货)订单时设为未使用 + * @param int $bonus_id 红包编号 + * @param int $order_id 订单号 + * @param int $is_used 是否使用了 + */ +function change_user_bonus($bonus_id, $order_id, $is_used = true) +{ + if ($is_used) + { + $sql = 'UPDATE ' . $GLOBALS['ecs']->table('user_bonus') . ' SET ' . + 'used_time = ' . gmtime() . ', ' . + "order_id = '$order_id' " . + "WHERE bonus_id = '$bonus_id'"; + } + else + { + $sql = 'UPDATE ' . $GLOBALS['ecs']->table('user_bonus') . ' SET ' . + 'used_time = 0, ' . + 'order_id = 0 ' . + "WHERE bonus_id = '$bonus_id'"; + } + $GLOBALS['db']->query($sql); +} + +/** + * 获得订单信息 + * + * @access private + * @return array + */ +function flow_order_info() +{ + $order = isset($_SESSION['flow_order']) ? $_SESSION['flow_order'] : array(); + + /* 初始化配送和支付方式 */ + if (!isset($order['shipping_id']) || !isset($order['pay_id'])) + { + /* 如果还没有设置配送和支付 */ + if ($_SESSION['user_id'] > 0) + { + /* 用户已经登录了,则获得上次使用的配送和支付 */ + $arr = last_shipping_and_payment(); + + if (!isset($order['shipping_id'])) + { + $order['shipping_id'] = $arr['shipping_id']; + } + if (!isset($order['pay_id'])) + { + $order['pay_id'] = $arr['pay_id']; + } + } + else + { + if (!isset($order['shipping_id'])) + { + $order['shipping_id'] = 0; + } + if (!isset($order['pay_id'])) + { + $order['pay_id'] = 0; + } + } + } + + if (!isset($order['pack_id'])) + { + $order['pack_id'] = 0; // 初始化包装 + } + if (!isset($order['card_id'])) + { + $order['card_id'] = 0; // 初始化贺卡 + } + if (!isset($order['bonus'])) + { + $order['bonus'] = 0; // 初始化红包 + } + if (!isset($order['integral'])) + { + $order['integral'] = 0; // 初始化积分 + } + if (!isset($order['surplus'])) + { + $order['surplus'] = 0; // 初始化余额 + } + + /* 扩展信息 */ + if (isset($_SESSION['flow_type']) && intval($_SESSION['flow_type']) != CART_GENERAL_GOODS) + { + $order['extension_code'] = $_SESSION['extension_code']; + $order['extension_id'] = $_SESSION['extension_id']; + } + + return $order; +} + +/** + * 合并订单 + * @param string $from_order_sn 从订单号 + * @param string $to_order_sn 主订单号 + * @return 成功返回true,失败返回错误信息 + */ +function merge_order($from_order_sn, $to_order_sn) +{ + /* 订单号不能为空 */ + if (trim($from_order_sn) == '' || trim($to_order_sn) == '') + { + return $GLOBALS['_LANG']['order_sn_not_null']; + } + + /* 订单号不能相同 */ + if ($from_order_sn == $to_order_sn) + { + return $GLOBALS['_LANG']['two_order_sn_same']; + } + + /* 取得订单信息 */ + $from_order = order_info(0, $from_order_sn); + $to_order = order_info(0, $to_order_sn); + + /* 检查订单是否存在 */ + if (!$from_order) + { + return sprintf($GLOBALS['_LANG']['order_not_exist'], $from_order_sn); + } + elseif (!$to_order) + { + return sprintf($GLOBALS['_LANG']['order_not_exist'], $to_order_sn); + } + + /* 检查合并的订单是否为普通订单,非普通订单不允许合并 */ + if ($from_order['extension_code'] != '' || $to_order['extension_code'] != 0) + { + return $GLOBALS['_LANG']['merge_invalid_order']; + } + + /* 检查订单状态是否是已确认或未确认、未付款、未发货 */ + if ($from_order['order_status'] != OS_UNCONFIRMED && $from_order['order_status'] != OS_CONFIRMED) + { + return sprintf($GLOBALS['_LANG']['os_not_unconfirmed_or_confirmed'], $from_order_sn); + } + elseif ($from_order['pay_status'] != PS_UNPAYED) + { + return sprintf($GLOBALS['_LANG']['ps_not_unpayed'], $from_order_sn); + } + elseif ($from_order['shipping_status'] != SS_UNSHIPPED) + { + return sprintf($GLOBALS['_LANG']['ss_not_unshipped'], $from_order_sn); + } + + if ($to_order['order_status'] != OS_UNCONFIRMED && $to_order['order_status'] != OS_CONFIRMED) + { + return sprintf($GLOBALS['_LANG']['os_not_unconfirmed_or_confirmed'], $to_order_sn); + } + elseif ($to_order['pay_status'] != PS_UNPAYED) + { + return sprintf($GLOBALS['_LANG']['ps_not_unpayed'], $to_order_sn); + } + elseif ($to_order['shipping_status'] != SS_UNSHIPPED) + { + return sprintf($GLOBALS['_LANG']['ss_not_unshipped'], $to_order_sn); + } + + /* 检查订单用户是否相同 */ + if ($from_order['user_id'] != $to_order['user_id']) + { + return $GLOBALS['_LANG']['order_user_not_same']; + } + + /* 合并订单 */ + $order = $to_order; + $order['order_id'] = ''; + $order['add_time'] = gmtime(); + + // 合并商品总额 + $order['goods_amount'] += $from_order['goods_amount']; + + // 合并折扣 + $order['discount'] += $from_order['discount']; + + if ($order['shipping_id'] > 0) + { + // 重新计算配送费用 + $weight_price = order_weight_price($to_order['order_id']); + $from_weight_price = order_weight_price($from_order['order_id']); + $weight_price['weight'] += $from_weight_price['weight']; + $weight_price['amount'] += $from_weight_price['amount']; + $weight_price['number'] += $from_weight_price['number']; + + $region_id_list = array($order['country'], $order['province'], $order['city'], $order['district']); + $shipping_area = shipping_area_info($order['shipping_id'], $region_id_list); + + $order['shipping_fee'] = shipping_fee($shipping_area['shipping_code'], + unserialize($shipping_area['configure']), $weight_price['weight'], $weight_price['amount'], $weight_price['number']); + + // 如果保价了,重新计算保价费 + if ($order['insure_fee'] > 0) + { + $order['insure_fee'] = shipping_insure_fee($shipping_area['shipping_code'], $order['goods_amount'], $shipping_area['insure']); + } + } + + // 重新计算包装费、贺卡费 + if ($order['pack_id'] > 0) + { + $pack = pack_info($order['pack_id']); + $order['pack_fee'] = $pack['free_money'] > $order['goods_amount'] ? $pack['pack_fee'] : 0; + } + if ($order['card_id'] > 0) + { + $card = card_info($order['card_id']); + $order['card_fee'] = $card['free_money'] > $order['goods_amount'] ? $card['card_fee'] : 0; + } + + // 红包不变,合并积分、余额、已付款金额 + $order['integral'] += $from_order['integral']; + $order['integral_money'] = value_of_integral($order['integral']); + $order['surplus'] += $from_order['surplus']; + $order['money_paid'] += $from_order['money_paid']; + + // 计算应付款金额(不包括支付费用) + $order['order_amount'] = $order['goods_amount'] - $order['discount'] + + $order['shipping_fee'] + + $order['insure_fee'] + + $order['pack_fee'] + + $order['card_fee'] + - $order['bonus'] + - $order['integral_money'] + - $order['surplus'] + - $order['money_paid']; + + // 重新计算支付费 + if ($order['pay_id'] > 0) + { + // 货到付款手续费 + $cod_fee = $shipping_area ? $shipping_area['pay_fee'] : 0; + $order['pay_fee'] = pay_fee($order['pay_id'], $order['order_amount'], $cod_fee); + + // 应付款金额加上支付费 + $order['order_amount'] += $order['pay_fee']; + } + + /* 插入订单表 */ + do + { + $order['order_sn'] = get_order_sn(); + if ($GLOBALS['db']->autoExecute($GLOBALS['ecs']->table('order_info'), addslashes_deep($order), 'INSERT')) + { + break; + } + else + { + if ($GLOBALS['db']->errno() != 1062) + { + die($GLOBALS['db']->errorMsg()); + } + } + } + while (true); // 防止订单号重复 + + /* 订单号 */ + $order_id = $GLOBALS['db']->insert_id(); + + /* 更新订单商品 */ + $sql = 'UPDATE ' . $GLOBALS['ecs']->table('order_goods') . + " SET order_id = '$order_id' " . + "WHERE order_id " . db_create_in(array($from_order['order_id'], $to_order['order_id'])); + $GLOBALS['db']->query($sql); + + include_once(ROOT_PATH . 'includes/lib_clips.php'); + /* 插入支付日志 */ + insert_pay_log($order_id, $order['order_amount'], PAY_ORDER); + + /* 删除原订单 */ + $sql = 'DELETE FROM ' . $GLOBALS['ecs']->table('order_info') . + " WHERE order_id " . db_create_in(array($from_order['order_id'], $to_order['order_id'])); + $GLOBALS['db']->query($sql); + + /* 删除原订单支付日志 */ + $sql = 'DELETE FROM ' . $GLOBALS['ecs']->table('pay_log') . + " WHERE order_id " . db_create_in(array($from_order['order_id'], $to_order['order_id'])); + $GLOBALS['db']->query($sql); + + /* 返还 from_order 的红包,因为只使用 to_order 的红包 */ + if ($from_order['bonus_id'] > 0) + { + unuse_bonus($from_order['bonus_id']); + } + + /* 返回成功 */ + return true; +} + +/** + * 查询配送区域属于哪个办事处管辖 + * @param array $regions 配送区域(1、2、3、4级按顺序) + * @return int 办事处id,可能为0 + */ +function get_agency_by_regions($regions) +{ + if (!is_array($regions) || empty($regions)) + { + return 0; + } + + $arr = array(); + $sql = "SELECT region_id, agency_id " . + "FROM " . $GLOBALS['ecs']->table('region') . + " WHERE region_id " . db_create_in($regions) . + " AND region_id > 0 AND agency_id > 0"; + $res = $GLOBALS['db']->query($sql); + while ($row = $GLOBALS['db']->fetchRow($res)) + { + $arr[$row['region_id']] = $row['agency_id']; + } + if (empty($arr)) + { + return 0; + } + + $agency_id = 0; + for ($i = count($regions) - 1; $i >= 0; $i--) + { + if (isset($arr[$regions[$i]])) + { + return $arr[$regions[$i]]; + } + } +} + +/** + * 获取配送插件的实例 + * @param int $shipping_id 配送插件ID + * @return object 配送插件对象实例 + */ +function &get_shipping_object($shipping_id) +{ + $shipping = shipping_info($shipping_id); + if (!$shipping) + { + $object = new stdClass(); + return $object; + } + + $file_path = ROOT_PATH.'includes/modules/shipping/' . $shipping['shipping_code'] . '.php'; + + include_once($file_path); + + $object = new $shipping['shipping_code']; + return $object; +} + +/** + * 改变订单中商品库存 + * @param int $order_id 订单号 + * @param bool $is_dec 是否减少库存 + * @param bool $storage 减库存的时机,1,下订单时;0,发货时; + */ +function change_order_goods_storage($order_id, $is_dec = true, $storage = 0) +{ + /* 查询订单商品信息 */ + switch ($storage) + { + case 0 : + $sql = "SELECT goods_id, SUM(send_number) AS num, MAX(extension_code) AS extension_code, product_id FROM " . $GLOBALS['ecs']->table('order_goods') . + " WHERE order_id = '$order_id' AND is_real = 1 GROUP BY goods_id, product_id"; + break; + + case 1 : + $sql = "SELECT goods_id, SUM(goods_number) AS num, MAX(extension_code) AS extension_code, product_id FROM " . $GLOBALS['ecs']->table('order_goods') . + " WHERE order_id = '$order_id' AND is_real = 1 GROUP BY goods_id, product_id"; + break; + } + + $res = $GLOBALS['db']->query($sql); + while ($row = $GLOBALS['db']->fetchRow($res)) + { + if ($row['extension_code'] != "package_buy") + { + if ($is_dec) + { + change_goods_storage($row['goods_id'], $row['product_id'], - $row['num']); + } + else + { + change_goods_storage($row['goods_id'], $row['product_id'], $row['num']); + } + $GLOBALS['db']->query($sql); + } + else + { + $sql = "SELECT goods_id, goods_number" . + " FROM " . $GLOBALS['ecs']->table('package_goods') . + " WHERE package_id = '" . $row['goods_id'] . "'"; + $res_goods = $GLOBALS['db']->query($sql); + while ($row_goods = $GLOBALS['db']->fetchRow($res_goods)) + { + $sql = "SELECT is_real" . + " FROM " . $GLOBALS['ecs']->table('goods') . + " WHERE goods_id = '" . $row_goods['goods_id'] . "'"; + $real_goods = $GLOBALS['db']->query($sql); + $is_goods = $GLOBALS['db']->fetchRow($real_goods); + + if ($is_dec) + { + change_goods_storage($row_goods['goods_id'], $row['product_id'], - ($row['num'] * $row_goods['goods_number'])); + } + elseif ($is_goods['is_real']) + { + change_goods_storage($row_goods['goods_id'], $row['product_id'], ($row['num'] * $row_goods['goods_number'])); + } + } + } + } + +} + +/** + * 商品库存增与减 货品库存增与减 + * + * @param int $good_id 商品ID + * @param int $product_id 货品ID + * @param int $number 增减数量,默认0; + * + * @return bool true,成功;false,失败; + */ +function change_goods_storage($good_id, $product_id, $number = 0) +{ + if ($number == 0) + { + return true; // 值为0即不做、增减操作,返回true + } + + if (empty($good_id) || empty($number)) + { + return false; + } + + $number = ($number > 0) ? '+ ' . $number : $number; + + /* 处理货品库存 */ + $products_query = true; + if (!empty($product_id)) + { + $sql = "UPDATE " . $GLOBALS['ecs']->table('products') ." + SET product_number = product_number $number + WHERE goods_id = '$good_id' + AND product_id = '$product_id' + LIMIT 1"; + $products_query = $GLOBALS['db']->query($sql); + } + + /* 处理商品库存 */ + $sql = "UPDATE " . $GLOBALS['ecs']->table('goods') ." + SET goods_number = goods_number $number + WHERE goods_id = '$good_id' + LIMIT 1"; + $query = $GLOBALS['db']->query($sql); + + if ($query && $products_query) + { + return true; + } + else + { + return false; + } +} + +/** + * 取得支付方式id列表 + * @param bool $is_cod 是否货到付款 + * @return array + */ +function payment_id_list($is_cod) +{ + $sql = "SELECT pay_id FROM " . $GLOBALS['ecs']->table('payment'); + if ($is_cod) + { + $sql .= " WHERE is_cod = 1"; + } + else + { + $sql .= " WHERE is_cod = 0"; + } + + return $GLOBALS['db']->getCol($sql); +} + +/** + * 生成查询订单的sql + * @param string $type 类型 + * @param string $alias order表的别名(包括.例如 o.) + * @return string + */ +function order_query_sql($type = 'finished', $alias = '') +{ + /* 已完成订单 */ + if ($type == 'finished') + { + return " AND {$alias}order_status " . db_create_in(array(OS_CONFIRMED, OS_SPLITED)) . + " AND {$alias}shipping_status " . db_create_in(array(SS_SHIPPED, SS_RECEIVED)) . + " AND {$alias}pay_status " . db_create_in(array(PS_PAYED, PS_PAYING)) . " "; + } + /* 待发货订单 */ + elseif ($type == 'await_ship') + { + return " AND {$alias}order_status " . + db_create_in(array(OS_CONFIRMED, OS_SPLITED, OS_SPLITING_PART)) . + " AND {$alias}shipping_status " . + db_create_in(array(SS_UNSHIPPED, SS_PREPARING, SS_SHIPPED_ING)) . + " AND ( {$alias}pay_status " . db_create_in(array(PS_PAYED, PS_PAYING)) . " OR {$alias}pay_id " . db_create_in(payment_id_list(true)) . ") "; + } + /* 待付款订单 */ + elseif ($type == 'await_pay') + { + return " AND {$alias}order_status " . db_create_in(array(OS_CONFIRMED, OS_SPLITED)) . + " AND {$alias}pay_status = '" . PS_UNPAYED . "'" . + " AND ( {$alias}shipping_status " . db_create_in(array(SS_SHIPPED, SS_RECEIVED)) . " OR {$alias}pay_id " . db_create_in(payment_id_list(false)) . ") "; + } + /* 未确认订单 */ + elseif ($type == 'unconfirmed') + { + return " AND {$alias}order_status = '" . OS_UNCONFIRMED . "' "; + } + /* 未处理订单:用户可操作 */ + elseif ($type == 'unprocessed') + { + return " AND {$alias}order_status " . db_create_in(array(OS_UNCONFIRMED, OS_CONFIRMED)) . + " AND {$alias}shipping_status = '" . SS_UNSHIPPED . "'" . + " AND {$alias}pay_status = '" . PS_UNPAYED . "' "; + } + /* 未付款未发货订单:管理员可操作 */ + elseif ($type == 'unpay_unship') + { + return " AND {$alias}order_status " . db_create_in(array(OS_UNCONFIRMED, OS_CONFIRMED)) . + " AND {$alias}shipping_status " . db_create_in(array(SS_UNSHIPPED, SS_PREPARING)) . + " AND {$alias}pay_status = '" . PS_UNPAYED . "' "; + } + /* 已发货订单:不论是否付款 */ + elseif ($type == 'shipped') + { + return " AND {$alias}order_status = '" . OS_CONFIRMED . "'" . + " AND {$alias}shipping_status " . db_create_in(array(SS_SHIPPED, SS_RECEIVED)) . " "; + } + else + { + die('函数 order_query_sql 参数错误'); + } +} + +/** + * 生成查询订单总金额的字段 + * @param string $alias order表的别名(包括.例如 o.) + * @return string + */ +function order_amount_field($alias = '') +{ + return " {$alias}goods_amount + {$alias}tax + {$alias}shipping_fee" . + " + {$alias}insure_fee + {$alias}pay_fee + {$alias}pack_fee" . + " + {$alias}card_fee "; +} + +/** + * 生成计算应付款金额的字段 + * @param string $alias order表的别名(包括.例如 o.) + * @return string + */ +function order_due_field($alias = '') +{ + return order_amount_field($alias) . + " - {$alias}money_paid - {$alias}surplus - {$alias}integral_money" . + " - {$alias}bonus - {$alias}discount "; +} + +/** + * 计算折扣:根据购物车和优惠活动 + * @return float 折扣 + */ +function compute_discount() +{ + /* 查询优惠活动 */ + $now = gmtime(); + $user_rank = ',' . $_SESSION['user_rank'] . ','; + $sql = "SELECT *" . + "FROM " . $GLOBALS['ecs']->table('favourable_activity') . + " WHERE start_time <= '$now'" . + " AND end_time >= '$now'" . + " AND CONCAT(',', user_rank, ',') LIKE '%" . $user_rank . "%'" . + " AND act_type " . db_create_in(array(FAT_DISCOUNT, FAT_PRICE)); + $favourable_list = $GLOBALS['db']->getAll($sql); + if (!$favourable_list) + { + return 0; + } + + /* 查询购物车商品 */ + $sql = "SELECT c.goods_id, c.goods_price * c.goods_number AS subtotal, g.cat_id, g.brand_id " . + "FROM " . $GLOBALS['ecs']->table('cart') . " AS c, " . $GLOBALS['ecs']->table('goods') . " AS g " . + "WHERE c.goods_id = g.goods_id " . + "AND c.session_id = '" . SESS_ID . "' " . + "AND c.parent_id = 0 " . + "AND c.is_gift = 0 " . + "AND rec_type = '" . CART_GENERAL_GOODS . "'"; + $goods_list = $GLOBALS['db']->getAll($sql); + if (!$goods_list) + { + return 0; + } + + /* 初始化折扣 */ + $discount = 0; + $favourable_name = array(); + + /* 循环计算每个优惠活动的折扣 */ + foreach ($favourable_list as $favourable) + { + $total_amount = 0; + if ($favourable['act_range'] == FAR_ALL) + { + foreach ($goods_list as $goods) + { + $total_amount += $goods['subtotal']; + } + } + elseif ($favourable['act_range'] == FAR_CATEGORY) + { + /* 找出分类id的子分类id */ + $id_list = array(); + $raw_id_list = explode(',', $favourable['act_range_ext']); + foreach ($raw_id_list as $id) + { + $id_list = array_merge($id_list, array_keys(cat_list($id, 0, false))); + } + $ids = join(',', array_unique($id_list)); + + foreach ($goods_list as $goods) + { + if (strpos(',' . $ids . ',', ',' . $goods['cat_id'] . ',') !== false) + { + $total_amount += $goods['subtotal']; + } + } + } + elseif ($favourable['act_range'] == FAR_BRAND) + { + foreach ($goods_list as $goods) + { + if (strpos(',' . $favourable['act_range_ext'] . ',', ',' . $goods['brand_id'] . ',') !== false) + { + $total_amount += $goods['subtotal']; + } + } + } + elseif ($favourable['act_range'] == FAR_GOODS) + { + foreach ($goods_list as $goods) + { + if (strpos(',' . $favourable['act_range_ext'] . ',', ',' . $goods['goods_id'] . ',') !== false) + { + $total_amount += $goods['subtotal']; + } + } + } + else + { + continue; + } + + /* 如果金额满足条件,累计折扣 */ + if ($total_amount > 0 && $total_amount >= $favourable['min_amount'] && ($total_amount <= $favourable['max_amount'] || $favourable['max_amount'] == 0)) + { + if ($favourable['act_type'] == FAT_DISCOUNT) + { + $discount += $total_amount * (1 - $favourable['act_type_ext'] / 100); + + $favourable_name[] = $favourable['act_name']; + } + elseif ($favourable['act_type'] == FAT_PRICE) + { + $discount += $favourable['act_type_ext']; + + $favourable_name[] = $favourable['act_name']; + } + } + } + + return array('discount' => $discount, 'name' => $favourable_name); +} + +/** + * 取得购物车该赠送的积分数 + * @return int 积分数 + */ +function get_give_integral() +{ + $sql = "SELECT SUM(c.goods_number * IF(g.give_integral > -1, g.give_integral, c.goods_price))" . + "FROM " . $GLOBALS['ecs']->table('cart') . " AS c, " . + $GLOBALS['ecs']->table('goods') . " AS g " . + "WHERE c.goods_id = g.goods_id " . + "AND c.session_id = '" . SESS_ID . "' " . + "AND c.goods_id > 0 " . + "AND c.parent_id = 0 " . + "AND c.rec_type = 0 " . + "AND c.is_gift = 0"; + + return intval($GLOBALS['db']->getOne($sql)); +} + +/** + * 取得某订单应该赠送的积分数 + * @param array $order 订单 + * @return int 积分数 + */ +function integral_to_give($order) +{ + /* 判断是否团购 */ + if ($order['extension_code'] == 'group_buy') + { + include_once(ROOT_PATH . 'includes/lib_goods.php'); + $group_buy = group_buy_info(intval($order['extension_id'])); + + return array('custom_points' => $group_buy['gift_integral'], 'rank_points' => $order['goods_amount']); + } + else + { + $sql = "SELECT SUM(og.goods_number * IF(g.give_integral > -1, g.give_integral, og.goods_price)) AS custom_points, SUM(og.goods_number * IF(g.rank_integral > -1, g.rank_integral, og.goods_price)) AS rank_points " . + "FROM " . $GLOBALS['ecs']->table('order_goods') . " AS og, " . + $GLOBALS['ecs']->table('goods') . " AS g " . + "WHERE og.goods_id = g.goods_id " . + "AND og.order_id = '$order[order_id]' " . + "AND og.goods_id > 0 " . + "AND og.parent_id = 0 " . + "AND og.is_gift = 0 AND og.extension_code != 'package_buy'"; + + return $GLOBALS['db']->getRow($sql); + } +} + +/** + * 发红包:发货时发红包 + * @param int $order_id 订单号 + * @return bool + */ +function send_order_bonus($order_id) +{ + /* 取得订单应该发放的红包 */ + $bonus_list = order_bonus($order_id); + + /* 如果有红包,统计并发送 */ + if ($bonus_list) + { + /* 用户信息 */ + $sql = "SELECT u.user_id, u.user_name, u.email " . + "FROM " . $GLOBALS['ecs']->table('order_info') . " AS o, " . + $GLOBALS['ecs']->table('users') . " AS u " . + "WHERE o.order_id = '$order_id' " . + "AND o.user_id = u.user_id "; + $user = $GLOBALS['db']->getRow($sql); + + /* 统计 */ + $count = 0; + $money = ''; + foreach ($bonus_list AS $bonus) + { + $count += $bonus['number']; + $money .= price_format($bonus['type_money']) . ' [' . $bonus['number'] . '], '; + + /* 修改用户红包 */ + $sql = "INSERT INTO " . $GLOBALS['ecs']->table('user_bonus') . " (bonus_type_id, user_id) " . + "VALUES('$bonus[type_id]', '$user[user_id]')"; + for ($i = 0; $i < $bonus['number']; $i++) + { + if (!$GLOBALS['db']->query($sql)) + { + return $GLOBALS['db']->errorMsg(); + } + } + } + + /* 如果有红包,发送邮件 */ + if ($count > 0) + { + $tpl = get_mail_template('send_bonus'); + $GLOBALS['smarty']->assign('user_name', $user['user_name']); + $GLOBALS['smarty']->assign('count', $count); + $GLOBALS['smarty']->assign('money', $money); + $GLOBALS['smarty']->assign('shop_name', $GLOBALS['_CFG']['shop_name']); + $GLOBALS['smarty']->assign('send_date', local_date($GLOBALS['_CFG']['date_format'])); + $GLOBALS['smarty']->assign('sent_date', local_date($GLOBALS['_CFG']['date_format'])); + $content = $GLOBALS['smarty']->fetch('str:' . $tpl['template_content']); + send_mail($user['user_name'], $user['email'], $tpl['template_subject'], $content, $tpl['is_html']); + } + } + + return true; +} + +/** + * 返回订单发放的红包 + * @param int $order_id 订单id + */ +function return_order_bonus($order_id) +{ + /* 取得订单应该发放的红包 */ + $bonus_list = order_bonus($order_id); + + /* 删除 */ + if ($bonus_list) + { + /* 取得订单信息 */ + $order = order_info($order_id); + $user_id = $order['user_id']; + + foreach ($bonus_list AS $bonus) + { + $sql = "DELETE FROM " . $GLOBALS['ecs']->table('user_bonus') . + " WHERE bonus_type_id = '$bonus[type_id]' " . + "AND user_id = '$user_id' " . + "AND order_id = '0' LIMIT " . $bonus['number']; + $GLOBALS['db']->query($sql); + } + } +} + +/** + * 取得订单应该发放的红包 + * @param int $order_id 订单id + * @return array + */ +function order_bonus($order_id) +{ + /* 查询按商品发的红包 */ + $day = getdate(); + $today = local_mktime(23, 59, 59, $day['mon'], $day['mday'], $day['year']); + + $sql = "SELECT b.type_id, b.type_money, SUM(o.goods_number) AS number " . + "FROM " . $GLOBALS['ecs']->table('order_goods') . " AS o, " . + $GLOBALS['ecs']->table('goods') . " AS g, " . + $GLOBALS['ecs']->table('bonus_type') . " AS b " . + " WHERE o.order_id = '$order_id' " . + " AND o.is_gift = 0 " . + " AND o.goods_id = g.goods_id " . + " AND g.bonus_type_id = b.type_id " . + " AND b.send_type = '" . SEND_BY_GOODS . "' " . + " AND b.send_start_date <= '$today' " . + " AND b.send_end_date >= '$today' " . + " GROUP BY b.type_id "; + $list = $GLOBALS['db']->getAll($sql); + + /* 查询定单中非赠品总金额 */ + $amount = order_amount($order_id, false); + + /* 查询订单日期 */ + $sql = "SELECT add_time " . + " FROM " . $GLOBALS['ecs']->table('order_info') . + " WHERE order_id = '$order_id' LIMIT 1"; + $order_time = $GLOBALS['db']->getOne($sql); + + /* 查询按订单发的红包 */ + $sql = "SELECT type_id, type_money, IFNULL(FLOOR('$amount' / min_amount), 1) AS number " . + "FROM " . $GLOBALS['ecs']->table('bonus_type') . + "WHERE send_type = '" . SEND_BY_ORDER . "' " . + "AND send_start_date <= '$order_time' " . + "AND send_end_date >= '$order_time' "; + $list = array_merge($list, $GLOBALS['db']->getAll($sql)); + + return $list; +} + +/** + * 计算购物车中的商品能享受红包支付的总额 + * @return float 享受红包支付的总额 + */ +function compute_discount_amount() +{ + /* 查询优惠活动 */ + $now = gmtime(); + $user_rank = ',' . $_SESSION['user_rank'] . ','; + $sql = "SELECT *" . + "FROM " . $GLOBALS['ecs']->table('favourable_activity') . + " WHERE start_time <= '$now'" . + " AND end_time >= '$now'" . + " AND CONCAT(',', user_rank, ',') LIKE '%" . $user_rank . "%'" . + " AND act_type " . db_create_in(array(FAT_DISCOUNT, FAT_PRICE)); + $favourable_list = $GLOBALS['db']->getAll($sql); + if (!$favourable_list) + { + return 0; + } + + /* 查询购物车商品 */ + $sql = "SELECT c.goods_id, c.goods_price * c.goods_number AS subtotal, g.cat_id, g.brand_id " . + "FROM " . $GLOBALS['ecs']->table('cart') . " AS c, " . $GLOBALS['ecs']->table('goods') . " AS g " . + "WHERE c.goods_id = g.goods_id " . + "AND c.session_id = '" . SESS_ID . "' " . + "AND c.parent_id = 0 " . + "AND c.is_gift = 0 " . + "AND rec_type = '" . CART_GENERAL_GOODS . "'"; + $goods_list = $GLOBALS['db']->getAll($sql); + if (!$goods_list) + { + return 0; + } + + /* 初始化折扣 */ + $discount = 0; + $favourable_name = array(); + + /* 循环计算每个优惠活动的折扣 */ + foreach ($favourable_list as $favourable) + { + $total_amount = 0; + if ($favourable['act_range'] == FAR_ALL) + { + foreach ($goods_list as $goods) + { + $total_amount += $goods['subtotal']; + } + } + elseif ($favourable['act_range'] == FAR_CATEGORY) + { + /* 找出分类id的子分类id */ + $id_list = array(); + $raw_id_list = explode(',', $favourable['act_range_ext']); + foreach ($raw_id_list as $id) + { + $id_list = array_merge($id_list, array_keys(cat_list($id, 0, false))); + } + $ids = join(',', array_unique($id_list)); + + foreach ($goods_list as $goods) + { + if (strpos(',' . $ids . ',', ',' . $goods['cat_id'] . ',') !== false) + { + $total_amount += $goods['subtotal']; + } + } + } + elseif ($favourable['act_range'] == FAR_BRAND) + { + foreach ($goods_list as $goods) + { + if (strpos(',' . $favourable['act_range_ext'] . ',', ',' . $goods['brand_id'] . ',') !== false) + { + $total_amount += $goods['subtotal']; + } + } + } + elseif ($favourable['act_range'] == FAR_GOODS) + { + foreach ($goods_list as $goods) + { + if (strpos(',' . $favourable['act_range_ext'] . ',', ',' . $goods['goods_id'] . ',') !== false) + { + $total_amount += $goods['subtotal']; + } + } + } + else + { + continue; + } + if ($total_amount > 0 && $total_amount >= $favourable['min_amount'] && ($total_amount <= $favourable['max_amount'] || $favourable['max_amount'] == 0)) + { + if ($favourable['act_type'] == FAT_DISCOUNT) + { + $discount += $total_amount * (1 - $favourable['act_type_ext'] / 100); + } + elseif ($favourable['act_type'] == FAT_PRICE) + { + $discount += $favourable['act_type_ext']; + } + } + } + + + return $discount; +} + +/** + * 添加礼包到购物车 + * + * @access public + * @param integer $package_id 礼包编号 + * @param integer $num 礼包数量 + * @return boolean + */ +function add_package_to_cart($package_id, $num = 1) +{ + $GLOBALS['err']->clean(); + + /* 取得礼包信息 */ + $package = get_package_info($package_id); + + if (empty($package)) + { + $GLOBALS['err']->add($GLOBALS['_LANG']['goods_not_exists'], ERR_NOT_EXISTS); + + return false; + } + + /* 是否正在销售 */ + if ($package['is_on_sale'] == 0) + { + $GLOBALS['err']->add($GLOBALS['_LANG']['not_on_sale'], ERR_NOT_ON_SALE); + + return false; + } + + /* 现有库存是否还能凑齐一个礼包 */ + if ($GLOBALS['_CFG']['use_storage'] == '1' && judge_package_stock($package_id)) + { + $GLOBALS['err']->add(sprintf($GLOBALS['_LANG']['shortage'], 1), ERR_OUT_OF_STOCK); + + return false; + } + + /* 检查库存 */ +// if ($GLOBALS['_CFG']['use_storage'] == 1 && $num > $package['goods_number']) +// { +// $num = $goods['goods_number']; +// $GLOBALS['err']->add(sprintf($GLOBALS['_LANG']['shortage'], $num), ERR_OUT_OF_STOCK); +// +// return false; +// } + + /* 初始化要插入购物车的基本件数据 */ + $parent = array( + 'user_id' => $_SESSION['user_id'], + 'session_id' => SESS_ID, + 'goods_id' => $package_id, + 'goods_sn' => '', + 'goods_name' => addslashes($package['package_name']), + 'market_price' => $package['market_package'], + 'goods_price' => $package['package_price'], + 'goods_number' => $num, + 'goods_attr' => '', + 'goods_attr_id' => '', + 'is_real' => $package['is_real'], + 'extension_code'=> 'package_buy', + 'is_gift' => 0, + 'rec_type' => CART_GENERAL_GOODS + ); + + /* 如果数量不为0,作为基本件插入 */ + if ($num > 0) + { + /* 检查该商品是否已经存在在购物车中 */ + $sql = "SELECT goods_number FROM " .$GLOBALS['ecs']->table('cart'). + " WHERE session_id = '" .SESS_ID. "' AND goods_id = '" . $package_id . "' ". + " AND parent_id = 0 AND extension_code = 'package_buy' " . + " AND rec_type = '" . CART_GENERAL_GOODS . "'"; + + $row = $GLOBALS['db']->getRow($sql); + + if($row) //如果购物车已经有此物品,则更新 + { + $num += $row['goods_number']; + if ($GLOBALS['_CFG']['use_storage'] == 0 || $num > 0) + { + $sql = "UPDATE " . $GLOBALS['ecs']->table('cart') . " SET goods_number = '" . $num . "'" . + " WHERE session_id = '" .SESS_ID. "' AND goods_id = '$package_id' ". + " AND parent_id = 0 AND extension_code = 'package_buy' " . + " AND rec_type = '" . CART_GENERAL_GOODS . "'"; + $GLOBALS['db']->query($sql); + } + else + { + $GLOBALS['err']->add(sprintf($GLOBALS['_LANG']['shortage'], $num), ERR_OUT_OF_STOCK); + return false; + } + } + else //购物车没有此物品,则插入 + { + $GLOBALS['db']->autoExecute($GLOBALS['ecs']->table('cart'), $parent, 'INSERT'); + } + } + + /* 把赠品删除 */ + $sql = "DELETE FROM " . $GLOBALS['ecs']->table('cart') . " WHERE session_id = '" . SESS_ID . "' AND is_gift <> 0"; + $GLOBALS['db']->query($sql); + + return true; +} + +/** + * 得到新发货单号 + * @return string + */ +function get_delivery_sn() +{ + /* 选择一个随机的方案 */ + mt_srand((double) microtime() * 1000000); + + return date('YmdHi') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT); +} + +/** + * 检查礼包内商品的库存 + * @return boolen + */ +function judge_package_stock($package_id, $package_num = 1) +{ + $sql = "SELECT goods_id, product_id, goods_number + FROM " . $GLOBALS['ecs']->table('package_goods') . " + WHERE package_id = '" . $package_id . "'"; + $row = $GLOBALS['db']->getAll($sql); + if (empty($row)) + { + return true; + } + + /* 分离货品与商品 */ + $goods = array('product_ids' => '', 'goods_ids' => ''); + foreach ($row as $value) + { + if ($value['product_id'] > 0) + { + $goods['product_ids'] .= ',' . $value['product_id']; + continue; + } + + $goods['goods_ids'] .= ',' . $value['goods_id']; + } + + /* 检查货品库存 */ + if ($goods['product_ids'] != '') + { + $sql = "SELECT p.product_id + FROM " . $GLOBALS['ecs']->table('products') . " AS p, " . $GLOBALS['ecs']->table('package_goods') . " AS pg + WHERE pg.product_id = p.product_id + AND pg.package_id = '$package_id' + AND pg.goods_number * $package_num > p.product_number + AND p.product_id IN (" . trim($goods['product_ids'], ',') . ")"; + $row = $GLOBALS['db']->getAll($sql); + + if (!empty($row)) + { + return true; + } + } + + /* 检查商品库存 */ + if ($goods['goods_ids'] != '') + { + $sql = "SELECT g.goods_id + FROM " . $GLOBALS['ecs']->table('goods') . "AS g, " . $GLOBALS['ecs']->table('package_goods') . " AS pg + WHERE pg.goods_id = g.goods_id + AND pg.goods_number * $package_num > g.goods_number + AND pg.package_id = '" . $package_id . "' + AND pg.goods_id IN (" . trim($goods['goods_ids'], ',') . ")"; + $row = $GLOBALS['db']->getAll($sql); + + if (!empty($row)) + { + return true; + } + } + + return false; +} +?> \ No newline at end of file diff --git a/includes/lib_passport.php b/includes/lib_passport.php new file mode 100644 index 0000000..2a9e24e --- /dev/null +++ b/includes/lib_passport.php @@ -0,0 +1,404 @@ +add($GLOBALS['_LANG']['shop_register_closed']); + } + /* 检查username */ + if (empty($username)) + { + $GLOBALS['err']->add($GLOBALS['_LANG']['username_empty']); + } + else + { + if (preg_match('/\'\/^\\s*$|^c:\\\\con\\\\con$|[%,\\*\\"\\s\\t\\<\\>\\&\'\\\\]/', $username)) + { + $GLOBALS['err']->add(sprintf($GLOBALS['_LANG']['username_invalid'], htmlspecialchars($username))); + } + } + + /* 检查email */ + if (empty($email)) + { + $GLOBALS['err']->add($GLOBALS['_LANG']['email_empty']); + } + else + { + if (!is_email($email)) + { + $GLOBALS['err']->add(sprintf($GLOBALS['_LANG']['email_invalid'], htmlspecialchars($email))); + } + } + + if ($GLOBALS['err']->error_no > 0) + { + return false; + } + + /* 检查是否和管理员重名 */ + if (admin_registered($username)) + { + $GLOBALS['err']->add(sprintf($GLOBALS['_LANG']['username_exist'], $username)); + return false; + } + + if (!$GLOBALS['user']->add_user($username, $password, $email)) + { + if ($GLOBALS['user']->error == ERR_INVALID_USERNAME) + { + $GLOBALS['err']->add(sprintf($GLOBALS['_LANG']['username_invalid'], $username)); + } + elseif ($GLOBALS['user']->error == ERR_USERNAME_NOT_ALLOW) + { + $GLOBALS['err']->add(sprintf($GLOBALS['_LANG']['username_not_allow'], $username)); + } + elseif ($GLOBALS['user']->error == ERR_USERNAME_EXISTS) + { + $GLOBALS['err']->add(sprintf($GLOBALS['_LANG']['username_exist'], $username)); + } + elseif ($GLOBALS['user']->error == ERR_INVALID_EMAIL) + { + $GLOBALS['err']->add(sprintf($GLOBALS['_LANG']['email_invalid'], $email)); + } + elseif ($GLOBALS['user']->error == ERR_EMAIL_NOT_ALLOW) + { + $GLOBALS['err']->add(sprintf($GLOBALS['_LANG']['email_not_allow'], $email)); + } + elseif ($GLOBALS['user']->error == ERR_EMAIL_EXISTS) + { + $GLOBALS['err']->add(sprintf($GLOBALS['_LANG']['email_exist'], $email)); + } + else + { + $GLOBALS['err']->add('UNKNOWN ERROR!'); + } + + //注册失败 + return false; + } + else + { + //注册成功 + + /* 设置成登录状态 */ + $GLOBALS['user']->set_session($username); + $GLOBALS['user']->set_cookie($username); + + /* 注册送积分 */ + if (!empty($GLOBALS['_CFG']['register_points'])) + { + log_account_change($_SESSION['user_id'], 0, 0, $GLOBALS['_CFG']['register_points'], $GLOBALS['_CFG']['register_points'], $GLOBALS['_LANG']['register_points']); + } + + /*推荐处理*/ + $affiliate = unserialize($GLOBALS['_CFG']['affiliate']); + if (isset($affiliate['on']) && $affiliate['on'] == 1) + { + // 推荐开关开启 + $up_uid = get_affiliate(); + empty($affiliate) && $affiliate = array(); + $affiliate['config']['level_register_all'] = intval($affiliate['config']['level_register_all']); + $affiliate['config']['level_register_up'] = intval($affiliate['config']['level_register_up']); + if ($up_uid) + { + if (!empty($affiliate['config']['level_register_all'])) + { + if (!empty($affiliate['config']['level_register_up'])) + { + $rank_points = $GLOBALS['db']->getOne("SELECT rank_points FROM " . $GLOBALS['ecs']->table('users') . " WHERE user_id = '$up_uid'"); + if ($rank_points + $affiliate['config']['level_register_all'] <= $affiliate['config']['level_register_up']) + { + log_account_change($up_uid, 0, 0, $affiliate['config']['level_register_all'], 0, sprintf($GLOBALS['_LANG']['register_affiliate'], $_SESSION['user_id'], $username)); + } + } + else + { + log_account_change($up_uid, 0, 0, $affiliate['config']['level_register_all'], 0, $GLOBALS['_LANG']['register_affiliate']); + } + } + + //设置推荐人 + $sql = 'UPDATE '. $GLOBALS['ecs']->table('users') . ' SET parent_id = ' . $up_uid . ' WHERE user_id = ' . $_SESSION['user_id']; + + $GLOBALS['db']->query($sql); + } + } + + //定义other合法的变量数组 + $other_key_array = array('msn', 'qq', 'office_phone', 'home_phone', 'mobile_phone'); + $update_data['reg_time'] = local_strtotime(local_date('Y-m-d H:i:s')); + if ($other) + { + foreach ($other as $key=>$val) + { + //删除非法key值 + if (!in_array($key, $other_key_array)) + { + unset($other[$key]); + } + else + { + $other[$key] = htmlspecialchars(trim($val)); //防止用户输入javascript代码 + } + } + $update_data = array_merge($update_data, $other); + } + $GLOBALS['db']->autoExecute($GLOBALS['ecs']->table('users'), $update_data, 'UPDATE', 'user_id = ' . $_SESSION['user_id']); + + update_user_info(); // 更新用户信息 + recalculate_price(); // 重新计算购物车中的商品价格 + + return true; + } +} + +/** + * + * + * @access public + * @param + * + * @return void + */ +function logout() +{ +/* todo */ +} + +/** + * 将指定user_id的密码修改为new_password。可以通过旧密码和验证字串验证修改。 + * + * @access public + * @param int $user_id 用户ID + * @param string $new_password 用户新密码 + * @param string $old_password 用户旧密码 + * @param string $code 验证码(md5($user_id . md5($password))) + * + * @return boolen $bool + */ +function edit_password($user_id, $old_password, $new_password='', $code ='') +{ + if (empty($user_id)) $GLOBALS['err']->add($GLOBALS['_LANG']['not_login']); + + if ($GLOBALS['user']->edit_password($user_id, $old_password, $new_password, $code)) + { + return true; + } + else + { + $GLOBALS['err']->add($GLOBALS['_LANG']['edit_password_failure']); + + return false; + } +} + +/** + * 会员找回密码时,对输入的用户名和邮件地址匹配 + * + * @access public + * @param string $user_name 用户帐号 + * @param string $email 用户Email + * + * @return boolen + */ +function check_userinfo($user_name, $email) +{ + if (empty($user_name) || empty($email)) + { + ecs_header("Location: user.php?act=get_password\n"); + + exit; + } + + /* 检测用户名和邮件地址是否匹配 */ + $user_info = $GLOBALS['user']->check_pwd_info($user_name, $email); + if (!empty($user_info)) + { + return $user_info; + } + else + { + return false; + } +} + +/** + * 用户进行密码找回操作时,发送一封确认邮件 + * + * @access public + * @param string $uid 用户ID + * @param string $user_name 用户帐号 + * @param string $email 用户Email + * @param string $code key + * + * @return boolen $result; + */ +function send_pwd_email($uid, $user_name, $email, $code) +{ + if (empty($uid) || empty($user_name) || empty($email) || empty($code)) + { + ecs_header("Location: user.php?act=get_password\n"); + + exit; + } + + /* 设置重置邮件模板所需要的内容信息 */ + $template = get_mail_template('send_password'); + $reset_email = $GLOBALS['ecs']->url() . 'user.php?act=get_password&uid=' . $uid . '&code=' . $code; + + $GLOBALS['smarty']->assign('user_name', $user_name); + $GLOBALS['smarty']->assign('reset_email', $reset_email); + $GLOBALS['smarty']->assign('shop_name', $GLOBALS['_CFG']['shop_name']); + $GLOBALS['smarty']->assign('send_date', date('Y-m-d')); + $GLOBALS['smarty']->assign('sent_date', date('Y-m-d')); + + $content = $GLOBALS['smarty']->fetch('str:' . $template['template_content']); + + /* 发送确认重置密码的确认邮件 */ + if (send_mail($user_name, $email, $template['template_subject'], $content, $template['is_html'])) + { + return true; + } + else + { + return false; + } +} + +/** + * 发送激活验证邮件 + * + * @access public + * @param int $user_id 用户ID + * + * @return boolen + */ +function send_regiter_hash ($user_id) +{ + /* 设置验证邮件模板所需要的内容信息 */ + $template = get_mail_template('register_validate'); + $hash = register_hash('encode', $user_id); + $validate_email = $GLOBALS['ecs']->url() . 'user.php?act=validate_email&hash=' . $hash; + + $sql = "SELECT user_name, email FROM " . $GLOBALS['ecs']->table('users') . " WHERE user_id = '$user_id'"; + $row = $GLOBALS['db']->getRow($sql); + + $GLOBALS['smarty']->assign('user_name', $row['user_name']); + $GLOBALS['smarty']->assign('validate_email', $validate_email); + $GLOBALS['smarty']->assign('shop_name', $GLOBALS['_CFG']['shop_name']); + $GLOBALS['smarty']->assign('send_date', date($GLOBALS['_CFG']['date_format'])); + + $content = $GLOBALS['smarty']->fetch('str:' . $template['template_content']); + + /* 发送激活验证邮件 */ + if (send_mail($row['user_name'], $row['email'], $template['template_subject'], $content, $template['is_html'])) + { + return true; + } + else + { + return false; + } +} + +/** + * 生成邮件验证hash + * + * @access public + * @param + * + * @return void + */ +function register_hash ($operation, $key) +{ + if ($operation == 'encode') + { + $user_id = intval($key); + $sql = "SELECT reg_time ". + " FROM " . $GLOBALS['ecs'] ->table('users'). + " WHERE user_id = '$user_id' LIMIT 1"; + $reg_time = $GLOBALS['db']->getOne($sql); + + $hash = substr(md5($user_id . $GLOBALS['_CFG']['hash_code'] . $reg_time), 16, 4); + + return base64_encode($user_id . ',' . $hash); + } + else + { + $hash = base64_decode(trim($key)); + $row = explode(',', $hash); + if (count($row) != 2) + { + return 0; + } + $user_id = intval($row[0]); + $salt = trim($row[1]); + + if ($user_id <= 0 || strlen($salt) != 4) + { + return 0; + } + + $sql = "SELECT reg_time ". + " FROM " . $GLOBALS['ecs'] ->table('users'). + " WHERE user_id = '$user_id' LIMIT 1"; + $reg_time = $GLOBALS['db']->getOne($sql); + + $pre_salt = substr(md5($user_id . $GLOBALS['_CFG']['hash_code'] . $reg_time), 16, 4); + + if ($pre_salt == $salt) + { + return $user_id; + } + else + { + return 0; + } + } +} + +/** + * 判断超级管理员用户名是否存在 + * @param string $adminname 超级管理员用户名 + * @return boolean + */ +function admin_registered( $adminname ) +{ + $res = $GLOBALS['db']->getOne("SELECT COUNT(*) FROM " . $GLOBALS['ecs']->table('admin_user') . + " WHERE user_name = '$adminname'"); + return $res; +} + +?> \ No newline at end of file diff --git a/includes/lib_payment.php b/includes/lib_payment.php new file mode 100644 index 0000000..6c6e2b0 --- /dev/null +++ b/includes/lib_payment.php @@ -0,0 +1,287 @@ +url() . 'respond.php?code=' . $code; +} + +/** + * 取得某支付方式信息 + * @param string $code 支付方式代码 + */ +function get_payment($code) +{ + $sql = 'SELECT * FROM ' . $GLOBALS['ecs']->table('payment'). + " WHERE pay_code = '$code' AND enabled = '1'"; + $payment = $GLOBALS['db']->getRow($sql); + + if ($payment) + { + $config_list = unserialize($payment['pay_config']); + + foreach ($config_list AS $config) + { + $payment[$config['name']] = $config['value']; + } + } + + return $payment; +} + +/** + * 通过订单sn取得订单ID + * @param string $order_sn 订单sn + * @param blob $voucher 是否为会员充值 + */ +function get_order_id_by_sn($order_sn, $voucher = 'false') +{ + if ($voucher == 'true') + { + if(is_numeric($order_sn)) + { + return $GLOBALS['db']->getOne("SELECT log_id FROM " . $GLOBALS['ecs']->table('pay_log') . " WHERE order_id=" . $order_sn . ' AND order_type=1'); + } + else + { + return ""; + } + } + else + { + if(is_numeric($order_sn)) + { + $sql = 'SELECT order_id FROM ' . $GLOBALS['ecs']->table('order_info'). " WHERE order_sn = '$order_sn'"; + $order_id = $GLOBALS['db']->getOne($sql); + } + if (!empty($order_id)) + { + $pay_log_id = $GLOBALS['db']->getOne("SELECT log_id FROM " . $GLOBALS['ecs']->table('pay_log') . " WHERE order_id='" . $order_id . "'"); + return $pay_log_id; + } + else + { + return ""; + } + } +} + +/** + * 通过订单ID取得订单商品名称 + * @param string $order_id 订单ID + */ +function get_goods_name_by_id($order_id) +{ + $sql = 'SELECT goods_name FROM ' . $GLOBALS['ecs']->table('order_goods'). " WHERE order_id = '$order_id'"; + $goods_name = $GLOBALS['db']->getCol($sql); + return implode(',', $goods_name); +} + +/** + * 检查支付的金额是否与订单相符 + * + * @access public + * @param string $log_id 支付编号 + * @param float $money 支付接口返回的金额 + * @return true + */ +function check_money($log_id, $money) +{ + $sql = 'SELECT order_amount FROM ' . $GLOBALS['ecs']->table('pay_log') . + " WHERE log_id = '$log_id'"; + $amount = $GLOBALS['db']->getOne($sql); + + if ($money == $amount) + { + return true; + } + else + { + return false; + } +} + +/** + * 修改订单的支付状态 + * + * @access public + * @param string $log_id 支付编号 + * @param integer $pay_status 状态 + * @param string $note 备注 + * @return void + */ +function order_paid($log_id, $pay_status = PS_PAYED, $note = '') +{ + /* 取得支付编号 */ + $log_id = intval($log_id); + if ($log_id > 0) + { + /* 取得要修改的支付记录信息 */ + $sql = "SELECT * FROM " . $GLOBALS['ecs']->table('pay_log') . + " WHERE log_id = '$log_id'"; + $pay_log = $GLOBALS['db']->getRow($sql); + if ($pay_log && $pay_log['is_paid'] == 0) + { + /* 修改此次支付操作的状态为已付款 */ + $sql = 'UPDATE ' . $GLOBALS['ecs']->table('pay_log') . + " SET is_paid = '1' WHERE log_id = '$log_id'"; + $GLOBALS['db']->query($sql); + + /* 根据记录类型做相应处理 */ + if ($pay_log['order_type'] == PAY_ORDER) + { + /* 取得订单信息 */ + $sql = 'SELECT order_id, user_id, order_sn, consignee, address, tel, shipping_id, extension_code, extension_id, goods_amount ' . + 'FROM ' . $GLOBALS['ecs']->table('order_info') . + " WHERE order_id = '$pay_log[order_id]'"; + $order = $GLOBALS['db']->getRow($sql); + $order_id = $order['order_id']; + $order_sn = $order['order_sn']; + + /* 修改订单状态为已付款 */ + $sql = 'UPDATE ' . $GLOBALS['ecs']->table('order_info') . + " SET order_status = '" . OS_CONFIRMED . "', " . + " confirm_time = '" . gmtime() . "', " . + " pay_status = '$pay_status', " . + " pay_time = '".gmtime()."', " . + " money_paid = order_amount," . + " order_amount = 0 ". + "WHERE order_id = '$order_id'"; + $GLOBALS['db']->query($sql); + + /* 记录订单操作记录 */ + order_action($order_sn, OS_CONFIRMED, SS_UNSHIPPED, $pay_status, $note, $GLOBALS['_LANG']['buyer']); + + /* 如果需要,发短信 */ + if ($GLOBALS['_CFG']['sms_order_payed'] == '1' && $GLOBALS['_CFG']['sms_shop_mobile'] != '') + { + include_once(ROOT_PATH.'includes/cls_sms.php'); + $sms = new sms(); + $sms->send($GLOBALS['_CFG']['sms_shop_mobile'], + sprintf($GLOBALS['_LANG']['order_payed_sms'], $order_sn, $order['consignee'], $order['tel']),'', 13,1); + } + + /* 对虚拟商品的支持 */ + $virtual_goods = get_virtual_goods($order_id); + if (!empty($virtual_goods)) + { + $msg = ''; + if (!virtual_goods_ship($virtual_goods, $msg, $order_sn, true)) + { + $GLOBALS['_LANG']['pay_success'] .= '
    '.$msg.'
    '.$GLOBALS['_LANG']['virtual_goods_ship_fail']; + } + + /* 如果订单没有配送方式,自动完成发货操作 */ + if ($order['shipping_id'] == -1) + { + /* 将订单标识为已发货状态,并记录发货记录 */ + $sql = 'UPDATE ' . $GLOBALS['ecs']->table('order_info') . + " SET shipping_status = '" . SS_SHIPPED . "', shipping_time = '" . gmtime() . "'" . + " WHERE order_id = '$order_id'"; + $GLOBALS['db']->query($sql); + + /* 记录订单操作记录 */ + order_action($order_sn, OS_CONFIRMED, SS_SHIPPED, $pay_status, $note, $GLOBALS['_LANG']['buyer']); + $integral = integral_to_give($order); + log_account_change($order['user_id'], 0, 0, intval($integral['rank_points']), intval($integral['custom_points']), sprintf($GLOBALS['_LANG']['order_gift_integral'], $order['order_sn'])); + } + } + + } + elseif ($pay_log['order_type'] == PAY_SURPLUS) + { + $sql = 'SELECT `id` FROM ' . $GLOBALS['ecs']->table('user_account') . " WHERE `id` = '$pay_log[order_id]' AND `is_paid` = 1 LIMIT 1"; + $res_id=$GLOBALS['db']->getOne($sql); + if(empty($res_id)) + { + /* 更新会员预付款的到款状态 */ + $sql = 'UPDATE ' . $GLOBALS['ecs']->table('user_account') . + " SET paid_time = '" .gmtime(). "', is_paid = 1" . + " WHERE id = '$pay_log[order_id]' LIMIT 1"; + $GLOBALS['db']->query($sql); + + /* 取得添加预付款的用户以及金额 */ + $sql = "SELECT user_id, amount FROM " . $GLOBALS['ecs']->table('user_account') . + " WHERE id = '$pay_log[order_id]'"; + $arr = $GLOBALS['db']->getRow($sql); + + /* 修改会员帐户金额 */ + $_LANG = array(); + include_once(ROOT_PATH . 'languages/' . $GLOBALS['_CFG']['lang'] . '/user.php'); + log_account_change($arr['user_id'], $arr['amount'], 0, 0, 0, $_LANG['surplus_type_0'], ACT_SAVING); + } + } + } + else + { + /* 取得已发货的虚拟商品信息 */ + $post_virtual_goods = get_virtual_goods($pay_log['order_id'], true); + + /* 有已发货的虚拟商品 */ + if (!empty($post_virtual_goods)) + { + $msg = ''; + /* 检查两次刷新时间有无超过12小时 */ + $sql = 'SELECT pay_time, order_sn FROM ' . $GLOBALS['ecs']->table('order_info') . " WHERE order_id = '$pay_log[order_id]'"; + $row = $GLOBALS['db']->getRow($sql); + $intval_time = gmtime() - $row['pay_time']; + if ($intval_time >= 0 && $intval_time < 3600 * 12) + { + $virtual_card = array(); + foreach ($post_virtual_goods as $code => $goods_list) + { + /* 只处理虚拟卡 */ + if ($code == 'virtual_card') + { + foreach ($goods_list as $goods) + { + if ($info = virtual_card_result($row['order_sn'], $goods)) + { + $virtual_card[] = array('goods_id'=>$goods['goods_id'], 'goods_name'=>$goods['goods_name'], 'info'=>$info); + } + } + + $GLOBALS['smarty']->assign('virtual_card', $virtual_card); + } + } + } + else + { + $msg = '
    ' . $GLOBALS['_LANG']['please_view_order_detail'] . '
    '; + } + + $GLOBALS['_LANG']['pay_success'] .= $msg; + } + + /* 取得未发货虚拟商品 */ + $virtual_goods = get_virtual_goods($pay_log['order_id'], false); + if (!empty($virtual_goods)) + { + $GLOBALS['_LANG']['pay_success'] .= '
    ' . $GLOBALS['_LANG']['virtual_goods_ship_fail']; + } + } + } +} + +?> \ No newline at end of file diff --git a/includes/lib_time.php b/includes/lib_time.php new file mode 100644 index 0000000..0bbfa37 --- /dev/null +++ b/includes/lib_time.php @@ -0,0 +1,181 @@ + 0) + { + $time -= date('Z'); + } + + return $time; +} + +/** + * 将一个用户自定义时区的日期转为GMT时间戳 + * + * @access public + * @param string $str + * + * @return integer + */ +function local_strtotime($str) +{ + $timezone = isset($_SESSION['timezone']) ? $_SESSION['timezone'] : $GLOBALS['_CFG']['timezone']; + + /** + * $time = mktime($hour, $minute, $second, $month, $day, $year) - date('Z') + (date('Z') - $timezone * 3600) + * 先用mktime生成时间戳,再减去date('Z')转换为GMT时间,然后修正为用户自定义时间。以下是化简后结果 + **/ + $time = strtotime($str) - $timezone * 3600; + + return $time; + +} + +/** + * 获得用户所在时区指定的时间戳 + * + * @param $timestamp integer 该时间戳必须是一个服务器本地的时间戳 + * + * @return array + */ +function local_gettime($timestamp = NULL) +{ + $tmp = local_getdate($timestamp); + return $tmp[0]; +} + +/** + * 获得用户所在时区指定的日期和时间信息 + * + * @param $timestamp integer 该时间戳必须是一个服务器本地的时间戳 + * + * @return array + */ +function local_getdate($timestamp = NULL) +{ + $timezone = isset($_SESSION['timezone']) ? $_SESSION['timezone'] : $GLOBALS['_CFG']['timezone']; + + /* 如果时间戳为空,则获得服务器的当前时间 */ + if ($timestamp === NULL) + { + $timestamp = time(); + } + + $gmt = $timestamp - date('Z'); // 得到该时间的格林威治时间 + $local_time = $gmt + ($timezone * 3600); // 转换为用户所在时区的时间戳 + + return getdate($local_time); +} + +?> \ No newline at end of file diff --git a/includes/lib_transaction.php b/includes/lib_transaction.php new file mode 100644 index 0000000..01982fe --- /dev/null +++ b/includes/lib_transaction.php @@ -0,0 +1,1165 @@ +add($GLOBALS['_LANG']['not_login']); + + return false; + } + + $cfg = array(); + $cfg['username'] = $GLOBALS['db']->getOne("SELECT user_name FROM " . $GLOBALS['ecs']->table('users') . " WHERE user_id='" . $profile['user_id'] . "'"); + if (isset($profile['sex'])) + { + $cfg['gender'] = intval($profile['sex']); + } + if (!empty($profile['email'])) + { + if (!is_email($profile['email'])) + { + $GLOBALS['err']->add(sprintf($GLOBALS['_LANG']['email_invalid'], $profile['email'])); + + return false; + } + $cfg['email'] = $profile['email']; + } + if (!empty($profile['birthday'])) + { + $cfg['bday'] = $profile['birthday']; + } + + + if (!$GLOBALS['user']->edit_user($cfg)) + { + if ($GLOBALS['user']->error == ERR_EMAIL_EXISTS) + { + $GLOBALS['err']->add(sprintf($GLOBALS['_LANG']['email_exist'], $profile['email'])); + } + else + { + $GLOBALS['err']->add('DB ERROR!'); + } + + return false; + } + + /* 过滤非法的键值 */ + $other_key_array = array('msn', 'qq', 'office_phone', 'home_phone', 'mobile_phone'); + foreach ($profile['other'] as $key => $val) + { + //删除非法key值 + if (!in_array($key, $other_key_array)) + { + unset($profile['other'][$key]); + } + else + { + $profile['other'][$key] = htmlspecialchars(trim($val)); //防止用户输入javascript代码 + } + } + /* 修改在其他资料 */ + if (!empty($profile['other'])) + { + $GLOBALS['db']->autoExecute($GLOBALS['ecs']->table('users'), $profile['other'], 'UPDATE', "user_id = '$profile[user_id]'"); + } + + return true; +} + +/** + * 获取用户帐号信息 + * + * @access public + * @param int $user_id 用户user_id + * + * @return void + */ +function get_profile($user_id) +{ + global $user; + + + /* 会员帐号信息 */ + $info = array(); + $infos = array(); + $sql = "SELECT user_name, birthday, sex, question, answer, rank_points, pay_points,user_money, user_rank,". + " msn, qq, office_phone, home_phone, mobile_phone, passwd_question, passwd_answer ". + "FROM " .$GLOBALS['ecs']->table('users') . " WHERE user_id = '$user_id'"; + $infos = $GLOBALS['db']->getRow($sql); + $infos['user_name'] = addslashes($infos['user_name']); + + $row = $user->get_profile_by_name($infos['user_name']); //获取用户帐号信息 + $_SESSION['email'] = $row['email']; //注册SESSION + + /* 会员等级 */ + if ($infos['user_rank'] > 0) + { + $sql = "SELECT rank_id, rank_name, discount FROM ".$GLOBALS['ecs']->table('user_rank') . + " WHERE rank_id = '$infos[user_rank]'"; + } + else + { + $sql = "SELECT rank_id, rank_name, discount, min_points". + " FROM ".$GLOBALS['ecs']->table('user_rank') . + " WHERE min_points<= " . intval($infos['rank_points']) . " ORDER BY min_points DESC"; + } + + if ($row = $GLOBALS['db']->getRow($sql)) + { + $info['rank_name'] = $row['rank_name']; + } + else + { + $info['rank_name'] = $GLOBALS['_LANG']['undifine_rank']; + } + + $cur_date = date('Y-m-d H:i:s'); + + /* 会员红包 */ + $bonus = array(); + $sql = "SELECT type_name, type_money ". + "FROM " .$GLOBALS['ecs']->table('bonus_type') . " AS t1, " .$GLOBALS['ecs']->table('user_bonus') . " AS t2 ". + "WHERE t1.type_id = t2.bonus_type_id AND t2.user_id = '$user_id' AND t1.use_start_date <= '$cur_date' ". + "AND t1.use_end_date > '$cur_date' AND t2.order_id = 0"; + $bonus = $GLOBALS['db']->getAll($sql); + if ($bonus) + { + for ($i = 0, $count = count($bonus); $i < $count; $i++) + { + $bonus[$i]['type_money'] = price_format($bonus[$i]['type_money'], false); + } + } + + $info['discount'] = $_SESSION['discount'] * 100 . "%"; + $info['email'] = $_SESSION['email']; + $info['user_name'] = $_SESSION['user_name']; + $info['rank_points'] = isset($infos['rank_points']) ? $infos['rank_points'] : ''; + $info['pay_points'] = isset($infos['pay_points']) ? $infos['pay_points'] : 0; + $info['user_money'] = isset($infos['user_money']) ? $infos['user_money'] : 0; + $info['sex'] = isset($infos['sex']) ? $infos['sex'] : 0; + $info['birthday'] = isset($infos['birthday']) ? $infos['birthday'] : ''; + $info['question'] = isset($infos['question']) ? htmlspecialchars($infos['question']) : ''; + + $info['user_money'] = price_format($info['user_money'], false); + $info['pay_points'] = $info['pay_points'] . $GLOBALS['_CFG']['integral_name']; + $info['bonus'] = $bonus; + $info['qq'] = $infos['qq']; + $info['msn'] = $infos['msn']; + $info['office_phone']= $infos['office_phone']; + $info['home_phone'] = $infos['home_phone']; + $info['mobile_phone'] = $infos['mobile_phone']; + $info['passwd_question'] = $infos['passwd_question']; + $info['passwd_answer'] = $infos['passwd_answer']; + + return $info; +} + +/** + * 取得收货人地址列表 + * @param int $user_id 用户编号 + * @return array + */ +function get_consignee_list($user_id) +{ + $sql = "SELECT * FROM " . $GLOBALS['ecs']->table('user_address') . + " WHERE user_id = '$user_id' LIMIT 5"; + + return $GLOBALS['db']->getAll($sql); +} + +/** + * 给指定用户添加一个指定红包 + * + * @access public + * @param int $user_id 用户ID + * @param string $bouns_sn 红包序列号 + * + * @return boolen $result + */ +function add_bonus($user_id, $bouns_sn) +{ + if (empty($user_id)) + { + $GLOBALS['err']->add($GLOBALS['_LANG']['not_login']); + + return false; + } + + /* 查询红包序列号是否已经存在 */ + $sql = "SELECT bonus_id, bonus_sn, user_id, bonus_type_id FROM " .$GLOBALS['ecs']->table('user_bonus') . + " WHERE bonus_sn = '$bouns_sn'"; + $row = $GLOBALS['db']->getRow($sql); + if ($row) + { + if ($row['user_id'] == 0) + { + //红包没有被使用 + $sql = "SELECT send_end_date, use_end_date ". + " FROM " . $GLOBALS['ecs']->table('bonus_type') . + " WHERE type_id = '" . $row['bonus_type_id'] . "'"; + + $bonus_time = $GLOBALS['db']->getRow($sql); + + $now = gmtime(); + if ($now > $bonus_time['use_end_date']) + { + $GLOBALS['err']->add($GLOBALS['_LANG']['bonus_use_expire']); + return false; + } + + $sql = "UPDATE " .$GLOBALS['ecs']->table('user_bonus') . " SET user_id = '$user_id' ". + "WHERE bonus_id = '$row[bonus_id]'"; + $result = $GLOBALS['db'] ->query($sql); + if ($result) + { + return true; + } + else + { + return $GLOBALS['db']->errorMsg(); + } + } + else + { + if ($row['user_id']== $user_id) + { + //红包已经添加过了。 + $GLOBALS['err']->add($GLOBALS['_LANG']['bonus_is_used']); + } + else + { + //红包被其他人使用过了。 + $GLOBALS['err']->add($GLOBALS['_LANG']['bonus_is_used_by_other']); + } + + return false; + } + } + else + { + //红包不存在 + $GLOBALS['err']->add($GLOBALS['_LANG']['bonus_not_exist']); + return false; + } + +} + +/** + * 获取用户指定范围的订单列表 + * + * @access public + * @param int $user_id 用户ID号 + * @param int $num 列表最大数量 + * @param int $start 列表起始位置 + * @return array $order_list 订单列表 + */ +function get_user_orders($user_id, $num = 10, $start = 0) +{ + /* 取得订单列表 */ + $arr = array(); + + $sql = "SELECT order_id, order_sn, order_status, shipping_status, pay_status, add_time, " . + "(goods_amount + shipping_fee + insure_fee + pay_fee + pack_fee + card_fee + tax - discount) AS total_fee ". + " FROM " .$GLOBALS['ecs']->table('order_info') . + " WHERE user_id = '$user_id' ORDER BY add_time DESC"; + $res = $GLOBALS['db']->SelectLimit($sql, $num, $start); + + while ($row = $GLOBALS['db']->fetchRow($res)) + { + if ($row['order_status'] == OS_UNCONFIRMED) + { + $row['handler'] = "".$GLOBALS['_LANG']['cancel'].""; + } + else if ($row['order_status'] == OS_SPLITED) + { + /* 对配送状态的处理 */ + if ($row['shipping_status'] == SS_SHIPPED) + { + @$row['handler'] = "".$GLOBALS['_LANG']['received'].""; + } + elseif ($row['shipping_status'] == SS_RECEIVED) + { + @$row['handler'] = ''.$GLOBALS['_LANG']['ss_received'] .''; + } + else + { + if ($row['pay_status'] == PS_UNPAYED) + { + @$row['handler'] = "' .$GLOBALS['_LANG']['pay_money']. ''; + } + else + { + @$row['handler'] = "' .$GLOBALS['_LANG']['view_order']. ''; + } + + } + } + else + { + $row['handler'] = ''.$GLOBALS['_LANG']['os'][$row['order_status']] .''; + } + + $row['shipping_status'] = ($row['shipping_status'] == SS_SHIPPED_ING) ? SS_PREPARING : $row['shipping_status']; + $row['order_status'] = $GLOBALS['_LANG']['os'][$row['order_status']] . ',' . $GLOBALS['_LANG']['ps'][$row['pay_status']] . ',' . $GLOBALS['_LANG']['ss'][$row['shipping_status']]; + + $arr[] = array('order_id' => $row['order_id'], + 'order_sn' => $row['order_sn'], + 'order_time' => local_date($GLOBALS['_CFG']['time_format'], $row['add_time']), + 'order_status' => $row['order_status'], + 'total_fee' => price_format($row['total_fee'], false), + 'handler' => $row['handler']); + } + + return $arr; +} + +/** + * 取消一个用户订单 + * + * @access public + * @param int $order_id 订单ID + * @param int $user_id 用户ID + * + * @return void + */ +function cancel_order($order_id, $user_id = 0) +{ + /* 查询订单信息,检查状态 */ + $sql = "SELECT user_id, order_id, order_sn , surplus , integral , bonus_id, order_status, shipping_status, pay_status FROM " .$GLOBALS['ecs']->table('order_info') ." WHERE order_id = '$order_id'"; + $order = $GLOBALS['db']->GetRow($sql); + + if (empty($order)) + { + $GLOBALS['err']->add($GLOBALS['_LANG']['order_exist']); + return false; + } + + // 如果用户ID大于0,检查订单是否属于该用户 + if ($user_id > 0 && $order['user_id'] != $user_id) + { + $GLOBALS['err'] ->add($GLOBALS['_LANG']['no_priv']); + + return false; + } + + // 订单状态只能是“未确认”或“已确认” + if ($order['order_status'] != OS_UNCONFIRMED && $order['order_status'] != OS_CONFIRMED) + { + $GLOBALS['err']->add($GLOBALS['_LANG']['current_os_not_unconfirmed']); + + return false; + } + + //订单一旦确认,不允许用户取消 + if ( $order['order_status'] == OS_CONFIRMED) + { + $GLOBALS['err']->add($GLOBALS['_LANG']['current_os_already_confirmed']); + + return false; + } + + // 发货状态只能是“未发货” + if ($order['shipping_status'] != SS_UNSHIPPED) + { + $GLOBALS['err']->add($GLOBALS['_LANG']['current_ss_not_cancel']); + + return false; + } + + // 如果付款状态是“已付款”、“付款中”,不允许取消,要取消和商家联系 + if ($order['pay_status'] != PS_UNPAYED) + { + $GLOBALS['err']->add($GLOBALS['_LANG']['current_ps_not_cancel']); + + return false; + } + + //将用户订单设置为取消 + $sql = "UPDATE ".$GLOBALS['ecs']->table('order_info') ." SET order_status = '".OS_CANCELED."' WHERE order_id = '$order_id'"; + if ($GLOBALS['db']->query($sql)) + { + /* 记录log */ + order_action($order['order_sn'], OS_CANCELED, $order['shipping_status'], PS_UNPAYED,$GLOBALS['_LANG']['buyer_cancel'],'buyer'); + /* 退货用户余额、积分、红包 */ + if ($order['user_id'] > 0 && $order['surplus'] > 0) + { + $change_desc = sprintf($GLOBALS['_LANG']['return_surplus_on_cancel'], $order['order_sn']); + log_account_change($order['user_id'], $order['surplus'], 0, 0, 0, $change_desc); + } + if ($order['user_id'] > 0 && $order['integral'] > 0) + { + $change_desc = sprintf($GLOBALS['_LANG']['return_integral_on_cancel'], $order['order_sn']); + log_account_change($order['user_id'], 0, 0, 0, $order['integral'], $change_desc); + } + if ($order['user_id'] > 0 && $order['bonus_id'] > 0) + { + change_user_bonus($order['bonus_id'], $order['order_id'], false); + } + + /* 如果使用库存,且下订单时减库存,则增加库存 */ + if ($GLOBALS['_CFG']['use_storage'] == '1' && $GLOBALS['_CFG']['stock_dec_time'] == SDT_PLACE) + { + change_order_goods_storage($order['order_id'], false, 1); + } + + /* 修改订单 */ + $arr = array( + 'bonus_id' => 0, + 'bonus' => 0, + 'integral' => 0, + 'integral_money' => 0, + 'surplus' => 0 + ); + update_order($order['order_id'], $arr); + + return true; + } + else + { + die($GLOBALS['db']->errorMsg()); + } + +} + +/** + * 确认一个用户订单 + * + * @access public + * @param int $order_id 订单ID + * @param int $user_id 用户ID + * + * @return bool $bool + */ +function affirm_received($order_id, $user_id = 0) +{ + /* 查询订单信息,检查状态 */ + $sql = "SELECT user_id, order_sn , order_status, shipping_status, pay_status FROM ".$GLOBALS['ecs']->table('order_info') ." WHERE order_id = '$order_id'"; + + $order = $GLOBALS['db']->GetRow($sql); + + // 如果用户ID大于 0 。检查订单是否属于该用户 + if ($user_id > 0 && $order['user_id'] != $user_id) + { + $GLOBALS['err'] -> add($GLOBALS['_LANG']['no_priv']); + + return false; + } + /* 检查订单 */ + elseif ($order['shipping_status'] == SS_RECEIVED) + { + $GLOBALS['err'] ->add($GLOBALS['_LANG']['order_already_received']); + + return false; + } + elseif ($order['shipping_status'] != SS_SHIPPED) + { + $GLOBALS['err']->add($GLOBALS['_LANG']['order_invalid']); + + return false; + } + /* 修改订单发货状态为“确认收货” */ + else + { + $sql = "UPDATE " . $GLOBALS['ecs']->table('order_info') . " SET shipping_status = '" . SS_RECEIVED . "' WHERE order_id = '$order_id'"; + if ($GLOBALS['db']->query($sql)) + { + /* 记录日志 */ + order_action($order['order_sn'], $order['order_status'], SS_RECEIVED, $order['pay_status'], '', $GLOBALS['_LANG']['buyer']); + + return true; + } + else + { + die($GLOBALS['db']->errorMsg()); + } + } + +} + +/** + * 保存用户的收货人信息 + * 如果收货人信息中的 id 为 0 则新增一个收货人信息 + * + * @access public + * @param array $consignee + * @param boolean $default 是否将该收货人信息设置为默认收货人信息 + * @return boolean + */ +function save_consignee($consignee, $default=false) +{ + if ($consignee['address_id'] > 0) + { + /* 修改地址 */ + $res = $GLOBALS['db']->autoExecute($GLOBALS['ecs']->table('user_address'), $consignee, 'UPDATE', 'address_id = ' . $consignee['address_id']); + } + else + { + /* 添加地址 */ + $res = $GLOBALS['db']->autoExecute($GLOBALS['ecs']->table('user_address'), $consignee, 'INSERT'); + $consignee['address_id'] = $GLOBALS['db']->insert_id(); + } + + if ($default) + { + /* 保存为用户的默认收货地址 */ + $sql = "UPDATE " . $GLOBALS['ecs']->table('users') . + " SET address_id = '$consignee[address_id]' WHERE user_id = '$_SESSION[user_id]'"; + + $res = $GLOBALS['db']->query($sql); + } + + return $res !== false; +} + +/** + * 删除一个收货地址 + * + * @access public + * @param integer $id + * @return boolean + */ +function drop_consignee($id) +{ + $sql = "SELECT user_id FROM " .$GLOBALS['ecs']->table('user_address') . " WHERE address_id = '$id'"; + $uid = $GLOBALS['db']->getOne($sql); + + if ($uid != $_SESSION['user_id']) + { + return false; + } + else + { + $sql = "DELETE FROM " .$GLOBALS['ecs']->table('user_address') . " WHERE address_id = '$id'"; + $res = $GLOBALS['db']->query($sql); + + return $res; + } +} + +/** + * 添加或更新指定用户收货地址 + * + * @access public + * @param array $address + * @return bool + */ +function update_address($address) +{ + $address_id = intval($address['address_id']); + unset($address['address_id']); + + if ($address_id > 0) + { + /* 更新指定记录 */ + $GLOBALS['db']->autoExecute($GLOBALS['ecs']->table('user_address'), $address, 'UPDATE', 'address_id = ' .$address_id . ' AND user_id = ' . $address['user_id']); + } + else + { + /* 插入一条新记录 */ + $GLOBALS['db']->autoExecute($GLOBALS['ecs']->table('user_address'), $address, 'INSERT'); + $address_id = $GLOBALS['db']->insert_id(); + } + + if (isset($address['defalut']) && $address['default'] > 0 && isset($address['user_id'])) + { + $sql = "UPDATE ".$GLOBALS['ecs']->table('users') . + " SET address_id = '".$address_id."' ". + " WHERE user_id = '" .$address['user_id']. "'"; + $GLOBALS['db'] ->query($sql); + } + + return true; +} + +/** + * 获取指订单的详情 + * + * @access public + * @param int $order_id 订单ID + * @param int $user_id 用户ID + * + * @return arr $order 订单所有信息的数组 + */ +function get_order_detail($order_id, $user_id = 0) +{ + include_once(ROOT_PATH . 'includes/lib_order.php'); + + $order_id = intval($order_id); + if ($order_id <= 0) + { + $GLOBALS['err']->add($GLOBALS['_LANG']['invalid_order_id']); + + return false; + } + $order = order_info($order_id); + + //检查订单是否属于该用户 + if ($user_id > 0 && $user_id != $order['user_id']) + { + $GLOBALS['err']->add($GLOBALS['_LANG']['no_priv']); + + return false; + } + + /* 对发货号处理 */ + if (!empty($order['invoice_no'])) + { + $shipping_code = $GLOBALS['db']->GetOne("SELECT shipping_code FROM ".$GLOBALS['ecs']->table('shipping') ." WHERE shipping_id = '$order[shipping_id]'"); + $plugin = ROOT_PATH.'includes/modules/shipping/'. $shipping_code. '.php'; + if (file_exists($plugin)) + { + include_once($plugin); + $shipping = new $shipping_code; + $order['invoice_no'] = $shipping->query($order['invoice_no']); + } + } + + /* 只有未确认才允许用户修改订单地址 */ + if ($order['order_status'] == OS_UNCONFIRMED) + { + $order['allow_update_address'] = 1; //允许修改收货地址 + } + else + { + $order['allow_update_address'] = 0; + } + + /* 获取订单中实体商品数量 */ + $order['exist_real_goods'] = exist_real_goods($order_id); + + /* 如果是未付款状态,生成支付按钮 */ + if ($order['pay_status'] == PS_UNPAYED && + ($order['order_status'] == OS_UNCONFIRMED || + $order['order_status'] == OS_CONFIRMED)) + { + /* + * 在线支付按钮 + */ + //支付方式信息 + $payment_info = array(); + $payment_info = payment_info($order['pay_id']); + + //无效支付方式 + if ($payment_info === false) + { + $order['pay_online'] = ''; + } + else + { + //取得支付信息,生成支付代码 + $payment = unserialize_config($payment_info['pay_config']); + + //获取需要支付的log_id + $order['log_id'] = get_paylog_id($order['order_id'], $pay_type = PAY_ORDER); + $order['user_name'] = $_SESSION['user_name']; + $order['pay_desc'] = $payment_info['pay_desc']; + + /* 调用相应的支付方式文件 */ + include_once(ROOT_PATH . 'includes/modules/payment/' . $payment_info['pay_code'] . '.php'); + + /* 取得在线支付方式的支付按钮 */ + $pay_obj = new $payment_info['pay_code']; + $order['pay_online'] = $pay_obj->get_code($order, $payment); + } + } + else + { + $order['pay_online'] = ''; + } + + /* 无配送时的处理 */ + $order['shipping_id'] == -1 and $order['shipping_name'] = $GLOBALS['_LANG']['shipping_not_need']; + + /* 其他信息初始化 */ + $order['how_oos_name'] = $order['how_oos']; + $order['how_surplus_name'] = $order['how_surplus']; + + /* 虚拟商品付款后处理 */ + if ($order['pay_status'] != PS_UNPAYED) + { + /* 取得已发货的虚拟商品信息 */ + $virtual_goods = get_virtual_goods($order_id, true); + $virtual_card = array(); + foreach ($virtual_goods AS $code => $goods_list) + { + /* 只处理虚拟卡 */ + if ($code == 'virtual_card') + { + foreach ($goods_list as $goods) + { + if ($info = virtual_card_result($order['order_sn'], $goods)) + { + $virtual_card[] = array('goods_id'=>$goods['goods_id'], 'goods_name'=>$goods['goods_name'], 'info'=>$info); + } + } + } + /* 处理超值礼包里面的虚拟卡 */ + if ($code == 'package_buy') + { + foreach ($goods_list as $goods) + { + $sql = 'SELECT g.goods_id FROM ' . $GLOBALS['ecs']->table('package_goods') . ' AS pg, ' . $GLOBALS['ecs']->table('goods') . ' AS g ' . + "WHERE pg.goods_id = g.goods_id AND pg.package_id = '" . $goods['goods_id'] . "' AND extension_code = 'virtual_card'"; + $vcard_arr = $GLOBALS['db']->getAll($sql); + + foreach ($vcard_arr AS $val) + { + if ($info = virtual_card_result($order['order_sn'], $val)) + { + $virtual_card[] = array('goods_id'=>$goods['goods_id'], 'goods_name'=>$goods['goods_name'], 'info'=>$info); + } + } + } + } + } + $var_card = deleteRepeat($virtual_card); + $GLOBALS['smarty']->assign('virtual_card', $var_card); + } + + /* 确认时间 支付时间 发货时间 */ + if ($order['confirm_time'] > 0 && ($order['order_status'] == OS_CONFIRMED || $order['order_status'] == OS_SPLITED || $order['order_status'] == OS_SPLITING_PART)) + { + $order['confirm_time'] = sprintf($GLOBALS['_LANG']['confirm_time'], local_date($GLOBALS['_CFG']['time_format'], $order['confirm_time'])); + } + else + { + $order['confirm_time'] = ''; + } + if ($order['pay_time'] > 0 && $order['pay_status'] != PS_UNPAYED) + { + $order['pay_time'] = sprintf($GLOBALS['_LANG']['pay_time'], local_date($GLOBALS['_CFG']['time_format'], $order['pay_time'])); + } + else + { + $order['pay_time'] = ''; + } + if ($order['shipping_time'] > 0 && in_array($order['shipping_status'], array(SS_SHIPPED, SS_RECEIVED))) + { + $order['shipping_time'] = sprintf($GLOBALS['_LANG']['shipping_time'], local_date($GLOBALS['_CFG']['time_format'], $order['shipping_time'])); + } + else + { + $order['shipping_time'] = ''; + } + + return $order; + +} + +/** + * 获取用户可以和并的订单数组 + * + * @access public + * @param int $user_id 用户ID + * + * @return array $merge 可合并订单数组 + */ +function get_user_merge($user_id) +{ + include_once(ROOT_PATH . 'includes/lib_order.php'); + $sql = "SELECT order_sn FROM ".$GLOBALS['ecs']->table('order_info') . + " WHERE user_id = '$user_id' " . order_query_sql('unprocessed') . + "AND extension_code = '' ". + " ORDER BY add_time DESC"; + $list = $GLOBALS['db']->GetCol($sql); + + $merge = array(); + foreach ($list as $val) + { + $merge[$val] = $val; + } + + return $merge; +} + +/** + * 合并指定用户订单 + * + * @access public + * @param string $from_order 合并的从订单号 + * @param string $to_order 合并的主订单号 + * + * @return boolen $bool + */ +function merge_user_order($from_order, $to_order, $user_id = 0) +{ + if ($user_id > 0) + { + /* 检查订单是否属于指定用户 */ + if (strlen($to_order) > 0) + { + $sql = "SELECT user_id FROM " .$GLOBALS['ecs']->table('order_info'). + " WHERE order_sn = '$to_order'"; + $order_user = $GLOBALS['db']->getOne($sql); + if ($order_user != $user_id) + { + $GLOBALS['err']->add($GLOBALS['_LANG']['no_priv']); + } + } + else + { + $GLOBALS['err']->add($GLOBALS['_LANG']['order_sn_empty']); + return false; + } + } + + $result = merge_order($from_order, $to_order); + if ($result === true) + { + return true; + } + else + { + $GLOBALS['err']->add($result); + return false; + } +} + +/** + * 将指定订单中的商品添加到购物车 + * + * @access public + * @param int $order_id + * + * @return mix $message 成功返回true, 错误返回出错信息 + */ +function return_to_cart($order_id) +{ + /* 初始化基本件数量 goods_id => goods_number */ + $basic_number = array(); + + /* 查订单商品:不考虑赠品 */ + $sql = "SELECT goods_id, product_id,goods_number, goods_attr, parent_id, goods_attr_id" . + " FROM " . $GLOBALS['ecs']->table('order_goods') . + " WHERE order_id = '$order_id' AND is_gift = 0 AND extension_code <> 'package_buy'" . + " ORDER BY parent_id ASC"; + $res = $GLOBALS['db']->query($sql); + + $time = gmtime(); + while ($row = $GLOBALS['db']->fetchRow($res)) + { + // 查该商品信息:是否删除、是否上架 + + $sql = "SELECT goods_sn, goods_name, goods_number, market_price, " . + "IF(is_promote = 1 AND '$time' BETWEEN promote_start_date AND promote_end_date, promote_price, shop_price) AS goods_price," . + "is_real, extension_code, is_alone_sale, goods_type " . + "FROM " . $GLOBALS['ecs']->table('goods') . + " WHERE goods_id = '$row[goods_id]' " . + " AND is_delete = 0 LIMIT 1"; + $goods = $GLOBALS['db']->getRow($sql); + + // 如果该商品不存在,处理下一个商品 + if (empty($goods)) + { + continue; + } + if($row['product_id']) + { + $order_goods_product_id=$row['product_id']; + $sql="SELECT product_number from ".$GLOBALS['ecs']->table('products')."where product_id='$order_goods_product_id'"; + $product_number=$GLOBALS['db']->getOne($sql); + } + // 如果使用库存,且库存不足,修改数量 + if ($GLOBALS['_CFG']['use_storage'] == 1 && ($row['product_id']?($product_number<$row['goods_number']):($goods['goods_number'] < $row['goods_number']))) + { + if ($goods['goods_number'] == 0 || $product_number=== 0) + { + // 如果库存为0,处理下一个商品 + continue; + } + else + { + if($row['product_id']) + { + $row['goods_number']=$product_number; + } + else + { + // 库存不为0,修改数量 + $row['goods_number'] = $goods['goods_number']; + } + } + } + + //检查商品价格是否有会员价格 + $sql = "SELECT goods_number FROM" . $GLOBALS['ecs']->table('cart') . " " . + "WHERE session_id = '" . SESS_ID . "' " . + "AND goods_id = '" . $row['goods_id'] . "' " . + "AND rec_type = '" . CART_GENERAL_GOODS . "' LIMIT 1"; + $temp_number = $GLOBALS['db']->getOne($sql); + $row['goods_number'] += $temp_number; + + $attr_array = empty($row['goods_attr_id']) ? array() : explode(',', $row['goods_attr_id']); + $goods['goods_price'] = get_final_price($row['goods_id'], $row['goods_number'], true, $attr_array); + + // 要返回购物车的商品 + $return_goods = array( + 'goods_id' => $row['goods_id'], + 'goods_sn' => addslashes($goods['goods_sn']), + 'goods_name' => addslashes($goods['goods_name']), + 'market_price' => $goods['market_price'], + 'goods_price' => $goods['goods_price'], + 'goods_number' => $row['goods_number'], + 'goods_attr' => empty($row['goods_attr']) ? '' : addslashes($row['goods_attr']), + 'goods_attr_id' => empty($row['goods_attr_id']) ? '' : $row['goods_attr_id'], + 'is_real' => $goods['is_real'], + 'extension_code'=> addslashes($goods['extension_code']), + 'parent_id' => '0', + 'is_gift' => '0', + 'rec_type' => CART_GENERAL_GOODS + ); + + // 如果是配件 + if ($row['parent_id'] > 0) + { + // 查询基本件信息:是否删除、是否上架、能否作为普通商品销售 + $sql = "SELECT goods_id " . + "FROM " . $GLOBALS['ecs']->table('goods') . + " WHERE goods_id = '$row[parent_id]' " . + " AND is_delete = 0 AND is_on_sale = 1 AND is_alone_sale = 1 LIMIT 1"; + $parent = $GLOBALS['db']->getRow($sql); + if ($parent) + { + // 如果基本件存在,查询组合关系是否存在 + $sql = "SELECT goods_price " . + "FROM " . $GLOBALS['ecs']->table('group_goods') . + " WHERE parent_id = '$row[parent_id]' " . + " AND goods_id = '$row[goods_id]' LIMIT 1"; + $fitting_price = $GLOBALS['db']->getOne($sql); + if ($fitting_price) + { + // 如果组合关系存在,取配件价格,取基本件数量,改parent_id + $return_goods['parent_id'] = $row['parent_id']; + $return_goods['goods_price'] = $fitting_price; + $return_goods['goods_number'] = $basic_number[$row['parent_id']]; + } + } + } + else + { + // 保存基本件数量 + $basic_number[$row['goods_id']] = $row['goods_number']; + } + + // 返回购物车:看有没有相同商品 + $sql = "SELECT goods_id " . + "FROM " . $GLOBALS['ecs']->table('cart') . + " WHERE session_id = '" . SESS_ID . "' " . + " AND goods_id = '$return_goods[goods_id]' " . + " AND goods_attr = '$return_goods[goods_attr]' " . + " AND parent_id = '$return_goods[parent_id]' " . + " AND is_gift = 0 " . + " AND rec_type = '" . CART_GENERAL_GOODS . "'"; + $cart_goods = $GLOBALS['db']->getOne($sql); + if (empty($cart_goods)) + { + // 没有相同商品,插入 + $return_goods['session_id'] = SESS_ID; + $return_goods['user_id'] = $_SESSION['user_id']; + $GLOBALS['db']->autoExecute($GLOBALS['ecs']->table('cart'), $return_goods, 'INSERT'); + } + else + { + // 有相同商品,修改数量 + $sql = "UPDATE " . $GLOBALS['ecs']->table('cart') . " SET " . + "goods_number = '" . $return_goods['goods_number'] . "' " . + ",goods_price = '" . $return_goods['goods_price'] . "' " . + "WHERE session_id = '" . SESS_ID . "' " . + "AND goods_id = '" . $return_goods['goods_id'] . "' " . + "AND rec_type = '" . CART_GENERAL_GOODS . "' LIMIT 1"; + $GLOBALS['db']->query($sql); + } + } + + // 清空购物车的赠品 + $sql = "DELETE FROM " . $GLOBALS['ecs']->table('cart') . + " WHERE session_id = '" . SESS_ID . "' AND is_gift = 1"; + $GLOBALS['db']->query($sql); + + return true; +} + +/** + * 保存用户收货地址 + * + * @access public + * @param array $address array_keys(consignee string, email string, address string, zipcode string, tel string, mobile stirng, sign_building string, best_time string, order_id int) + * @param int $user_id 用户ID + * + * @return boolen $bool + */ +function save_order_address($address, $user_id) +{ + $GLOBALS['err']->clean(); + /* 数据验证 */ + empty($address['consignee']) and $GLOBALS['err']->add($GLOBALS['_LANG']['consigness_empty']); + empty($address['address']) and $GLOBALS['err']->add($GLOBALS['_LANG']['address_empty']); + $address['order_id'] == 0 and $GLOBALS['err']->add($GLOBALS['_LANG']['order_id_empty']); + if (empty($address['email'])) + { + $GLOBALS['err']->add($GLOBALS['email_empty']); + } + else + { + if (!is_email($address['email'])) + { + $GLOBALS['err']->add(sprintf($GLOBALS['_LANG']['email_invalid'], $address['email'])); + } + } + if ($GLOBALS['err']->error_no > 0) + { + return false; + } + + /* 检查订单状态 */ + $sql = "SELECT user_id, order_status FROM " .$GLOBALS['ecs']->table('order_info'). " WHERE order_id = '" .$address['order_id']. "'"; + $row = $GLOBALS['db']->getRow($sql); + if ($row) + { + if ($user_id > 0 && $user_id != $row['user_id']) + { + $GLOBALS['err']->add($GLOBALS['_LANG']['no_priv']); + return false; + } + if ($row['order_status'] != OS_UNCONFIRMED) + { + $GLOBALS['err']->add($GLOBALS['_LANG']['require_unconfirmed']); + return false; + } + $GLOBALS['db']->autoExecute($GLOBALS['ecs']->table('order_info'), $address, 'UPDATE', "order_id = '$address[order_id]'"); + return true; + } + else + { + /* 订单不存在 */ + $GLOBALS['err']->add($GLOBALS['_LANG']['order_exist']); + return false; + } +} + +/** + * + * @access public + * @param int $user_id 用户ID + * @param int $num 列表显示条数 + * @param int $start 显示起始位置 + * + * @return array $arr 红保列表 + */ +function get_user_bouns_list($user_id, $num = 10, $start = 0) +{ + $sql = "SELECT u.bonus_sn, u.order_id, b.type_name, b.type_money, b.min_goods_amount, b.use_start_date, b.use_end_date ". + " FROM " .$GLOBALS['ecs']->table('user_bonus'). " AS u ,". + $GLOBALS['ecs']->table('bonus_type'). " AS b". + " WHERE u.bonus_type_id = b.type_id AND u.user_id = '" .$user_id. "'"; + $res = $GLOBALS['db']->selectLimit($sql, $num, $start); + $arr = array(); + + $day = getdate(); + $cur_date = local_mktime(23, 59, 59, $day['mon'], $day['mday'], $day['year']); + + while ($row = $GLOBALS['db']->fetchRow($res)) + { + /* 先判断是否被使用,然后判断是否开始或过期 */ + if (empty($row['order_id'])) + { + /* 没有被使用 */ + if ($row['use_start_date'] > $cur_date) + { + $row['status'] = $GLOBALS['_LANG']['not_start']; + } + else if ($row['use_end_date'] < $cur_date) + { + $row['status'] = $GLOBALS['_LANG']['overdue']; + } + else + { + $row['status'] = $GLOBALS['_LANG']['not_use']; + } + } + else + { + $row['status'] = '' .$GLOBALS['_LANG']['had_use']. ''; + } + + $row['use_startdate'] = local_date($GLOBALS['_CFG']['date_format'], $row['use_start_date']); + $row['use_enddate'] = local_date($GLOBALS['_CFG']['date_format'], $row['use_end_date']); + + $arr[] = $row; + } + return $arr; + +} + +/** + * 获得会员的团购活动列表 + * + * @access public + * @param int $user_id 用户ID + * @param int $num 列表显示条数 + * @param int $start 显示起始位置 + * + * @return array $arr 团购活动列表 + */ +function get_user_group_buy($user_id, $num = 10, $start = 0) +{ + return true; +} + + /** + * 获得团购详细信息(团购订单信息) + * + * + */ + function get_group_buy_detail($user_id, $group_buy_id) + { + return true; + } + + /** + * 去除虚拟卡中重复数据 + * + * + */ +function deleteRepeat($array){ + $_card_sn_record = array(); + foreach ($array as $_k => $_v){ + foreach ($_v['info'] as $__k => $__v){ + if (in_array($__v['card_sn'],$_card_sn_record)){ + unset($array[$_k]['info'][$__k]); + } else { + array_push($_card_sn_record,$__v['card_sn']); + } + } + } + return $array; +} +?> \ No newline at end of file diff --git a/includes/lib_uc.php b/includes/lib_uc.php new file mode 100644 index 0000000..d11a6da --- /dev/null +++ b/includes/lib_uc.php @@ -0,0 +1,137 @@ +getAll("SELECT g.goods_id, g.goods_name, g.goods_sn, g.goods_desc, g.goods_thumb, o.goods_price FROM " . $GLOBALS['ecs']->table('order_goods') . " AS o, " . $GLOBALS['ecs']->table('goods') . " AS g WHERE o.order_id='{$id}' AND o.goods_id=g.goods_id"); + foreach($order_res as $goods_data) + { + if(!empty($goods_data['goods_thumb'])) + { + $url = $GLOBALS['ecs']->url() . $goods_data['goods_thumb']; + } + else + { + $url = $GLOBALS['ecs']->url() . $GLOBALS['_CFG']['no_picture']; + } + $link = $GLOBALS['ecs']->url() . "goods.php?id=" . $goods_data["goods_id"]; + + $feed['icon'] = "goods"; + $feed['title_template'] = '{username} ' . $GLOBALS['_LANG']['feed_user_buy'] . ' {goods_name}'; + $feed['title_data'] = array('username'=> $_SESSION['user_name'], 'goods_name'=> $goods_data['goods_name']); + $feed['body_template'] = '{goods_name} ' . $GLOBALS['_LANG']['feed_goods_price'] . ':{goods_price} ' . $GLOBALS['_LANG']['feed_goods_desc'] . ':{goods_desc}'; + $feed['body_data'] = array('goods_name'=>$goods_data['goods_name'], 'goods_price'=>$goods_data['goods_price'], 'goods_desc'=>sub_str(strip_tags($goods_data['goods_desc']), 150, true)); + $feed['images'][] = array('url'=> $url, + 'link'=> $link); + uc_call("uc_feed_add", array($feed['icon'], $_SESSION['user_id'], $_SESSION['user_name'], $feed['title_template'], $feed['title_data'], $feed ['body_template'], $feed['body_data'], '', '', $feed['images'])); + } + } + return; +} + +/** + * 获得商品tag所关联的其他应用的列表 + * + * @param array $attr + * + * @return void + */ +function get_linked_tags($tag_data) +{ + //取所有应用列表 + $app_list = uc_call("uc_app_ls"); + if ($app_list == '') + { + return ''; + } + foreach($app_list as $app_key => $app_data) + { + if ($app_data['appid'] == UC_APPID) + { + unset($app_list[$app_key]); + continue; + } + $get_tag_array[$app_data['appid']] = '5'; + $app_array[$app_data['appid']]['name'] = $app_data['name']; + $app_array[$app_data['appid']]['type'] = $app_data['type']; + $app_array[$app_data['appid']]['url'] = $app_data['url']; + $app_array[$app_data['appid']]['tagtemplates'] = $app_data['tagtemplates']; + } + + $tag_rand_key = array_rand($tag_data); + $get_tag_data = uc_call("uc_tag_get", array($tag_data[$tag_rand_key], $get_tag_array)); + foreach($get_tag_data as $appid => $tag_data_array) + { + $templates = $app_array[$appid]['tagtemplates']['template']; + if (!empty($templates) && !empty($tag_data_array['data'])) + { + foreach($tag_data_array['data'] as $tag_data) + { + $show_data = $templates; + foreach($tag_data as $tag_key => $data) + { + $show_data = str_replace('{' . $tag_key . '}', $data, $show_data); + } + $app_array[$appid]['data'][] = $show_data; + } + } + } + + return $app_array; +} + +/** + * 兑换积分 + * + * @param integer $uid 用户ID + * @param integer $fromcredits 原积分 + * @param integer $tocredits 目标积分 + * @param integer $toappid 目标应用ID + * @param integer $netamount 积分数额 + * + * @return boolean + */ +function exchange_points($uid, $fromcredits, $tocredits, $toappid, $netamount) +{ + $ucresult = uc_call('uc_credit_exchange_request', array($uid, $fromcredits, $tocredits, $toappid, $netamount)); + if (!$ucresult) + { + return false; + } + else + { + return true; + } +} + +?> \ No newline at end of file diff --git a/includes/modules/convert/shopex46.php b/includes/modules/convert/shopex46.php new file mode 100644 index 0000000..5baa4ab --- /dev/null +++ b/includes/modules/convert/shopex46.php @@ -0,0 +1,948 @@ +sdb = $sdb; + $this->sprefix = $sprefix; + $this->sroot = $sroot; + $this->troot = str_replace('/includes/modules/convert', '', str_replace('\\', '/', dirname(__FILE__))); + $this->tdocroot = str_replace('/' . ADMIN_PATH, '', dirname(PHP_SELF)); + $this->scharset = $scharset; + if (EC_CHARSET == 'utf-8') + { + $tcharset = 'UTF8'; + } + elseif (EC_CHARSET == 'gbk') + { + $tcharset = 'GB2312'; + } + $this->tcharset = $tcharset; + } + + /** + * 需要转换的表(用于检查数据库是否完整) + * @return array + */ + function required_tables() + { + return array( + $this->sprefix.'mall_offer_pcat',$this->sprefix.'mall_goods',$this->sprefix.'mall_offer_linkgoods',$this->sprefix.'mall_member_level', + $this->sprefix.'mall_member',$this->sprefix.'mall_offer_p',$this->sprefix.'mall_offer_deliverarea',$this->sprefix.'mall_offer_t', + $this->sprefix.'mall_offer_ncat',$this->sprefix.'mall_offer_ncon',$this->sprefix.'mall_offer_link',$this->sprefix.'mall_orders', + $this->sprefix.'mall_items',$this->sprefix.'mall_offer', + ); + } + + /** + * 比需的目录 + * @return array + */ + function required_dirs() + { + return array( + '/syssite/home/shop/1/pictures/newsimg/', + '/syssite/home/shop/1/pictures/productsimg/big/', + '/syssite/home/shop/1/pictures/productsimg/small/', + '/syssite/home/shop/1/pictures/linkimg/', + '/cert/', + ); + } + + /** + * 下一步操作:空表示结束 + * @param string $step 当前操作:空表示开始 + * @return string + */ + function next_step($step) + { + /* 所有操作 */ + $steps = array( + '' => 'step_file', + 'step_file' => 'step_cat', + 'step_cat' => 'step_brand', + 'step_brand' => 'step_goods', + 'step_goods' => 'step_users', + 'step_users' => 'step_article', + 'step_article' => 'step_order', + 'step_order' => 'step_config', + 'step_config' => '', + ); + + return $steps[$step]; + } + + /** + * 执行某个步骤 + * @param string $step + */ + function process($step) + { + $func = str_replace('step', 'process', $step); + return $this->$func(); + } + + /** + * 复制文件 + * @return 成功返回true,失败返回错误信息 + */ + function process_file() + { + /* 复制 html 编辑器的图片 */ + $from = $this->sroot . '/syssite/home/shop/1/pictures/newsimg/'; + $to = $this->troot . '/images/upload/'; + copy_files($from, $to); + + /* 复制商品图片 */ + $to = $this->troot . '/images/' . date('Ym') . '/'; + + $from = $this->sroot . '/syssite/home/shop/1/pictures/productsimg/big/'; + copy_files($from, $to, 'big_'); + + $from = $this->sroot . '/syssite/home/shop/1/pictures/productsimg/small/'; + copy_files($from, $to, 'small_'); + + $from = $this->sroot . '/syssite/home/shop/1/pictures/productsimg/big/'; + copy_files($from, $to, 'original_'); + + /* 复制友情链接图片 */ + $from = $this->sroot . '/syssite/home/shop/1/pictures/linkimg/'; + $to = $this->troot . '/data/afficheimg/'; + + /* 复制证书 */ + $from = $this->sroot . '/cert/'; + $to = $this->troot . '/cert/'; + + return TRUE; + } + + /** + * 商品分类 + * @return 成功返回true,失败返回错误信息 + */ + function process_cat() + { + global $db, $ecs; + + /* 清空分类、商品类型、属性 */ + truncate_table('category'); + truncate_table('goods_type'); + truncate_table('attribute'); + + /* 查询分类并循环处理 */ + $sql = "SELECT * FROM ".$this->sprefix."mall_offer_pcat"; + $res = $this->sdb->query($sql); + while ($row = $this->sdb->fetchRow($res)) + { + $cat = array(); + $cat['cat_id'] = $row['catid']; + $cat['cat_name'] = ecs_iconv($this->scharset, $this->tcharset, addslashes($row['cat'])); + $cat['parent_id'] = $row['pid']; + $cat['sort_order'] = $row['catord']; + + /* 插入分类 */ + if (!$db->autoExecute($ecs->table('category'), $cat, 'INSERT', '', 'SILENT')) + { + //return $db->error(); + } + + /* 检查该分类是否有属性 */ + $has_attr = false; + for ($i = 1; $i <= 40; $i++) + { + if (trim($row["attr".$i]) != '') + { + $has_attr = TRUE; + break; + } + } + + /* 如果该分类有属性,插入商品类型,类型名称取分类名称 */ + if ($has_attr) + { + if (!$db->autoExecute($ecs->table('goods_type'), $cat, 'INSERT', '', 'SILENT')) + { + //return $db->error(); + } + } + + /* 插入属性 */ + $attr = array(); + $attr['cat_id'] = $row['catid']; + $attr['attr_input_type'] = ATTR_INPUT; + $attr['attr_type'] = ATTR_NOT_NEED_SELECT; + for ($i = 1; $i <= 40; $i++) + { + if (trim($row["attr".$i]) != '') + { + $attr['attr_name'] = ecs_iconv($this->scharset, $this->tcharset, $row["attr".$i]); + $attr['sort_order'] = $i; + if (!$db->autoExecute($ecs->table('attribute'), $attr, 'INSERT', '', 'SILENT')) + { + //return $db->error(); + } + } + } + } + + /* 返回成功 */ + return TRUE; + } + + /** + * 品牌 + * @return 成功返回true,失败返回错误信息 + */ + function process_brand() + { + global $db, $ecs; + + /* 清空品牌 */ + truncate_table('brand'); + + /* 查询品牌并插入 */ + $sql = "SELECT DISTINCT brand FROM ".$this->sprefix."mall_goods WHERE TRIM(brand) <> ''"; + $res = $this->sdb->query($sql); + while ($row = $this->sdb->fetchRow($res)) + { + $brand = array( + 'brand_name' => ecs_iconv($this->scharset, $this->tcharset, addslashes($row['brand'])), + 'brand_desc' => '', + ); + if (!$db->autoExecute($ecs->table('brand'), $brand, 'INSERT', '', 'SILENT')) + { + //return $db->error(); + } + } + + /* 返回成功 */ + return TRUE; + } + + /** + * 商品 + * @return 成功返回true,失败返回错误信息 + */ + function process_goods() + { + global $db, $ecs; + + /* 清空商品、商品扩展分类、商品属性、商品相册、关联商品、组合商品、赠品 */ + truncate_table('goods'); + truncate_table('goods_cat'); + truncate_table('goods_attr'); + truncate_table('goods_gallery'); + truncate_table('link_goods'); + truncate_table('group_goods'); + + /* 查询品牌列表 name => id */ + $brand_list = array(); + $sql = "SELECT brand_id, brand_name FROM " . $ecs->table('brand'); + $res = $db->query($sql); + while ($row = $db->fetchRow($res)) + { + $brand_list[$row['brand_name']] = $row['brand_id']; + } + + /* 取得商店设置 */ + $sql = "SELECT offer_pointtype, offer_pointnum FROM ".$this->sprefix."mall_offer WHERE offerid = '1'"; + $config = $this->sdb->getRow($sql); + + /* 查询商品并处理 */ + $sql = "SELECT * FROM ".$this->sprefix."mall_goods"; + $res = $this->sdb->query($sql); + while ($row = $this->sdb->fetchRow($res)) + { + $goods = array(); + $goods['goods_id'] = $row['gid']; + $goods['cat_id'] = $row['catid']; + $goods['goods_sn'] = ecs_iconv($this->scharset, $this->tcharset, addslashes($row['bn'])); + $goods['goods_name'] = ecs_iconv($this->scharset, $this->tcharset, addslashes($row['goods'])); + $goods['brand_id'] = trim($row['brand']) == '' ? '0' : $brand_list[ecs_iconv($this->scharset, $this->tcharset, addslashes($row['brand']))]; + $goods['goods_number'] = $row['storage']; + $goods['goods_weight'] = $row['weight']; + $goods['market_price'] = $row['priceintro']; + $goods['shop_price'] = $row['ifdiscreteness'] == '1' ? $row['basicprice'] : $row['price']; + if ($row['tejia2'] == '1') + { + $goods['promote_price'] = $goods['shop_price']; + $goods['promote_start_date'] = gmtime(); + $goods['promote_end_date'] = local_strtotime('+1 weeks'); + } + $goods['warn_number'] = $row['ifalarm'] == '1' ? $row['alarmnum'] : '0'; + $goods['goods_brief'] = ecs_iconv($this->scharset, $this->tcharset, addslashes($row['intro'])); + $goods['goods_desc'] = str_replace('pictures/newsimg/', $this->tdocroot . '/images/upload/', ecs_iconv($this->scharset, $this->tcharset, addslashes($row['memo']))); + $goods['is_real'] = '1'; + $goods['is_on_sale'] = $row['shop_iffb']; + $goods['is_alone_sale'] = '1'; + $goods['add_time'] = $row['uptime']; + $goods['sort_order'] = $row['offer_ord']; + $goods['is_delete'] = '0'; + $goods['is_best'] = $row['recommand2']; + $goods['is_new'] = $row['new2']; + $goods['is_hot'] = $row['hot2']; + $goods['is_promote'] = $row['tejia2']; + $goods['goods_type'] = $row['catid']; + $goods['last_update'] = gmtime(); + + /* 图片:如果没有本地文件,取远程图片 */ + $file = $this->troot . '/images/' . date('Ym') . '/small_' . $row['gid']; + if (file_exists($file. '.jpg')) + { + $goods['goods_thumb'] = 'images/' . date('Ym') . '/small_' . $row['gid'] . '.jpg'; + } + elseif (file_exists($file. '.jpeg')) + { + $goods['goods_thumb'] = 'images/' . date('Ym') . '/small_' . $row['gid'] . '.jpeg'; + } + elseif (file_exists($file. '.gif')) + { + $goods['goods_thumb'] = 'images/' . date('Ym') . '/small_' . $row['gid'] . '.gif'; + } + elseif (file_exists($file. '.png')) + { + $goods['goods_thumb'] = 'images/' . date('Ym') . '/small_' . $row['gid'] . '.png'; + } + else + { + $goods['goods_thumb'] = $row['smallimgremote']; + } + + $file = $this->troot . '/images/' . date('Ym') . '/big_' . $row['gid']; + if (file_exists($file. '.jpg')) + { + $goods['goods_img'] = 'images/' . date('Ym') . '/big_' . $row['gid'] . '.jpg'; + $goods['original_img'] = 'images/' . date('Ym') . '/original_' . $row['gid'] . '.jpg'; + } + elseif (file_exists($file. '.jpeg')) + { + $goods['goods_img'] = 'images/' . date('Ym') . '/big_' . $row['gid'] . '.jpeg'; + $goods['original_img'] = 'images/' . date('Ym') . '/original_' . $row['gid'] . '.jpeg'; + } + elseif (file_exists($file. '.gif')) + { + $goods['goods_img'] = 'images/' . date('Ym') . '/big_' . $row['gid'] . '.gif'; + $goods['original_img'] = 'images/' . date('Ym') . '/original_' . $row['gid'] . '.gif'; + } + elseif (file_exists($file. '.png')) + { + $goods['goods_img'] = 'images/' . date('Ym') . '/big_' . $row['gid'] . '.png'; + $goods['orinigal_img'] = 'images/' . date('Ym') . '/original_' . $row['gid'] . '.png'; + } + else + { + $goods['goods_img'] = $row['bigimgremote']; + } + + /* 积分:根据商店设置 */ + if ($config['offer_pointtype'] == '0') + { + /* 不使用积分 */ + $goods['integral'] = '0'; + } + elseif ($config['offer_pointtype'] == '1') + { + /* 按比例 */ + $goods['integral'] = round($goods['shop_price'] * $config['offer_pointnum']); + } + else + { + /* 自定义 */ + $goods['integral'] = $row['point']; + } + + /* 插入 */ + if (!$db->autoExecute($ecs->table('goods'), $goods, 'INSERT', '', 'SILENT')) + { + //return $db->error(); + } + + /* 扩展分类 */ + if ($row['linkclass'] != '') + { + $goods_cat = array(); + $goods_cat['goods_id'] = $row['gid']; + $cat_id_list = explode(',', trim($row['linkclass'], ',')); + foreach ($cat_id_list as $cat_id) + { + $goods_cat['cat_id'] = $cat_id; + if (!$db->autoExecute($ecs->table('goods_cat'), $goods_cat, 'INSERT', '', 'SILENT')) + { + //return $db->error(); + } + } + } + + /* 取得该分类的所有属性 */ + $attr_list = array(); + $sql = "SELECT * FROM " . $ecs->table('attribute') . " WHERE cat_id = '$row[catid]'"; + $res1 = $db->query($sql); + while ($attr = $db->fetchRow($res1)) + { + $attr_list[$attr['sort_order']] = $attr['attr_id']; + } + + /* 商品属性 */ + if ($attr_list) + { + $goods_attr = array(); + $goods_attr['goods_id'] = $row['gid']; + for ($i = 1; $i <= 40; $i++) + { + if (trim($row['attr' . $i]) != '') + { + $goods_attr['attr_id'] = $attr_list[$i]; + $goods_attr['attr_value'] = trim(ecs_iconv($this->scharset, $this->tcharset, $row['attr' . $i])); + if (!$db->autoExecute($ecs->table('goods_attr'), $goods_attr, 'INSERT', '', 'SILENT')) + { + //return $db->error(); + } + } + } + } + + /* 商品相册 */ + if ($row['multi_image']) + { + $goods_gallery = array(); + $goods_gallery['goods_id'] = $row['gid']; + $img_list = explode('&&&', $row['multi_image']); + foreach ($img_list as $img) + { + if (substr($img, 0, 7) == 'http://') + { + $goods_gallery['img_url'] = $img; + } + else + { + make_dir('images/' . date('Ym') . '/'); + $goods_gallery['img_url'] = 'images/' . date('Ym') . '/big_' . $img; + $goods_gallery['img_original'] = 'images/' . date('Ym') . '/original_' . $img; + } + + if (!$db->autoExecute($ecs->table('goods_gallery'), $goods_gallery, 'INSERT', '', 'SILENT')) + { + //return $db->error(); + } + } + } + } + + /* 关联商品 */ + $sql = "SELECT * FROM ".$this->sprefix."mall_offer_linkgoods"; + $res = $this->sdb->query($sql); + while ($row = $this->sdb->fetchRow($res)) + { + $link_goods = array(); + $link_goods['goods_id'] = $row['pgid']; + $link_goods['link_goods_id'] = $row['sgid']; + $link_goods['is_double'] = $row['type']; + + if (!$db->autoExecute($ecs->table('link_goods'), $link_goods, 'INSERT', '', 'SILENT')) + { + //return $db->error(); + } + + if ($row['type'] == '1') + { + $link_goods = array(); + $link_goods['goods_id'] = $row['sgid']; + $link_goods['link_goods_id'] = $row['pgid']; + $link_goods['is_double'] = $row['type']; + + if (!$db->autoExecute($ecs->table('link_goods'), $link_goods, 'INSERT', '', 'SILENT')) + { + //return $db->error(); + } + } + } + + /* 组合商品 */ + + /* 返回成功 */ + return TRUE; + } + + /** + * 会员等级、会员、会员价格 + */ + function process_users() + { + global $db, $ecs; + + /* 清空会员、会员等级、会员价格、用户红包、用户地址 */ + truncate_table('user_rank'); + truncate_table('users'); + truncate_table('user_address'); + truncate_table('user_bonus'); + truncate_table('member_price'); + truncate_table('user_account'); + + /* 查询并插入会员等级 */ + $sql = "SELECT * FROM ".$this->sprefix."mall_member_level order by point desc"; + $res = $this->sdb->query($sql); + $max_points = 50000; + while ($row = $this->sdb->fetchRow($res)) + { + $user_rank = array(); + $user_rank['rank_id'] = $row['levelid']; + $user_rank['rank_name'] = ecs_iconv($this->scharset, $this->tcharset, addslashes($row['name'])); + $user_rank['min_points'] = $row['point']; + $user_rank['max_points'] = $max_points; + $user_rank['discount'] = round($row['discount'] * 100); + $user_rank['show_price'] = '1'; + $user_rank['special_rank'] = '0'; + + if (!$db->autoExecute($ecs->table('user_rank'), $user_rank, 'INSERT', '', 'SILENT')) + { + //return $db->error(); + } + + $max_points = $row['point'] - 1; + } + + /* 查询并插入会员 */ + $sql = "SELECT * FROM ".$this->sprefix."mall_member"; + $res = $this->sdb->query($sql); + while ($row = $this->sdb->fetchRow($res)) + { + $user = array(); + $user['user_id'] = $row['userid']; + $user['email'] = $row['email']; + $user['user_name'] = ecs_iconv($this->scharset, $this->tcharset, addslashes($row['user'])); + $user['password'] = $row['password']; + $user['question'] = ecs_iconv($this->scharset, $this->tcharset, addslashes($row['pw_question'])); + $user['answer'] = ecs_iconv($this->scharset, $this->tcharset, addslashes($row['pw_answer'])); + $user['sex'] = $row['sex']; + if (!empty($row['birthday'])) + { + $birthday = strtotime($row['birthday']); + if ($birthday != -1 && $birthday !== false) + { + $user['birthday'] = date('Y-m-d', $birthday); + } + } + $user['user_money'] = $row['advance']; + $user['pay_points'] = $row['point']; + $user['rank_points'] = $row['point']; + $user['reg_time'] = $row['regtime']; + $user['last_login'] = $row['regtime']; + $user['last_ip'] = $row['ip']; + $user['visit_count'] = '1'; + $user['user_rank'] = '0'; + + if (!$db->autoExecute($ecs->table('users'), $user, 'INSERT', '', 'SILENT')) + { + //return $db->error(); + } + uc_call('uc_user_register', array($user['user_name'], $user['password'], $user['email'])); + } + + /* 收货人地址 */ + $sql = "SELECT * FROM ".$this->sprefix."mall_member_receiver"; + $res = $this->sdb->query($sql); + while ($row = $this->sdb->fetchRow($res)) + { + $address = array(); + $address['address_id'] = $row['receiveid']; + $address['address_name'] = ecs_iconv($this->scharset, $this->tcharset, addslashes($row['name'])); + $address['user_id'] = $row['memberid']; + $address['consignee'] = ecs_iconv($this->scharset, $this->tcharset, addslashes($row['name'])); + $address['email'] = $row['email']; + $address['address'] = ecs_iconv($this->scharset, $this->tcharset, addslashes($row['address'])); + $address['zipcode'] = $row['zipcode']; + $address['tel'] = $row['telphone']; + $address['mobile'] = $row['mobile']; + + if (!$db->autoExecute($ecs->table('user_address'), $address, 'INSERT', '', 'SILENT')) + { + //return $db->error(); + } + } + + /* 会员价格 */ + $temp_arr = array(); + $sql = "SELECT * FROM ".$this->sprefix."mall_member_price"; + $res = $this->sdb->query($sql); + while ($row = $this->sdb->fetchRow($res)) + { + if ($row['gid'] > 0 && $row['levelid'] > 0 && !isset($temp_arr[$row['gid']][$row['levelid']])) + { + $temp_arr[$row['gid']][$row['levelid']] = true; + + $member_price = array(); + $member_price['goods_id'] = $row['gid']; + $member_price['user_rank'] = $row['levelid']; + $member_price['user_price'] = $row['price']; + + if (!$db->autoExecute($ecs->table('member_price'), $member_price, 'INSERT', '', 'SILENT')) + { + //return $db->error(); + } + } + } + unset($temp_arr); + + /* 帐户明细 */ + $sql = "SELECT * FROM ".$this->sprefix."mall_member_advance"; + $res = $this->sdb->query($sql); + while ($row = $this->sdb->fetchRow($res)) + { + $user_account = array(); + $user_account['user_id'] = $row['memberid']; + $user_account['admin_user'] = $row['doman']; + $user_account['amount'] = $row['money']; + $user_account['add_time'] = $row['date']; + $user_account['paid_time'] = $row['date']; + $user_account['admin_note'] = $row['description']; + $user_account['process_type'] = $row['money'] >= 0 ? SURPLUS_SAVE : SURPLUS_RETURN; + $user_account['is_paid'] = '1'; + + if (!$db->autoExecute($ecs->table('user_account'), $user_account, 'INSERT', '', 'SILENT')) + { + //return $db->error(); + } + } + + /* 返回 */ + return TRUE; + } + + /** + * 文章 + */ + function process_article() + { + global $db, $ecs; + + /* 清空文章类型、文章、友情链接 */ + truncate_table('article_cat'); + truncate_table('article'); + truncate_table('friend_link'); + + /* 文章类型 */ + $sql = "SELECT * FROM ".$this->sprefix."mall_offer_ncat"; + $res = $this->sdb->query($sql); + while ($row = $this->sdb->fetchRow($res)) + { + $cat = array(); + $cat['cat_id'] = $row['catid']; + $cat['cat_name'] = ecs_iconv($this->scharset, $this->tcharset, addslashes($row['cat'])); + $cat['cat_type'] = '1'; + $cat['sort_order'] = $row['pid']; + $cat['is_open'] = '1'; + + if (!$db->autoExecute($ecs->table('article_cat'), $cat, 'INSERT', '', 'SILENT')) + { + //return $db->error(); + } + } + + /* 文章 */ + $sql = "SELECT * FROM ".$this->sprefix."mall_offer_ncon"; + $res = $this->sdb->query($sql); + while ($row = $this->sdb->fetchRow($res)) + { + $article = array(); + $article['article_id'] = $row['newsid']; + $article['cat_id'] = $row['catid']; + $article['title'] = ecs_iconv($this->scharset, $this->tcharset, addslashes($row['title'])); + $article['content'] = ecs_iconv($this->scharset, $this->tcharset, addslashes($row['con'])); + $article['article_type']= '0'; + $article['is_open'] = $row['ifpub']; + $article['add_time'] = $row['uptime']; + + if (!$db->autoExecute($ecs->table('article'), $article, 'INSERT', '', 'SILENT')) + { + //return $db->error(); + } + } + + /* 友情链接 */ + $sql = "SELECT * FROM ".$this->sprefix."mall_offer_link"; + $res = $this->sdb->query($sql); + while ($row = $this->sdb->fetchRow($res)) + { + $link = array(); + $link['link_id'] = $row['linkid']; + $link['link_name'] = ecs_iconv($this->scharset, $this->tcharset, addslashes($row['linktitle'])); + $link['link_url'] = $row['linkurl']; + $link['show_order'] = '0'; + + if ($row['linktype'] == 'img') + { + $link['link_logo'] = $row['imgurl']; + } + + if (!$db->autoExecute($ecs->table('friend_link'), $link, 'INSERT', '', 'SILENT')) + { + //return $db->error(); + } + } + + /* 返回 */ + return TRUE; + } + + /** + * 订单 + */ + function process_order() + { + global $db, $ecs; + + /* 清空订单、订单商品 */ + truncate_table('order_info'); + truncate_table('order_goods'); + truncate_table('order_action'); + + /* 订单 */ + $sql = "SELECT o.*, t.tmethod, p.payment FROM ".$this->sprefix."mall_orders AS o " . + "LEFT JOIN ".$this->sprefix."mall_offer_t AS t ON o.ttype = t.id " . + "LEFT JOIN ".$this->sprefix."mall_offer_p AS p ON o.ptype = p.id"; + $res = $this->sdb->query($sql); + while ($row = $this->sdb->fetchRow($res)) + { + $order = array(); + $order['order_sn'] = $row['orderid']; + $order['user_id'] = $row['userid']; + $order['add_time'] = $row['ordertime']; + $order['consignee'] = ecs_iconv($this->scharset, $this->tcharset, addslashes($row['name'])); + $order['address'] = ecs_iconv($this->scharset, $this->tcharset, addslashes($row['addr'])); + $order['zipcode'] = $row['zip']; + $order['tel'] = $row['tel']; + $order['mobile'] = $row['mobile']; + $order['email'] = $row['email']; + $order['postscript'] = ecs_iconv($this->scharset, $this->tcharset, addslashes($row['memo'])); + $order['shipping_name'] = is_null($row['tmethod']) ? ' ' : ecs_iconv($this->scharset, $this->tcharset, addslashes($row['tmethod'])); + $order['pay_name'] = is_null($row['payment']) ? ' ' : ecs_iconv($this->scharset, $this->tcharset, addslashes($row['payment'])); + $order['inv_payee'] = ecs_iconv($this->scharset, $this->tcharset, addslashes($row['invoiceform'])); + $order['goods_amount'] = $row['item_amount']; + $order['shipping_fee'] = $row['freight']; + $order['order_amount'] = $row['total_amount']; + $order['pay_time'] = $row['paytime']; + $order['shipping_time'] = $row['sendtime']; + + /* 状态 */ + if ($row['ordstate'] == '0') + { + $order['order_status'] = OS_UNCONFIRMED; + $order['shipping_status'] = SS_UNSHIPPED; + } + elseif ($row['ordstate'] == '1') + { + $order['order_status'] = OS_CONFIRMED; + $order['shipping_status'] = SS_UNSHIPPED; + } + elseif ($row['ordstate'] == '9') + { + $order['order_status'] = OS_INVALID; + $order['shipping_status'] = SS_UNSHIPPED; + } + else // 3 发货 4 归档 + { + $order['order_status'] = OS_CONFIRMED; + $order['shipping_status'] = SS_SHIPPED; + } + + if ($row['ifsk'] == '1') + { + $order['pay_status'] = PS_PAYED; + } + else // 0 未付款 5 退款 + { + $order['pay_status'] = PS_UNPAYED; + } + + if ($row['userrecsts'] == '1') // 用户操作了 + { + if ($row['recsts'] == '1') // 到货 + { + if ($order['shipping_status'] == SS_SHIPPED) + { + $order['shipping_status'] = SS_RECEIVED; + } + } + elseif ($row['recsts'] == '2') // 取消 + { + $order['order_status'] = OS_CANCELED; + $order['pay_status'] = PS_UNPAYED; + $order['shipping_status'] = SS_UNSHIPPED; + } + } + + /* 如果已付款,修改已付款金额为订单总金额,修改订单总金额为0 */ + if ($order['pay_status'] > PS_UNPAYED) + { + $order['money_paid'] = $order['order_amount']; + $order['order_amount'] = 0; + } + + if (!$db->autoExecute($ecs->table('order_info'), $order, 'INSERT', '', 'SILENT')) + { + //return $db->error(); + } + + /* 订单商品 */ + $order_id = $db->insert_id(); + $sql = "SELECT i.*, g.priceintro FROM ".$this->sprefix."mall_items AS i " . + "LEFT JOIN ".$this->sprefix."mall_goods AS g ON i.gid = g.gid " . + "WHERE orderid = '$row[orderid]'"; + $res1 = $this->sdb->query($sql); + while ($row = $this->sdb->fetchRow($res1)) + { + $goods = array(); + $goods['order_id'] = $order_id; + $goods['goods_id'] = $row['gid']; + $goods['goods_name'] = ecs_iconv($this->scharset, $this->tcharset, addslashes($row['goods'])); + $goods['goods_sn'] = ecs_iconv($this->scharset, $this->tcharset, addslashes($row['bn'])); + $goods['goods_number'] = $row['nums']; + $goods['goods_price'] = $row['price']; + $goods['market_price'] = is_null($row['priceintro']) ? $row['goods_price'] : $row['priceintro']; + $goods['is_real'] = 1; + $goods['parent_id'] = 0; + $goods['is_gift'] = 0; + + if (!$db->autoExecute($ecs->table('order_goods'), $goods, 'INSERT', '', 'SILENT')) + { + //return $db->error(); + } + } + } + + /* 返回 */ + return TRUE; + } + + /** + * 商店设置 + */ + function process_config() + { + global $ecs, $db; + + /* 查询设置 */ + $sql = "SELECT * FROM ".$this->sprefix."mall_offer " . + "WHERE offerid = '1'"; + $row = $this->sdb->getRow($sql); + + $config = array(); + $config['shop_name'] = ecs_iconv($this->scharset, $this->tcharset, addslashes($row['offer_name'])); + $config['shop_title'] = ecs_iconv($this->scharset, $this->tcharset, addslashes($row['offer_shoptitle'])); + $config['shop_desc'] = ecs_iconv($this->scharset, $this->tcharset, addslashes($row['offer_metadesc'])); + $config['shop_address'] = ecs_iconv($this->scharset, $this->tcharset, addslashes($row['offer_addr'])); + $config['service_email'] = $row['offer_email']; + $config['service_phone'] = $row['offer_tel']; + $config['icp_number'] = ecs_iconv($this->scharset, $this->tcharset, addslashes($row['offer_certtext'])); + //$config['integral_scale'] = $row['offer_pointtype'] == '0' ? '0' : $row['offer_pointnum'] * 100; + $config['thumb_width'] = $row['offer_smallsize_w']; + $config['thumb_height'] = $row['offer_smallsize_h']; + $config['image_width'] = $row['offer_bigsize_w']; + $config['image_height'] = $row['offer_bigsize_h']; + $config['promote_number'] = $row['offer_tejianums']; + $config['best_number'] = $row['offer_tjnums']; + $config['new_number'] = $row['offer_newgoodsnums']; + $config['hot_number'] = $row['offer_hotnums']; + $config['smtp_host'] = $row['offer_smtp_server']; + $config['smtp_port'] = $row['offer_smtp_port']; + $config['smtp_user'] = $row['offer_smtp_user']; + $config['smtp_pass'] = $row['offer_smtp_password']; + $config['smtp_mail'] = $row['offer_smtp_email']; + + /* 更新 */ + foreach ($config as $code => $value) + { + $sql = "UPDATE " . $ecs->table('shop_config') . " SET " . + "value = '$value' " . + "WHERE code = '$code' LIMIT 1"; + if (!$db->query($sql, 'SILENT')) + { + //return $db->error(); + } + } + + /* 返回 */ + return TRUE; + } +} + +?> \ No newline at end of file diff --git a/includes/modules/convert/shopex47.php b/includes/modules/convert/shopex47.php new file mode 100644 index 0000000..98af67e --- /dev/null +++ b/includes/modules/convert/shopex47.php @@ -0,0 +1,978 @@ +sdb = $sdb; + $this->sprefix = $sprefix; + $this->sroot = $sroot; + $this->troot = str_replace('/includes/modules/convert', '', str_replace('\\', '/', dirname(__FILE__))); + $this->tdocroot = str_replace('/' . ADMIN_PATH, '', dirname(PHP_SELF)); + $this->scharset = $scharset; + if (EC_CHARSET == 'utf-8') + { + $tcharset = 'UTF8'; + } + elseif (EC_CHARSET == 'gbk') + { + $tcharset = 'GB2312'; + } + $this->tcharset = $tcharset; + } + + /** + * 需要转换的表(用于检查数据库是否完整) + * @return array + */ + function required_tables() + { + return array( + $this->sprefix.'mall_offer_pcat',$this->sprefix.'mall_brand',$this->sprefix.'mall_goods',$this->sprefix.'mall_offer_linkgoods', $this->sprefix.'mall_member_level',$this->sprefix.'mall_member',$this->sprefix.'mall_offer_p',$this->sprefix.'mall_offer_deliverarea',$this->sprefix.'mall_offer_t',$this->sprefix.'mall_offer_ncat',$this->sprefix.'mall_offer_ncon',$this->sprefix.'mall_offer_link', + $this->sprefix.'mall_orders',$this->sprefix.'mall_items',$this->sprefix.'mall_offer', + ); + } + + /** + * 必需的目录 + * @return array + */ + function required_dirs() + { + return array( + '/syssite/home/shop/1/pictures/brandimg/', + '/syssite/home/shop/1/pictures/newsimg/', + '/syssite/home/shop/1/pictures/productsimg/big/', + '/syssite/home/shop/1/pictures/productsimg/small/', + '/syssite/home/shop/1/pictures/linkimg/', + '/cert/', + ); + } + + /** + * 下一步操作:空表示结束 + * @param string $step 当前操作:空表示开始 + * @return string + */ + function next_step($step) + { + /* 所有操作 */ + $steps = array( + '' => 'step_file', + 'step_file' => 'step_cat', + 'step_cat' => 'step_brand', + 'step_brand' => 'step_goods', + 'step_goods' => 'step_users', + 'step_users' => 'step_article', + 'step_article' => 'step_order', + 'step_order' => 'step_config', + 'step_config' => '', + ); + + return $steps[$step]; + } + + /** + * 执行某个步骤 + * @param string $step + */ + function process($step) + { + $func = str_replace('step', 'process', $step); + return $this->$func(); + } + + /** + * 复制文件 + * @return 成功返回true,失败返回错误信息 + */ + function process_file() + { + /* 复制品牌图片 */ + $from = $this->sroot . '/syssite/home/shop/1/pictures/brandimg/'; + $to = $this->troot . '/data/brandlogo/'; + copy_files($from, $to); + + /* 复制 html 编辑器的图片 */ + $from = $this->sroot . '/syssite/home/shop/1/pictures/newsimg/'; + $to = $this->troot . '/images/upload/Image/'; + copy_files($from, $to); + + /* 复制商品图片 */ + $to = $this->troot . '/images/' . date('Ym') . '/'; + + $from = $this->sroot . '/syssite/home/shop/1/pictures/productsimg/big/'; + copy_files($from, $to, 'big_'); + + $from = $this->sroot . '/syssite/home/shop/1/pictures/productsimg/small/'; + copy_files($from, $to, 'small_'); + + $from = $this->sroot . '/syssite/home/shop/1/pictures/productsimg/big/'; + copy_files($from, $to, 'original_'); + + /* 复制友情链接图片 */ + $from = $this->sroot . '/syssite/home/shop/1/pictures/linkimg/'; + $to = $this->troot . '/data/afficheimg/'; + copy_files($from, $to); + + /* 复制证书 */ + $from = $this->sroot . '/cert/'; + $to = $this->troot . '/cert/'; + copy_files($from, $to); + + return TRUE; + } + + /** + * 商品分类 + * @return 成功返回true,失败返回错误信息 + */ + function process_cat() + { + global $db, $ecs; + + /* 清空分类、商品类型、属性 */ + truncate_table('category'); + truncate_table('goods_type'); + truncate_table('attribute'); + + /* 查询分类并循环处理 */ + $sql = "SELECT * FROM ".$this->sprefix."mall_offer_pcat"; + $res = $this->sdb->query($sql); + while ($row = $this->sdb->fetchRow($res)) + { + $cat = array(); + $cat['cat_id'] = $row['catid']; + $cat['cat_name'] = $row['cat']; + $cat['parent_id'] = $row['pid']; + $cat['sort_order'] = $row['catord']; + + /* 插入分类 */ + if (!$db->autoExecute($ecs->table('category'), $cat, 'INSERT', '', 'SILENT')) + { + //return $db->error(); + } + } + + /* 查询商品类型并循环处理 */ + $sql = "SELECT * FROM ".$this->sprefix."mall_prop_category"; + $res = $this->sdb->query($sql); + while ($row = $this->sdb->fetchRow($res)) + { + $type = array(); + $type['cat_id'] = $row['prop_cat_id']; + $type['cat_name'] = $row['cat_name']; + $type['enabled'] = '1'; + if (!$db->autoExecute($ecs->table('goods_type'), $type, 'INSERT', '', 'SILENT')) + { + //return $db->error(); + } + } + + /* 查询属性值并循环处理 */ + $sql = "SELECT * FROM ".$this->sprefix."mall_prop WHERE prop_type = 'propvalue'"; + $res = $this->sdb->query($sql); + while ($row = $this->sdb->fetchRow($res)) + { + $attr = array(); + $attr['attr_id'] = $row['prop_id']; + $attr['attr_name'] = $row['prop_name']; + $attr['cat_id'] = $row['prop_cat_id']; + $attr['sort_order'] = $row['ordnum']; + $attr['attr_input_type'] = '1'; + $attr['attr_type'] = '1'; + + $sql = "SELECT DISTINCT prop_value FROM ".$this->sprefix."mall_prop_value WHERE prop_id = '$row[prop_id]'"; + $attr['attr_values']= join("\n", $this->sdb->getCol($sql)); + if (!$db->autoExecute($ecs->table('attribute'), $attr, 'INSERT', '', 'SILENT')) + { + //return $db->error(); + } + } + + /* 返回成功 */ + return TRUE; + } + + /** + * 品牌 + * @return 成功返回true,失败返回错误信息 + */ + function process_brand() + { + global $db, $ecs; + + /* 清空品牌 */ + truncate_table('brand'); + + /* 查询品牌并插入 */ + $sql = "SELECT * FROM ".$this->sprefix."mall_brand"; + $res = $this->sdb->query($sql); + while ($row = $this->sdb->fetchRow($res)) + { + $brand = array( + 'brand_name' => $row['brand_name'], + 'brand_desc' => '', + 'site_url' => ecs_iconv($this->scharset, $this->tcharset, addslashes($row['brand_site_url'])), + 'brand_logo' => ecs_iconv($this->scharset, $this->tcharset, addslashes($row['brand_logo'])) + ); + if (!$db->autoExecute($ecs->table('brand'), $brand, 'INSERT', '', 'SILENT')) + { + //return $db->error(); + } + } + + /* 返回成功 */ + return TRUE; + } + + /** + * 商品 + * @return 成功返回true,失败返回错误信息 + */ + function process_goods() + { + global $db, $ecs; + + /* 清空商品、商品扩展分类、商品属性、商品相册、关联商品、组合商品、赠品 */ + truncate_table('goods'); + truncate_table('goods_cat'); + truncate_table('goods_attr'); + truncate_table('goods_gallery'); + truncate_table('link_goods'); + truncate_table('group_goods'); + + /* 查询品牌列表 name => id */ + $brand_list = array(); + $sql = "SELECT brand_id, brand_name FROM " . $ecs->table('brand'); + $res = $db->query($sql); + while ($row = $db->fetchRow($res)) + { + $brand_list[$row['brand_name']] = $row['brand_id']; + } + + /* 取得商店设置 */ + $sql = "SELECT offer_pointtype, offer_pointnum FROM ".$this->sprefix."mall_offer WHERE offerid = '1'"; + $config = $this->sdb->getRow($sql); + + /* 取得商品分类对应的商品类型 */ + $cat_type_list = array(); + $sql = "SELECT catid, prop_cat_id FROM ".$this->sprefix."mall_offer_pcat"; + $res = $this->sdb->query($sql); + while ($row = $this->sdb->fetchRow($res)) + { + $cat_type_list[$row['catid']] = $row['prop_cat_id']; + } + + /* 查询商品并处理 */ + $sql = "SELECT * FROM ".$this->sprefix."mall_goods"; + $res = $this->sdb->query($sql); + while ($row = $this->sdb->fetchRow($res)) + { + $goods = array(); + + if ($row['ifobject'] == '0') + { + /* 虚拟商品 */ + $goods['is_real'] = '0'; + } + elseif ($row['ifobject'] == '1') + { + /* 实体商品 */ + $goods['is_real'] = '1'; + } + elseif ($row['ifobject'] == '2') + { + /* 数字文件,暂时无法转换 */ + continue; + } + elseif ($row['ifobject'] == '3') + { + /* 捆绑销售,暂时无法转换 */ + continue; + } + else + { + /* 未知,无法转换 */ + continue; + } + $goods['goods_id'] = $row['gid']; + $goods['cat_id'] = $row['catid']; + $goods['goods_sn'] = ecs_iconv($this->scharset, $this->tcharset, addslashes($row['bn'])); + $goods['goods_name'] = $row['goods']; + $goods['brand_id'] = trim($row['brand']) == '' ? '0' : $brand_list[ecs_iconv($this->scharset, $this->tcharset, addslashes($row['brand']))]; + $goods['goods_number'] = $row['storage']; + $goods['goods_weight'] = $row['weight']; + $goods['market_price'] = $row['priceintro']; + $goods['shop_price'] = $row['ifdiscreteness'] == '1' ? $row['basicprice'] : $row['price']; + if ($row['tejia2'] == '1') + { + $goods['promote_price'] = $goods['shop_price']; + $goods['promote_start_date'] = gmtime(); + $goods['promote_end_date'] = gmstr2time('+1 weeks'); + } + $goods['warn_number'] = $row['ifalarm'] == '1' ? $row['alarmnum'] : '0'; + $goods['goods_brief'] = ecs_iconv($this->scharset, $this->tcharset, addslashes($row['intro'])); + $goods['goods_desc'] = str_replace('pictures/newsimg/', $this->tdocroot . '/images/upload/Image/', ecs_iconv($this->scharset, $this->tcharset, addslashes($row['memo']))); + $goods['is_on_sale'] = $row['shop_iffb']; + $goods['is_alone_sale'] = $row['onsale']; + $goods['add_time'] = $row['uptime']; + $goods['sort_order'] = $row['offer_ord']; + $goods['is_delete'] = '0'; + $goods['is_best'] = $row['recommand2']; + $goods['is_new'] = $row['new2']; + $goods['is_hot'] = $row['hot2']; + $goods['is_promote'] = $row['tejia2']; + $goods['goods_type'] = isset($cat_type_list[$row['catid']]) ? $cat_type_list[$row['catid']] : 0; + $goods['last_update'] = gmtime(); + + /* 图片:如果没有本地文件,取远程图片 */ + $file = $this->troot . '/images/' . date('Ym') . '/small_' . $row['gid']; + if (file_exists($file. '.jpg')) + { + $goods['goods_thumb'] = 'images/' . date('Ym') . '/small_' . $row['gid'] . '.jpg'; + } + elseif (file_exists($file. '.jpeg')) + { + $goods['goods_thumb'] = 'images/' . date('Ym') . '/small_' . $row['gid'] . '.jpeg'; + } + elseif (file_exists($file. '.gif')) + { + $goods['goods_thumb'] = 'images/' . date('Ym') . '/small_' . $row['gid'] . '.gif'; + } + elseif (file_exists($file. '.png')) + { + $goods['goods_thumb'] = 'images/' . date('Ym') . '/small_' . $row['gid'] . '.png'; + } + else + { + $goods['goods_thumb'] = $row['smallimgremote']; + } + + $file = $this->troot . '/images/' . date('Ym') . '/big_' . $row['gid']; + if (file_exists($file. '.jpg')) + { + $goods['goods_img'] = 'images/' . date('Ym') . '/big_' . $row['gid'] . '.jpg'; + $goods['original_img'] = 'images/' . date('Ym') . '/original_' . $row['gid'] . '.jpg'; + } + elseif (file_exists($file. '.jpeg')) + { + $goods['goods_img'] = 'images/' . date('Ym') . '/big_' . $row['gid'] . '.jpeg'; + $goods['original_img'] = 'images/' . date('Ym') . '/original_' . $row['gid'] . '.jpeg'; + } + elseif (file_exists($file. '.gif')) + { + $goods['goods_img'] = 'images/' . date('Ym') . '/big_' . $row['gid'] . '.gif'; + $goods['original_img'] = 'images/' . date('Ym') . '/original_' . $row['gid'] . '.gif'; + } + elseif (file_exists($file. '.png')) + { + $goods['goods_img'] = 'images/' . date('Ym') . '/big_' . $row['gid'] . '.png'; + $goods['orinigal_img'] = 'images/' . date('Ym') . '/original_' . $row['gid'] . '.png'; + } + else + { + $goods['goods_img'] = $row['bigimgremote']; + } + + /* 积分:根据商店设置 */ + if ($config['offer_pointtype'] == '0') + { + /* 不使用积分 */ + $goods['integral'] = '0'; + } + elseif ($config['offer_pointtype'] == '1') + { + /* 按比例 */ + $goods['integral'] = round($goods['shop_price'] * $config['offer_pointnum']); + } + else + { + /* 自定义 */ + $goods['integral'] = $row['point']; + } + + /* 插入 */ + if (!$db->autoExecute($ecs->table('goods'), $goods, 'INSERT', '', 'SILENT')) + { + //return $db->error(); + } + + /* 扩展分类 */ + if ($row['linkclass'] != '') + { + $goods_cat = array(); + $goods_cat['goods_id'] = $row['gid']; + $cat_id_list = explode(',', trim($row['linkclass'], ',')); + foreach ($cat_id_list as $cat_id) + { + $goods_cat['cat_id'] = $cat_id; + if (!$db->autoExecute($ecs->table('goods_cat'), $goods_cat, 'INSERT', '', 'SILENT')) + { + //return $db->error(); + } + } + } + + /* 取得该分类的所有属性 */ + $sql = "SELECT DISTINCT pv.prop_id, pv.prop_value " . + "FROM ".$this->sprefix."mall_goods_prop_grp_value AS gp, " . + $this->sprefix."mall_prop_value AS pv " . + "WHERE gp.prop_value_id = pv.prop_value_id " . + "AND gp.gid = '$row[gid]'"; + $res1 = $this->sdb->query($sql); + while ($attr = $this->sdb->fetchRow($res1)) + { + $goods_attr = array(); + $goods_attr['goods_id'] = $row['gid']; + $goods_attr['attr_id'] = $attr['prop_id']; + $goods_attr['attr_value'] = ecs_iconv($this->scharset, $this->tcharset, addslashes($attr['prop_value'])); + $goods_attr['attr_price'] = '0'; + if (!$db->autoExecute($ecs->table('goods_attr'), $goods_attr, 'INSERT', '', 'SILENT')) + { + //return $db->error(); + } + } + + /* 商品相册 */ + if ($row['multi_image']) + { + $goods_gallery = array(); + $goods_gallery['goods_id'] = $row['gid']; + $img_list = explode('&&&', $row['multi_image']); + foreach ($img_list as $img) + { + if (substr($img, 0, 7) == 'http://') + { + $goods_gallery['img_url'] = $img; + } + else + { + make_dir('images/' . date('Ym') . '/'); + $goods_gallery['img_url'] = 'images/' . date('Ym') . '/big_' . $img; + $goods_gallery['img_original'] = 'images/' . date('Ym') . '/original_' . $img; + } + + if (!$db->autoExecute($ecs->table('goods_gallery'), $goods_gallery, 'INSERT', '', 'SILENT')) + { + //return $db->error(); + } + } + } + } + + /* 关联商品 */ + $sql = "SELECT * FROM ".$this->sprefix."mall_offer_linkgoods"; + $res = $this->sdb->query($sql); + while ($row = $this->sdb->fetchRow($res)) + { + $link_goods = array(); + $link_goods['goods_id'] = $row['pgid']; + $link_goods['link_goods_id'] = $row['sgid']; + $link_goods['is_double'] = $row['type']; + + if (!$db->autoExecute($ecs->table('link_goods'), $link_goods, 'INSERT', '', 'SILENT')) + { + //return $db->error(); + } + + if ($row['type'] == '1') + { + $link_goods = array(); + $link_goods['goods_id'] = $row['sgid']; + $link_goods['link_goods_id'] = $row['pgid']; + $link_goods['is_double'] = $row['type']; + + if (!$db->autoExecute($ecs->table('link_goods'), $link_goods, 'INSERT', '', 'SILENT')) + { + //return $db->error(); + } + } + } + + /* 组合商品 */ + $sql = "SELECT DISTINCT gid, prop_goods_id, price FROM ".$this->sprefix."mall_pcat_prop_has_goods"; + $res = $this->sdb->query($sql); + while ($row = $this->sdb->fetchRow($res)) + { + $group_goods = array(); + $group_goods['parent_id'] = $row['gid']; + $group_goods['goods_id'] = $row['prop_goods_id']; + $group_goods['goods_price'] = $row['price']; + + if (!$db->autoExecute($ecs->table('group_goods'), $group_goods, 'INSERT', '', 'SILENT')) + { + //return $db->error(); + } + } + + /* 返回成功 */ + return TRUE; + } + + /** + * 会员等级、会员、会员价格 + */ + function process_users() + { + global $db, $ecs; + + /* 清空会员、会员等级、会员价格、用户红包、用户地址、帐户明细 */ + truncate_table('user_rank'); + truncate_table('users'); + truncate_table('user_address'); + truncate_table('user_bonus'); + truncate_table('member_price'); + truncate_table('user_account'); + + /* 查询并插入会员等级 */ + $sql = "SELECT * FROM ".$this->sprefix."mall_member_level order by point desc"; + $res = $this->sdb->query($sql); + $max_points = 50000; + while ($row = $this->sdb->fetchRow($res)) + { + $user_rank = array(); + $user_rank['rank_id'] = $row['levelid']; + $user_rank['rank_name'] = ecs_iconv($this->scharset, $this->tcharset, addslashes($row['name'])); + $user_rank['min_points'] = $row['point']; + $user_rank['max_points'] = $max_points; + $user_rank['discount'] = round($row['discount'] * 100); + $user_rank['show_price'] = '1'; + $user_rank['special_rank'] = '0'; + + if (!$db->autoExecute($ecs->table('user_rank'), $user_rank, 'INSERT', '', 'SILENT')) + { + //return $db->error(); + } + + $max_points = $row['point'] - 1; + } + + /* 查询并插入会员 */ + $sql = "SELECT * FROM ".$this->sprefix."mall_member"; + $res = $this->sdb->query($sql); + while ($row = $this->sdb->fetchRow($res)) + { + $user = array(); + $user['user_id'] = $row['userid']; + $user['email'] = $row['email']; + $user['user_name'] = ecs_iconv($this->scharset, $this->tcharset, addslashes($row['user'])); + $user['password'] = $row['password']; + $user['question'] = ecs_iconv($this->scharset, $this->tcharset, addslashes($row['pw_question'])); + $user['answer'] = ecs_iconv($this->scharset, $this->tcharset, addslashes($row['pw_answer'])); + $user['sex'] = $row['sex']; + if (!empty($row['birthday'])) + { + $birthday = strtotime($row['birthday']); + if ($birthday != -1 && $birthday !== false) + { + $user['birthday'] = date('Y-m-d', $birthday); + } + } + $user['user_money'] = $row['advance']; + $user['pay_points'] = $row['point']; + $user['rank_points'] = $row['point']; + $user['reg_time'] = $row['regtime']; + $user['last_login'] = $row['regtime']; + $user['last_ip'] = $row['ip']; + $user['visit_count'] = '1'; + $user['user_rank'] = '0'; + + if (!$db->autoExecute($ecs->table('users'), $user, 'INSERT', '', 'SILENT')) + { + //return $db->error(); + } + // uc_call('uc_user_register', array($user['user_name'], $user['password'], $user['email'])); + } + + /* 收货人地址 */ + $sql = "SELECT * FROM ".$this->sprefix."mall_member_receiver"; + $res = $this->sdb->query($sql); + while ($row = $this->sdb->fetchRow($res)) + { + $address = array(); + $address['address_id'] = $row['receiveid']; + $address['address_name'] = ecs_iconv($this->scharset, $this->tcharset, addslashes($row['name'])); + $address['user_id'] = $row['memberid']; + $address['consignee'] = ecs_iconv($this->scharset, $this->tcharset, addslashes($row['name'])); + $address['email'] = $row['email']; + $address['address'] = ecs_iconv($this->scharset, $this->tcharset, addslashes($row['address'])); + $address['zipcode'] = $row['zipcode']; + $address['tel'] = $row['telphone']; + $address['mobile'] = $row['mobile']; + + if (!$db->autoExecute($ecs->table('user_address'), $address, 'INSERT', '', 'SILENT')) + { + //return $db->error(); + } + } + + /* 会员价格 */ + $temp_arr = array(); + $sql = "SELECT * FROM ".$this->sprefix."mall_member_price"; + $res = $this->sdb->query($sql); + while ($row = $this->sdb->fetchRow($res)) + { + if ($row['gid'] > 0 && $row['levelid'] > 0 && !isset($temp_arr[$row['gid']][$row['levelid']])) + { + $temp_arr[$row['gid']][$row['levelid']] = true; + + $member_price = array(); + $member_price['goods_id'] = $row['gid']; + $member_price['user_rank'] = $row['levelid']; + $member_price['user_price'] = $row['price']; + + if (!$db->autoExecute($ecs->table('member_price'), $member_price, 'INSERT', '', 'SILENT')) + { + //return $db->error(); + } + } + } + unset($temp_arr); + + /* 帐户明细 */ + $sql = "SELECT * FROM ".$this->sprefix."mall_member_advance"; + $res = $this->sdb->query($sql); + while ($row = $this->sdb->fetchRow($res)) + { + $user_account = array(); + $user_account['user_id'] = $row['memberid']; + $user_account['admin_user'] = $row['doman']; + $user_account['amount'] = $row['money']; + $user_account['add_time'] = $row['date']; + $user_account['paid_time'] = $row['date']; + $user_account['admin_note'] = $row['description']; + $user_account['process_type'] = $row['money'] >= 0 ? SURPLUS_SAVE : SURPLUS_RETURN; + $user_account['is_paid'] = '1'; + + if (!$db->autoExecute($ecs->table('user_account'), $user_account, 'INSERT', '', 'SILENT')) + { + //return $db->error(); + } + } + + /* 返回 */ + return TRUE; + } + + /** + * 文章 + */ + function process_article() + { + global $db, $ecs; + + /* 清空文章类型、文章、友情链接 */ + truncate_table('article_cat'); + truncate_table('article'); + truncate_table('friend_link'); + + /* 文章类型 */ + $sql = "SELECT * FROM ".$this->sprefix."mall_offer_ncat"; + $res = $this->sdb->query($sql); + while ($row = $this->sdb->fetchRow($res)) + { + $cat = array(); + $cat['cat_id'] = $row['catid']; + $cat['cat_name'] = ecs_iconv($this->scharset, $this->tcharset, addslashes($row['cat'])); + $cat['cat_type'] = '1'; + $cat['sort_order'] = $row['pid']; + $cat['is_open'] = '1'; + + if (!$db->autoExecute($ecs->table('article_cat'), $cat, 'INSERT', '', 'SILENT')) + { + //return $db->error(); + } + } + + /* 文章 */ + $sql = "SELECT * FROM ".$this->sprefix."mall_offer_ncon"; + $res = $this->sdb->query($sql); + while ($row = $this->sdb->fetchRow($res)) + { + $article = array(); + $article['article_id'] = $row['newsid']; + $article['cat_id'] = $row['catid']; + $article['title'] = ecs_iconv($this->scharset, $this->tcharset, addslashes($row['title'])); + $article['content'] = ecs_iconv($this->scharset, $this->tcharset, addslashes($row['con'])); + $article['content'] = str_replace('pictures/newsimg/', 'images/upload/Image/', $article['content']); + $article['article_type']= '0'; + $article['is_open'] = $row['ifpub']; + $article['add_time'] = $row['uptime']; + + if (!$db->autoExecute($ecs->table('article'), $article, 'INSERT', '', 'SILENT')) + { + //return $db->error(); + } + } + + /* 友情链接 */ + $sql = "SELECT * FROM ".$this->sprefix."mall_offer_link"; + $res = $this->sdb->query($sql); + while ($row = $this->sdb->fetchRow($res)) + { + $link = array(); + $link['link_id'] = $row['linkid']; + $link['link_name'] = ecs_iconv($this->scharset, $this->tcharset, addslashes($row['linktitle'])); + $link['link_url'] = $row['linkurl']; + $link['show_order'] = '0'; + + if ($row['linktype'] == 'image') + { + $link['link_logo'] = 'data/afficheimg/'.$row['imgurl']; + } + + if (!$db->autoExecute($ecs->table('friend_link'), $link, 'INSERT', '', 'SILENT')) + { + //return $db->error(); + } + } + + /* 返回 */ + return TRUE; + } + + /** + * 订单 + */ + function process_order() + { + global $db, $ecs; + + /* 清空订单、订单商品 */ + truncate_table('order_info'); + truncate_table('order_goods'); + truncate_table('order_action'); + + /* 订单 */ + $sql = "SELECT o.*, t.tmethod, p.payment FROM ".$this->sprefix."mall_orders AS o " . + "LEFT JOIN ".$this->sprefix."mall_offer_t AS t ON o.ttype = t.id " . + "LEFT JOIN ".$this->sprefix."mall_offer_p AS p ON o.ptype = p.id"; + $res = $this->sdb->query($sql); + while ($row = $this->sdb->fetchRow($res)) + { + $order = array(); + $order['order_sn'] = $row['orderid']; + $order['user_id'] = $row['userid']; + $order['add_time'] = $row['ordertime']; + $order['consignee'] = ecs_iconv($this->scharset, $this->tcharset, addslashes($row['name'])); + $order['address'] = ecs_iconv($this->scharset, $this->tcharset, addslashes($row['addr'])); + $order['zipcode'] = $row['zip']; + $order['tel'] = $row['tel']; + $order['mobile'] = $row['mobile']; + $order['email'] = $row['email']; + $order['postscript'] = ecs_iconv($this->scharset, $this->tcharset, addslashes($row['memo'])); + $order['shipping_name'] = is_null($row['tmethod']) ? ' ' : ecs_iconv($this->scharset, $this->tcharset, addslashes($row['tmethod'])); + $order['pay_name'] = is_null($row['payment']) ? ' ' : ecs_iconv($this->scharset, $this->tcharset, addslashes($row['payment'])); + $order['inv_payee'] = ecs_iconv($this->scharset, $this->tcharset, addslashes($row['invoiceform'])); + $order['goods_amount'] = $row['item_amount']; + $order['shipping_fee'] = $row['freight']; + $order['order_amount'] = $row['total_amount']; + $order['pay_time'] = $row['paytime']; + $order['shipping_time'] = $row['sendtime']; + + /* 状态 */ + if ($row['ordstate'] == '0') + { + $order['order_status'] = OS_UNCONFIRMED; + $order['shipping_status'] = SS_UNSHIPPED; + } + elseif ($row['ordstate'] == '1') + { + $order['order_status'] = OS_CONFIRMED; + $order['shipping_status'] = SS_UNSHIPPED; + } + elseif ($row['ordstate'] == '9') + { + $order['order_status'] = OS_INVALID; + $order['shipping_status'] = SS_UNSHIPPED; + } + else // 3 发货 4 归档 + { + $order['order_status'] = OS_CONFIRMED; + $order['shipping_status'] = SS_SHIPPED; + } + + if ($row['ifsk'] == '1') + { + $order['pay_status'] = PS_PAYED; + } + else // 0 未付款 5 退款 + { + $order['pay_status'] = PS_UNPAYED; + } + + if ($row['userrecsts'] == '1') // 用户操作了 + { + if ($row['recsts'] == '1') // 到货 + { + if ($order['shipping_status'] == SS_SHIPPED) + { + $order['shipping_status'] = SS_RECEIVED; + } + } + elseif ($row['recsts'] == '2') // 取消 + { + $order['order_status'] = OS_CANCELED; + $order['pay_status'] = PS_UNPAYED; + $order['shipping_status'] = SS_UNSHIPPED; + } + } + + /* 如果已付款,修改已付款金额为订单总金额,修改订单总金额为0 */ + if ($order['pay_status'] > PS_UNPAYED) + { + $order['money_paid'] = $order['order_amount']; + $order['order_amount'] = 0; + } + + if (!$db->autoExecute($ecs->table('order_info'), $order, 'INSERT', '', 'SILENT')) + { + //return $db->error(); + } + + /* 订单商品 */ + $order_id = $db->insert_id(); + $sql = "SELECT i.*, g.priceintro FROM ".$this->sprefix."mall_items AS i " . + "LEFT JOIN ".$this->sprefix."mall_goods AS g ON i.gid = g.gid " . + "WHERE orderid = '$row[orderid]'"; + $res1 = $this->sdb->query($sql); + while ($row = $this->sdb->fetchRow($res1)) + { + $goods = array(); + $goods['order_id'] = $order_id; + $goods['goods_id'] = $row['gid']; + $goods['goods_name'] = ecs_iconv($this->scharset, $this->tcharset, addslashes($row['goods'])); + $goods['goods_sn'] = ecs_iconv($this->scharset, $this->tcharset, addslashes($row['bn'])); + $goods['goods_number'] = $row['nums']; + $goods['goods_price'] = $row['price']; + $goods['market_price'] = is_null($row['priceintro']) ? $row['goods_price'] : $row['priceintro']; + $goods['is_real'] = 1; + $goods['parent_id'] = 0; + $goods['is_gift'] = 0; + + if (!$db->autoExecute($ecs->table('order_goods'), $goods, 'INSERT', '', 'SILENT')) + { + //return $db->error(); + } + } + } + + /* 返回 */ + return TRUE; + } + + /** + * 商店设置 + */ + function process_config() + { + global $ecs, $db; + + /* 查询设置 */ + $sql = "SELECT * FROM ".$this->sprefix."mall_offer " . + "WHERE offerid = '1'"; + $row = $this->sdb->getRow($sql); + + $config = array(); + $config['shop_name'] = ecs_iconv($this->scharset, $this->tcharset, addslashes($row['offer_name'])); + $config['shop_title'] = ecs_iconv($this->scharset, $this->tcharset, addslashes($row['offer_shoptitle'])); + $config['shop_desc'] = ecs_iconv($this->scharset, $this->tcharset, addslashes($row['offer_metadesc'])); + $config['shop_address'] = ecs_iconv($this->scharset, $this->tcharset, addslashes($row['offer_addr'])); + $config['service_email'] = $row['offer_email']; + $config['service_phone'] = $row['offer_tel']; + $config['icp_number'] = ecs_iconv($this->scharset, $this->tcharset, addslashes($row['offer_certtext'])); + //$config['integral_scale'] = $row['offer_pointtype'] == '0' ? '0' : $row['offer_pointnum'] * 100; + $config['thumb_width'] = $row['offer_smallsize_w']; + $config['thumb_height'] = $row['offer_smallsize_h']; + $config['image_width'] = $row['offer_bigsize_w']; + $config['image_height'] = $row['offer_bigsize_h']; + $config['promote_number'] = $row['offer_tejianums']; + $config['best_number'] = $row['offer_tjnums']; + $config['new_number'] = $row['offer_newgoodsnums']; + $config['hot_number'] = $row['offer_hotnums']; + $config['smtp_host'] = $row['offer_smtp_server']; + $config['smtp_port'] = $row['offer_smtp_port']; + $config['smtp_user'] = $row['offer_smtp_user']; + $config['smtp_pass'] = $row['offer_smtp_password']; + $config['smtp_mail'] = $row['offer_smtp_email']; + + /* 更新 */ + foreach ($config as $code => $value) + { + $sql = "UPDATE " . $ecs->table('shop_config') . " SET " . + "value = '$value' " . + "WHERE code = '$code' LIMIT 1"; + if (!$db->query($sql, 'SILENT')) + { + //return $db->error(); + } + } + + /* 返回 */ + return TRUE; + } + +} + +?> \ No newline at end of file diff --git a/includes/modules/convert/shopex48.php b/includes/modules/convert/shopex48.php new file mode 100644 index 0000000..72f576f --- /dev/null +++ b/includes/modules/convert/shopex48.php @@ -0,0 +1,730 @@ +sdb = $sdb; + $this->sprefix = $sprefix; + $this->sroot = $sroot; + $this->troot = str_replace('/includes/modules/convert', '', str_replace('\\', '/', dirname(__FILE__))); + $this->tdocroot = str_replace('/' . ADMIN_PATH, '', dirname(PHP_SELF)); + $this->scharset = $scharset; + if (EC_CHARSET == 'utf-8') + { + $tcharset = 'UTF8'; + } + elseif (EC_CHARSET == 'gbk') + { + $tcharset = 'GB2312'; + } + $this->tcharset = $tcharset; + } + + /** + * 需要转换的表(用于检查数据库是否完整) + * @return array + */ + function required_tables() + { + return array( + $this->sprefix.'goods', + ); + } + + /** + * 必需的目录 + * @return array + */ + function required_dirs() + { + return array( + '/images/goods/', + '/images/brand/', + '/images/link/', + ); + } + + /** + * 下一步操作:空表示结束 + * @param string $step 当前操作:空表示开始 + * @return string + */ + function next_step($step) + { + /* 所有操作 */ + $steps = array( + '' => 'step_file', + 'step_file' => 'step_cat', + 'step_cat' => 'step_brand', + 'step_brand' => 'step_goods', + 'step_goods' => 'step_users', + 'step_users' => 'step_article', + 'step_article' => 'step_order', + 'step_order' => 'step_config', + 'step_config' => '', + ); + + return $steps[$step]; + } + + /** + * 执行某个步骤 + * @param string $step + */ + function process($step) + { + $func = str_replace('step', 'process', $step); + return $this->$func(); + } + + /** + * 复制文件 + * @return 成功返回true,失败返回错误信息 + */ + function process_file() + { + /* 复制品牌图片 */ + $from = $this->sroot . '/images/brand/'; + $to = $this->troot . '/data/brandlogo/'; + copy_dirs($from, $to); + + /* 复制商品图片 */ + $to = $this->troot . '/images/goods/'; + + $from = $this->sroot . '/images/goods/'; + copy_dirs($from, $to); + + /* 复制友情链接图片 */ + $from = $this->sroot . '/images/link/'; + $to = $this->troot . '/data/afficheimg/'; + copy_dirs($from, $to); + + return TRUE; + } + + /** + * 商品分类 + * @return 成功返回true,失败返回错误信息 + */ + function process_cat() + { + global $db, $ecs; + + /* 清空分类、商品类型、属性 */ + truncate_table('category'); + truncate_table('goods_type'); + //truncate_table('attribute'); + + /* 查询分类并循环处理 */ + $sql = "SELECT * FROM ".$this->sprefix."goods_cat"; + $res = $this->sdb->query($sql); + while ($row = $this->sdb->fetchRow($res)) + { + $cat = array(); + $cat['cat_id'] = $row['cat_id']; + $cat['cat_name'] = $row['cat_name']; + $cat['parent_id'] = $row['parent_id']; + $cat['sort_order'] = $row['p_order']; + + /* 插入分类 */ + if (!$db->autoExecute($ecs->table('category'), $cat, 'INSERT', '', 'SILENT')) + { + //return $db->error(); + } + } + + /* 查询商品类型并循环处理 */ + $sql = "SELECT * FROM ".$this->sprefix."goods_type"; + $res = $this->sdb->query($sql); + while ($row = $this->sdb->fetchRow($res)) + { + $type = array(); + $type['cat_id'] = $row['prop_cat_id']; + $type['cat_name'] = $row['name']; + $type['enabled'] = '1'; + if (!$db->autoExecute($ecs->table('goods_type'), $type, 'INSERT', '', 'SILENT')) + { + //return $db->error(); + } + } + + /* 查询属性值并循环处理 */ + + + /* 返回成功 */ + return true; + } + + /** + * 品牌 + * @return 成功返回true,失败返回错误信息 + */ + function process_brand() + { + global $db, $ecs; + + /* 清空品牌 */ + truncate_table('brand'); + + /* 查询品牌并插入 */ + $sql = "SELECT * FROM ".$this->sprefix."brand"; + $res = $this->sdb->query($sql); + while ($row = $this->sdb->fetchRow($res)) + { + $brand_logo = ecs_iconv($this->scharset, $this->tcharset, addslashes($row['brand_logo'])); + $logoarr = explode('|',$brand_logo); + if(strpos($logoarr[0],'http') === 0){ + $brand_url = $logoarr[0]; + + }else{ + $logourl = explode('/',$logoarr[0],3); + $brand_url = $logourl[2]; + } + + $brand = array( + 'brand_name' => $row['brand_name'], + 'brand_desc' => '', + 'site_url' => ecs_iconv($this->scharset, $this->tcharset, addslashes($row['brand_url'])), + 'brand_logo' => $brand_url + ); + if (!$db->autoExecute($ecs->table('brand'), $brand, 'INSERT', '', 'SILENT')) + { + //return $db->error(); + } + } + + /* 返回成功 */ + return TRUE; + } + + /** + * 商品 + * @return 成功返回true,失败返回错误信息 + */ + function process_goods() + { + global $db, $ecs; + + /* 清空商品、商品扩展分类、商品属性、商品相册、关联商品、组合商品、赠品 */ + truncate_table('goods'); + truncate_table('goods_cat'); + truncate_table('goods_attr'); + truncate_table('goods_gallery'); + truncate_table('link_goods'); + truncate_table('group_goods'); + + + /* 查询品牌列表 name => id */ + $brand_list = array(); + $sql = "SELECT brand_id, brand_name FROM " . $ecs->table('brand'); + $res = $db->query($sql); + while ($row = $db->fetchRow($res)) + { + $brand_list[$row['brand_name']] = $row['brand_id']; + } + + /* 取得商店设置 */ + + + /* 取得商品分类对应的商品类型 */ + $cat_type_list = array(); + $sql = "SELECT cat_id, supplier_cat_id FROM ".$this->sprefix."goods_cat"; + $res = $this->sdb->query($sql); + while ($row = $this->sdb->fetchRow($res)) + { + $cat_type_list[$row['cat_id']] = $row['supplier_cat_id']; + } + + /* 查询商品并处理 */ + $sql = "SELECT * FROM ".$this->sprefix."goods"; + $res = $this->sdb->query($sql); + while ($row = $this->sdb->fetchRow($res)) + { + $goods = array(); + + + $goods['goods_id'] = $row['goods_id']; + $goods['cat_id'] = $row['cat_id']; + $goods['goods_sn'] = $row['bn']; + $goods['goods_name'] = $row['name']; + $goods['brand_id'] = trim($row['brand']) == '' ? '0' : $brand_list[ecs_iconv($this->scharset, $this->tcharset, addslashes($row['brand']))]; + $goods['goods_number'] = $row['store']; + $goods['goods_weight'] = $row['weight']; + $goods['market_price'] = $row['mktprice']; + $goods['shop_price'] = $row['price']; + $goods['promote_price'] = $row['name']; + $goods['goods_brief'] = $row['brief']; + $goods['goods_desc'] = $row['intro']; + //$goods['is_on_sale'] = $row['shop_iffb']; + //$goods['is_alone_sale'] = $row['onsale']; + $goods['add_time'] = $row['uptime']; + //$goods['sort_order'] = $row['offer_ord']; + //$goods['is_delete'] = '0'; + //$goods['is_best'] = $row['recommand2']; + //$goods['is_new'] = $row['new2']; + //$goods['is_hot'] = $row['hot2']; + //$goods['is_promote'] = $row['tejia2']; + //$goods['goods_type'] = isset($cat_type_list[$row['cat_id']]) ? $cat_type_list[$row['cat_id']] : 0; + $big_pic = $row['big_pic']; + $big_pic_arr = explode('|',$big_pic); + $small_pic = $row['small_pic']; + $small_pic_arr = explode('|',$small_pic); + $goods['goods_img'] = $small_pic_arr[0]; + $goods['goods_thumb'] = $small_pic_arr[0]; + $goods['original_img'] = $small_pic_arr[0]; + $goods['last_update'] = gmtime(); + + /* 插入 */ + if (!$db->autoExecute($ecs->table('goods'), $goods, 'INSERT', '', 'SILENT')) + { + //return $db->error(); + } + + /* 商品相册 */ + $sql2 = "SELECT * FROM ".$this->sprefix."gimages"; + $result = $this->sdb->query($sql2); + while ($row2 = $this->sdb->fetchRow($result)) + { + $goods_gallery = array(); + $goods_gallery['goods_id'] = $row2['goods_id']; + $big_pic = $row2['big']; + $big_pic_arr = explode('|',$big_pic); + $goods_gallery['img_original'] = $big_pic_arr[0]; + $small_pic = $row2['small']; + $small_pic_arr = explode('|',$small_pic); + $goods_gallery['thumb_url'] = $small_pic_arr[0]; + $goods_gallery['img_url'] = $goods_gallery['thumb_url']; + //$goods['original_img'] = $big_pic; + + if (!$db->autoExecute($ecs->table('goods_gallery'), $goods_gallery, 'INSERT', '', 'SILENT')) + { + //return $db->error(); + } + } + + } + + /* 返回成功 */ + return TRUE; + } + + /** + * 会员等级、会员、会员价格 + */ + function process_users() + { + global $db, $ecs; + + /* 清空会员、会员等级、会员价格、用户红包、用户地址、帐户明细 */ + truncate_table('user_rank'); + truncate_table('users'); + truncate_table('user_address'); + truncate_table('user_bonus'); + truncate_table('member_price'); + truncate_table('user_account'); + + /* 查询并插入会员等级 */ + $sql = "SELECT * FROM ".$this->sprefix."member_lv order by point desc"; + $res = $this->sdb->query($sql); + $max_points = 50000; + while ($row = $this->sdb->fetchRow($res)) + { + $user_rank = array(); + $user_rank['rank_id'] = $row['member']; + $user_rank['rank_name'] = $row['name']; + $user_rank['min_points'] = $row['point']; + $user_rank['max_points'] = $max_points; + $user_rank['discount'] = round($row['dis_count'] * 100); + $user_rank['show_price'] = '1'; + $user_rank['special_rank'] = '0'; + + if (!$db->autoExecute($ecs->table('user_rank'), $user_rank, 'INSERT', '', 'SILENT')) + { + //return $db->error(); + } + + $max_points = $row['point'] - 1; + } + + /* 查询并插入会员 */ + $sql = "SELECT * FROM ".$this->sprefix."members"; + $res = $this->sdb->query($sql); + while ($row = $this->sdb->fetchRow($res)) + { + $user = array(); + $user['user_id'] = $row['member_id']; + $user['email'] = $row['email']; + $user['user_name'] = ecs_iconv($this->scharset, $this->tcharset, addslashes($row['uname'])); + $user['password'] = $row['password']; + $user['question'] = ecs_iconv($this->scharset, $this->tcharset, addslashes($row['pw_question'])); + $user['answer'] = ecs_iconv($this->scharset, $this->tcharset, addslashes($row['pw_answer'])); + $user['sex'] = $row['sex']; + if (!empty($row['birthday'])) + { + $birthday = strtotime($row['birthday']); + if ($birthday != -1 && $birthday !== false) + { + $user['birthday'] = date('Y-m-d', $birthday); + } + } + $user['user_money'] = $row['advance']; + $user['pay_points'] = $row['point']; + $user['rank_points'] = $row['point']; + $user['reg_time'] = $row['regtime']; + $user['last_login'] = $row['regtime']; + $user['last_ip'] = $row['reg_ip']; + $user['visit_count'] = '1'; + $user['user_rank'] = '0'; + + if (!$db->autoExecute($ecs->table('users'), $user, 'INSERT', '', 'SILENT')) + { + //return $db->error(); + } + //uc_call('uc_user_register', array($user['user_name'], $user['password'], $user['email'])); + } + + /* 收货人地址 */ + $sql = "SELECT * FROM ".$this->sprefix."member_addrs"; + $res = $this->sdb->query($sql); + while ($row = $this->sdb->fetchRow($res)) + { + $address = array(); + $address['address_id'] = $row['addr_id']; + $address['address_name'] = ecs_iconv($this->scharset, $this->tcharset, addslashes($row['name'])); + $address['user_id'] = $row['member_id']; + $address['consignee'] = ecs_iconv($this->scharset, $this->tcharset, addslashes($row['name'])); + //$address['email'] = $row['email']; + $address['address'] = ecs_iconv($this->scharset, $this->tcharset, addslashes($row['addr'])); + $address['zipcode'] = $row['zip']; + $address['tel'] = $row['tel']; + $address['mobile'] = $row['mobile']; + $address['country'] = $row['country']; + $address['province'] = $row['province']; + $address['city'] = $row['city']; + + if (!$db->autoExecute($ecs->table('user_address'), $address, 'INSERT', '', 'SILENT')) + { + //return $db->error(); + } + } + + /* 会员价格 */ + $temp_arr = array(); + $sql = "SELECT * FROM ".$this->sprefix."goods_lv_price"; + $res = $this->sdb->query($sql); + while ($row = $this->sdb->fetchRow($res)) + { + if ($row['goods_id'] > 0 && $row['level_id'] > 0 && !isset($temp_arr[$row['goods_id']][$row['level_id']])) + { + $temp_arr[$row['goods_id']][$row['level_id']] = true; + + $member_price = array(); + $member_price['goods_id'] = $row['goods_id']; + $member_price['user_rank'] = $row['level_id']; + $member_price['user_price'] = $row['price']; + + if (!$db->autoExecute($ecs->table('member_price'), $member_price, 'INSERT', '', 'SILENT')) + { + //return $db->error(); + } + } + } + unset($temp_arr); + + /* 帐户明细 */ + $sql = "SELECT * FROM ".$this->sprefix."advance_logs"; + $res = $this->sdb->query($sql); + while ($row = $this->sdb->fetchRow($res)) + { + $user_account = array(); + $user_account['user_id'] = $row['member_id']; + $user_account['admin_user'] = $row['memo']; + $user_account['amount'] = $row['money']; + $user_account['add_time'] = $row['mtime']; + $user_account['paid_time'] = $row['mtime']; + $user_account['admin_note'] = $row['message']; + $user_account['payment'] = $row['paymethod']; + $user_account['process_type'] = $row['money'] >= 0 ? SURPLUS_SAVE : SURPLUS_RETURN; + $user_account['is_paid'] = '1'; + + if (!$db->autoExecute($ecs->table('user_account'), $user_account, 'INSERT', '', 'SILENT')) + { + //return $db->error(); + } + } + /* 返回 */ + return TRUE; + } + + /** + * 文章 + */ + function process_article() + { + global $db, $ecs; + + /* 清空文章类型、文章、友情链接 */ + //truncate_table('article_cat'); + //truncate_table('article'); + truncate_table('friend_link'); + + /* 文章 */ + $sql = "SELECT * FROM ".$this->sprefix."articles"; + $res = $this->sdb->query($sql); + while ($row = $this->sdb->fetchRow($res)) + { + $article = array(); + $article['article_id'] = $row['article_id']; + $article['cat_id'] = $row['node_id']; + $article['title'] = ecs_iconv($this->scharset, $this->tcharset, addslashes($row['title'])); + $article['content'] = ecs_iconv($this->scharset, $this->tcharset, addslashes($row['content'])); + $article['content'] = str_replace('pictures/newsimg/', 'images/upload/Image/', $article['content']); + $article['article_type']= '0'; + $article['is_open'] = $row['ifpub']; + $article['add_time'] = $row['uptime']; + + if (!$db->autoExecute($ecs->table('article'), $article, 'INSERT', '', 'SILENT')) + { + //return $db->error(); + } + } + + /* 友情链接 */ + $sql = "SELECT * FROM ".$this->sprefix."link"; + $res = $this->sdb->query($sql); + while ($row = $this->sdb->fetchRow($res)) + { + $link = array(); + $link['link_id'] = $row['link_id']; + $link['link_name'] = ecs_iconv($this->scharset, $this->tcharset, addslashes($row['link_name'])); + $link['link_url'] = $row['href']; + $link['show_order'] = '0'; + $link_logo = $row['image_url']; + $logoarr = explode('|',$link_logo); + $logourl = explode('/',$logoarr[0],3); + $link['link_logo'] = 'data/afficheimg/'.$logourl[2]; + if (!$db->autoExecute($ecs->table('friend_link'), $link, 'INSERT', '', 'SILENT')) + { + //return $db->error(); + } + } + + /* 返回 */ + return TRUE; + } + + /** + * 订单 + */ + function process_order() + { + global $db, $ecs; + + /* 清空订单、订单商品 */ + truncate_table('order_info'); + truncate_table('order_goods'); + truncate_table('order_action'); + + /* 订单 */ + $sql = "SELECT o.* FROM ".$this->sprefix."orders AS o " ; + $res = $this->sdb->query($sql); + while ($row = $this->sdb->fetchRow($res)) + { + $order = array(); + $order['order_sn'] = $row['order_id']; + $order['user_id'] = $row['member_id']; + $order['add_time'] = $row['createtime']; + $order['consignee'] = ecs_iconv($this->scharset, $this->tcharset, addslashes($row['consignee'])); + $order['address'] = ecs_iconv($this->scharset, $this->tcharset, addslashes($row['ship_addr'])); + $order['zipcode'] = $row['ship_zip']; + $order['tel'] = $row['ship_tel']; + $order['mobile'] = $row['ship_mobile']; + $order['email'] = $row['ship_email']; + $order['postscript'] = ecs_iconv($this->scharset, $this->tcharset, addslashes($row['memo'])); + $order['shipping_name'] = ecs_iconv($this->scharset, $this->tcharset, addslashes($row['ship_name'])); + $order['pay_name'] = ecs_iconv($this->scharset, $this->tcharset, addslashes($row['shipping'])); + $order['inv_payee'] = ecs_iconv($this->scharset, $this->tcharset, addslashes($row['tax_company'])); + $order['goods_amount'] = $row['total_amount']; + $order['shipping_fee'] = $row['cost_freight']; + $order['order_amount'] = $row['final_amount']; + $order['pay_time'] = $row['paytime']; + $order['shipping_time'] = $row['acttime']; + + /* 状态 */ + if ($row['ordstate'] == '0') + { + $order['order_status'] = OS_UNCONFIRMED; + $order['shipping_status'] = SS_UNSHIPPED; + } + elseif ($row['ordstate'] == '1') + { + $order['order_status'] = OS_CONFIRMED; + $order['shipping_status'] = SS_UNSHIPPED; + } + elseif ($row['ordstate'] == '9') + { + $order['order_status'] = OS_INVALID; + $order['shipping_status'] = SS_UNSHIPPED; + } + else // 3 发货 4 归档 + { + $order['order_status'] = OS_CONFIRMED; + $order['shipping_status'] = SS_SHIPPED; + } + + if ($row['pay_status'] == '1') + { + $order['pay_status'] = PS_PAYED; + } + else // 0 未付款 5 退款 + { + $order['pay_status'] = PS_UNPAYED; + } + + if ($row['userrecsts'] == '1') // 用户操作了 + { + if ($row['recsts'] == '1') // 到货 + { + if ($order['shipping_status'] == SS_SHIPPED) + { + $order['shipping_status'] = SS_RECEIVED; + } + } + elseif ($row['recsts'] == '2') // 取消 + { + $order['order_status'] = OS_CANCELED; + $order['pay_status'] = PS_UNPAYED; + $order['shipping_status'] = SS_UNSHIPPED; + } + } + + if (!$db->autoExecute($ecs->table('order_info'), $order, 'INSERT', '', 'SILENT')) + { + //return $db->error(); + } + + /* 订单商品 */ + + } + /* 返回 */ + return TRUE; + } + + /** + * 商店设置 + */ + function process_config() + { + global $ecs, $db; + + /* 查询设置 */ + $sql = "SELECT * FROM ".$this->sprefix."settings"; + $row = $this->sdb->getRow($sql); + $store = $row['store']; + $store_arr = unserialize($store); + $config = array(); + //$config['shop_name'] = ecs_iconv($this->scharset, $this->tcharset, addslashes($store_arr[0]); + //$config['shop_title'] = ecs_iconv($this->scharset, $this->tcharset, addslashes($store_arr[0])); + //$config['shop_desc'] = ecs_iconv($this->scharset, $this->tcharset, addslashes($store_arr[1])); + //$config['shop_address'] = ecs_iconv($this->scharset, $this->tcharset, addslashes($row['store'])); + $config['shop_address'] = $row['store']; + //$config['service_email'] = $row['offer_email']; + $config['service_phone'] = $store_arr[2]; + //$config['icp_number'] = ecs_iconv($this->scharset, $this->tcharset, addslashes($row['offer_certtext'])); + //$config['integral_scale'] = $row['offer_pointtype'] == '0' ? '0' : $row['offer_pointnum'] * 100; + //$config['thumb_width'] = $row['offer_smallsize_w']; + //$config['thumb_height'] = $row['offer_smallsize_h']; + //$config['image_width'] = $row['offer_bigsize_w']; + //$config['image_height'] = $row['offer_bigsize_h']; + //$config['promote_number'] = $row['offer_tejianums']; + //$config['best_number'] = $row['offer_tjnums']; + //$config['new_number'] = $row['offer_newgoodsnums']; + //$config['hot_number'] = $row['offer_hotnums']; + //$config['smtp_host'] = $row['offer_smtp_server']; + //$config['smtp_port'] = $row['offer_smtp_port']; + //$config['smtp_user'] = $row['offer_smtp_user']; + //$config['smtp_pass'] = $row['offer_smtp_password']; + //$config['smtp_mail'] = $row['offer_smtp_email']; + + /* 更新 */ + foreach ($config as $code => $value) + { + $sql = "UPDATE " . $ecs->table('shop_config') . " SET " . + "value = '$value' " . + "WHERE code = '$code' LIMIT 1"; + if (!$db->query($sql, 'SILENT')) + { + //return $db->error(); + } + } + + /* 返回 */ + return TRUE; + } + + + +} + +?> \ No newline at end of file diff --git a/includes/modules/cron/auto_manage.php b/includes/modules/cron/auto_manage.php new file mode 100644 index 0000000..e9b4e8b --- /dev/null +++ b/includes/modules/cron/auto_manage.php @@ -0,0 +1,172 @@ + 'auto_manage_count', 'type' => 'select', 'value' => '5'), + ); + + return; +} +$time = gmtime(); +$limit = !empty($cron['auto_manage_count']) ? $cron['auto_manage_count'] : 5; +$sql = "SELECT * FROM " . $GLOBALS['ecs']->table('auto_manage') . " WHERE starttime > '0' AND starttime <= '$time' OR endtime > '0' AND endtime <= '$time' LIMIT $limit"; +$autodb = $db->getAll($sql); +foreach ($autodb as $key => $val) +{ + $del = $up = false; + if ($val['type'] == 'goods') + { + $goods = true; + $where = " WHERE goods_id = '$val[item_id]'"; + } + else + { + $goods = false; + $where = " WHERE article_id = '$val[item_id]'"; + } + + + //上下架判断 + if(!empty($val['starttime']) && !empty($val['endtime'])) + { + //上下架时间均设置 + if($val['starttime'] <= $time && $time < $val['endtime']) + { + //上架时间 <= 当前时间 < 下架时间 + $up = true; + $del = false; + } + elseif($val['starttime'] >= $time && $time > $val['endtime']) + { + //下架时间 <= 当前时间 < 上架时间 + $up = false; + $del = false; + } + elseif($val['starttime'] == $time && $time == $val['endtime']) + { + //下架时间 == 当前时间 == 上架时间 + $sql = "DELETE FROM " . $GLOBALS['ecs']->table('auto_manage') . "WHERE item_id = '$val[item_id]' AND type = '$val[type]'"; + $db->query($sql); + continue; + } + elseif($val['starttime'] > $val['endtime']) + { + // 下架时间 < 上架时间 < 当前时间 + $up = true; + $del = true; + } + elseif($val['starttime'] < $val['endtime']) + { + // 上架时间 < 下架时间 < 当前时间 + $up = false; + $del = true; + } + else + { + // 上架时间 = 下架时间 < 当前时间 + $sql = "DELETE FROM " . $GLOBALS['ecs']->table('auto_manage') . "WHERE item_id = '$val[item_id]' AND type = '$val[type]'"; + $db->query($sql); + + continue; + } + } + elseif(!empty($val['starttime'])) + { + //只设置了上架时间 + $up = true; + $del = true; + } + else + { + //只设置了下架时间 + $up = false; + $del = true; + } + + if ($goods) + { + if ($up) + { + $sql = "UPDATE " . $GLOBALS['ecs']->table('goods') . " SET is_on_sale = 1 $where"; + } + else + { + $sql = "UPDATE " . $GLOBALS['ecs']->table('goods') . " SET is_on_sale = 0 $where"; + } + } + else + { + if ($up) + { + $sql = "UPDATE " . $GLOBALS['ecs']->table('article') . " SET is_open = 1 $where"; + } + else + { + $sql = "UPDATE " . $GLOBALS['ecs']->table('article') . " SET is_open = 0 $where"; + } + } + $db->query($sql); + if ($del) + { + $sql = "DELETE FROM " . $GLOBALS['ecs']->table('auto_manage') . "WHERE item_id = '$val[item_id]' AND type = '$val[type]'"; + $db->query($sql); + } + else + { + if($up) + { + $sql = "UPDATE " . $GLOBALS['ecs']->table('auto_manage') . " SET starttime = 0 WHERE item_id = '$val[item_id]' AND type = '$val[type]'"; + } + else + { + $sql = "UPDATE " . $GLOBALS['ecs']->table('auto_manage') . " SET endtime = 0 WHERE item_id = '$val[item_id]' AND type = '$val[type]'"; + } + $db->query($sql); + } +} +?> \ No newline at end of file diff --git "a/includes/modules/cron/ecshop\346\250\241\346\235\277\347\275\221 - ecshop\346\250\241\346\235\277\345\210\266\344\275\234\344\272\214\346\254\241\345\274\200\345\217\221\347\254\254\344\270\200\347\253\231.url" "b/includes/modules/cron/ecshop\346\250\241\346\235\277\347\275\221 - ecshop\346\250\241\346\235\277\345\210\266\344\275\234\344\272\214\346\254\241\345\274\200\345\217\221\347\254\254\344\270\200\347\253\231.url" new file mode 100644 index 0000000..8360d56 --- /dev/null +++ "b/includes/modules/cron/ecshop\346\250\241\346\235\277\347\275\221 - ecshop\346\250\241\346\235\277\345\210\266\344\275\234\344\272\214\346\254\241\345\274\200\345\217\221\347\254\254\344\270\200\347\253\231.url" @@ -0,0 +1,9 @@ +[DEFAULT] +BASEURL=http://www.ecshoptemplate.com/ +[{000214A0-0000-0000-C000-000000000046}] +Prop3=19,2 +[InternetShortcut] +URL=http://www.ecshoptemplate.com/ +IDList= +IconFile=http://www.ecshoptemplate.com/favicon.ico +IconIndex=1 diff --git a/includes/modules/cron/ipdel.php b/includes/modules/cron/ipdel.php new file mode 100644 index 0000000..ab153ac --- /dev/null +++ b/includes/modules/cron/ipdel.php @@ -0,0 +1,63 @@ + 'ipdel_day', 'type' => 'select', 'value' => '30'), + ); + + return; +} + +empty($cron['ipdel_day']) && $cron['ipdel_day'] = 7; + +$deltime = gmtime() - $cron['ipdel_day'] * 3600 * 24; +$sql = "DELETE FROM " . $ecs->table('stats') . + "WHERE access_time < '$deltime'"; +$db->query($sql); + +?> \ No newline at end of file diff --git "a/includes/modules/cron/\346\234\200\346\250\241\346\235\277 - \344\270\223\346\263\250\347\275\221\345\272\227\345\225\206\345\237\216\346\250\241\346\235\277\345\210\266\344\275\234\344\270\216\345\256\232\345\210\266\345\274\200\345\217\221.url" "b/includes/modules/cron/\346\234\200\346\250\241\346\235\277 - \344\270\223\346\263\250\347\275\221\345\272\227\345\225\206\345\237\216\346\250\241\346\235\277\345\210\266\344\275\234\344\270\216\345\256\232\345\210\266\345\274\200\345\217\221.url" new file mode 100644 index 0000000..f60bd51 --- /dev/null +++ "b/includes/modules/cron/\346\234\200\346\250\241\346\235\277 - \344\270\223\346\263\250\347\275\221\345\272\227\345\225\206\345\237\216\346\250\241\346\235\277\345\210\266\344\275\234\344\270\216\345\256\232\345\210\266\345\274\200\345\217\221.url" @@ -0,0 +1,9 @@ +[DEFAULT] +BASEURL=http://www.zuimoban.com/ +[{000214A0-0000-0000-C000-000000000046}] +Prop3=19,2 +[InternetShortcut] +URL=http://www.zuimoban.com/ +IDList= +IconFile=http://www.zuimoban.com/favicon.ico +IconIndex=1 diff --git "a/includes/modules/ecshop\346\250\241\346\235\277\347\275\221 - ecshop\346\250\241\346\235\277\345\210\266\344\275\234\344\272\214\346\254\241\345\274\200\345\217\221\347\254\254\344\270\200\347\253\231.url" "b/includes/modules/ecshop\346\250\241\346\235\277\347\275\221 - ecshop\346\250\241\346\235\277\345\210\266\344\275\234\344\272\214\346\254\241\345\274\200\345\217\221\347\254\254\344\270\200\347\253\231.url" new file mode 100644 index 0000000..8360d56 --- /dev/null +++ "b/includes/modules/ecshop\346\250\241\346\235\277\347\275\221 - ecshop\346\250\241\346\235\277\345\210\266\344\275\234\344\272\214\346\254\241\345\274\200\345\217\221\347\254\254\344\270\200\347\253\231.url" @@ -0,0 +1,9 @@ +[DEFAULT] +BASEURL=http://www.ecshoptemplate.com/ +[{000214A0-0000-0000-C000-000000000046}] +Prop3=19,2 +[InternetShortcut] +URL=http://www.ecshoptemplate.com/ +IDList= +IconFile=http://www.ecshoptemplate.com/favicon.ico +IconIndex=1 diff --git a/includes/modules/integrates/bmforum.php b/includes/modules/integrates/bmforum.php new file mode 100644 index 0000000..e9a0ee5 --- /dev/null +++ b/includes/modules/integrates/bmforum.php @@ -0,0 +1,357 @@ +bmforum($cfg); + } + + /** + * + * + * @access public + * @param + * + * @return void + */ + function bmforum($cfg) + { + parent::integrate($cfg); + if ($this->error) + { + /* 数据库连接出错 */ + return false; + } + //$this->cookie_prefix = $cfg['cookie_prefix']; + $this->field_id = 'userid'; + $this->field_name = 'username'; + $this->field_email = 'mailadd'; + $this->field_gender = 'sex'; + $this->field_bday = 'birthday'; + $this->field_pass = 'pwd'; + $this->field_reg_date = 'regdate'; + $this->user_table = 'userlist'; + + /* 检查数据表是否存在 */ + $sql = "SHOW TABLES LIKE '" . $this->prefix . "%'"; + + $exist_tables = $this->db->getCol($sql); + + if (empty($exist_tables) || (!in_array($this->prefix.$this->user_table, $exist_tables))) + { + $this->error = 2; + /* 缺少数据表 */ + return false; + } + } + + /** + * 获取论坛有效积分及单位 + * + * @access public + * @param + * + * @return void + */ + function get_points_name () + { + static $ava_credits = NULL; + if ($ava_credits === NULL) + { + $sql = "SELECT value FROM " . $this->table('settings') . " WHERE variable='extcredits'"; + $str = $this->db->getOne($sql); + $extcredits = @unserialize($str); + + $ava_credits = array(); + if ($extcredits) + { + $count = count($extcredits); + for ($i=1; $i <= $count; $i++) + { + if (!empty($extcredits[$i]['available'])) + { + $ava_credits['extcredits' . $i]['title'] = empty($extcredits[$i]['title'])? '' : ($this->charset != 'UTF8') ? ecs_iconv($this->charset, 'UTF8', $extcredits[$i]['title']) : $extcredits[$i]['title']; + $ava_credits['extcredits' . $i]['unit'] = empty($extcredits[$i]['unit'])? '' : ($this->charset != 'UTF8') ? ecs_iconv($this->charset, 'UTF8', $extcredits[$i]['unit']) : $extcredits[$i]['unit']; + } + } + } + } + + return $ava_credits; + } + + /** + * 获取用户积分 + * + * @access public + * @param + * + * @return array + */ + function get_points($username) + { + $credits = $this->get_points_name(); + $fileds = array_keys($credits); + if ($fileds) + { + if ($this->charset != 'UTF8') + { + $username = ecs_iconv('UTF8', $this->charset, $username); + } + $sql = "SELECT " . $this->field_id . ', ' . implode(', ',$fileds). + " FROM " . $this->table($this->user_table). + " WHERE " . $this->field_name . "='$username'"; + $row = $this->db->getRow($sql); + return $row; + } + else + { + return false; + } + } + + /** + * + * + * @access public + * @param + * + * @return void + */ + function set_points ($username, $credits) + { + $user_set = array_keys($credits); + $points_set = array_keys($this->get_points_name()); + + $set = array_intersect($user_set, $points_set); + + if ($set) + { + if ($this->charset != 'UTF8') + { + $username = ecs_iconv('UTF8', $this->charset, $username); + } + $tmp = array(); + foreach ($set as $credit) + { + $tmp[] = $credit . '=' . $credit . '+' . $credits[$credit]; + } + $sql = "UPDATE " . $this->table($this->user_table). + " SET " . implode(', ', $tmp). + " WHERE " . $this->field_name . " = '$username'"; + $this->db->query($sql); + } + + return true; + } + + /** + * 设置论坛cookie + * + * @access public + * @param + * + * @return void + */ + function set_cookie ($username="") + { + parent::set_cookie($username); + if (empty($username)) + { + $time = time() - 3600; + setcookie('bmforumerboardidnum', '', $time, $this->cookie_path, $this->cookie_domain); + setcookie('bmforumerboardpbmfym', '', $time, $this->cookie_path, $this->cookie_domain); + } + else + { + if ($this->charset != 'UTF8') + { + $username = ecs_iconv('UTF8', $this->charset, $username); + } + + $sql = "SELECT " . $this->field_id . " AS user_id, " . $this->field_pass . " As password ". + " FROM " . $this->table($this->user_table) . " WHERE " . $this->field_name . "='$username'"; + + $row = $this->db->getRow($sql); + + setcookie('bmforumerboardidnum', $row['user_id'], time() + 3600 * 24 * 30, $this->cookie_path, $this->cookie_domain); + setcookie('bmforumerboardpbmfym', $row['password'], time() + 3600 * 24 * 30, $this->cookie_path, $this->cookie_domain); + } + } + + /** + * 检查cookie + * + * @access public + * @param + * + * @return void + */ + function check_cookie () + { + if (empty($_COOKIE['bmforumerboardidnum']) || empty($_COOKIE['bmforumerboardpbmfym'])) + { + return ''; + } + + $user_id = intval($_COOKIE['bmforumerboardidnum']); + $password = addslashes_deep(trim($_COOKIE['bmforumerboardpbmfym'])); + + $sql = "SELECT " . $this->field_name . + " FROM " . $this->table($this->user_table). + " WHERE " . $this->field_id . "='$user_id' AND " . $this->field_pass . "='$password'"; + $username = $this->db->getOne($sql); + + if (empty($username)) + { + return ''; + } + else + { + if ($username && ($this->charset != 'UTF8')) + { + $username = ecs_iconv($this->charset, 'UTF8', $username); + } + + return $username; + } + + } + + /** + * discuz 5.5 加密函数,从/include/global.func.php获得 + * + * @access public + * @param + * + * @return void + */ + function authcode($string, $operation, $key = '') + { + $key = md5($key ? $key : $this->authkey); + $key_length = strlen($key); + + $string = $operation == 'DECODE' ? base64_decode($string) : substr(md5($string.$key), 0, 8) . $string; + $string_length = strlen($string); + + $rndkey = $box = array(); + $result = ''; + + for ($i = 0; $i <= 255; $i++) + { + $rndkey[$i] = ord($key[$i % $key_length]); + $box[$i] = $i; + } + + for ($j = $i = 0; $i < 256; $i++) + { + $j = ($j + $box[$i] + $rndkey[$i]) % 256; + $tmp = $box[$i]; + $box[$i] = $box[$j]; + $box[$j] = $tmp; + } + + for ($a = $j = $i = 0; $i < $string_length; $i++) + { + $a = ($a + 1) % 256; + $j = ($j + $box[$a]) % 256; + $tmp = $box[$a]; + $box[$a] = $box[$j]; + $box[$j] = $tmp; + $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256])); + } + + if ($operation == 'DECODE') + { + if (substr($result, 0, 8) == substr(md5(substr($result, 8).$key), 0, 8)) + { + return substr($result, 8); + } + else + { + return ''; + } + } + else + { + return str_replace('=', '', base64_encode($result)); + } + } + + /** + * discuz 5.5 随机函数,从/include/global.func.php获得 + * + * @access public + * @param + * + * @return void + */ + + function random($length, $numeric = 0) { + PHP_VERSION < '4.2.0' && mt_srand((double)microtime() * 1000000); + if($numeric) { + $hash = sprintf('%0'.$length.'d', mt_rand(0, pow(10, $length) - 1)); + } else { + $hash = ''; + $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz'; + $max = strlen($chars) - 1; + for($i = 0; $i < $length; $i++) { + $hash .= $chars[mt_rand(0, $max)]; + } + } + return $hash; + } + +} \ No newline at end of file diff --git a/includes/modules/integrates/discuz.php b/includes/modules/integrates/discuz.php new file mode 100644 index 0000000..870bd7f --- /dev/null +++ b/includes/modules/integrates/discuz.php @@ -0,0 +1,367 @@ +discuz($cfg); + } + + /*------------------------------------------------------ */ + //-- PUBLIC METHODs + /*------------------------------------------------------ */ + + /** + * 会员数据整合插件类的构造函数 + * + * @access public + * @param string $db_host 数据库主机 + * @param string $db_name 数据库名 + * @param string $db_user 数据库用户名 + * @param string $db_pass 数据库密码 + * @return void + */ + function discuz($cfg) + { + parent::integrate($cfg); + if ($this->error) + { + /* 数据库连接出错 */ + return false; + } + $this->cookie_prefix = isset($cfg['prefix']) ? $cfg['prefix'] : ''; + $this->field_id = 'uid'; + $this->field_name = 'username'; + $this->field_email = 'email'; + $this->field_gender = 'gender'; + $this->field_bday = 'bday'; + $this->field_pass = 'password'; + $this->field_reg_date = 'regdate'; + $this->user_table = 'members'; + + /* 检查数据表是否存在 */ + $sql = "SHOW TABLES LIKE '" . $this->prefix . "%'"; + + $exist_tables = $this->db->getCol($sql); + + if (empty($exist_tables) || (!in_array($this->prefix.$this->user_table, $exist_tables)) || (!in_array($this->prefix.'settings', $exist_tables))) + { + $this->error = 2; + /* 缺少数据表 */ + return false; + } + + $key = $this->db->GetOne('SELECT value FROM ' . $this->table('settings') . " WHERE variable = 'authkey'"); + $this->authkey = md5($key . $_SERVER['HTTP_USER_AGENT']); + } + + + /** + * 获取论坛有效积分及单位 + * + * @access public + * @param + * + * @return void + */ + function get_points_name () + { + static $ava_credits = NULL; + if ($ava_credits === NULL) + { + $sql = "SELECT value FROM " . $this->table('settings') . " WHERE variable='extcredits'"; + $str = $this->db->getOne($sql); + $extcredits = @unserialize($str); + + $ava_credits = array(); + if ($extcredits) + { + $count = count($extcredits); + for ($i=1; $i <= $count; $i++) + { + if (!empty($extcredits[$i]['available'])) + { + $ava_credits['extcredits' . $i]['title'] = empty($extcredits[$i]['title'])? '' : ($this->charset != 'UTF8') ? ecs_iconv($this->charset, 'UTF8', $extcredits[$i]['title']) : $extcredits[$i]['title']; + $ava_credits['extcredits' . $i]['unit'] = ''; + } + } + } + } + + return $ava_credits; + } + + /** + * + * + * @access public + * @param + * + * @return void + */ + function set_points ($username, $credits) + { + $user_set = array_keys($credits); + $points_set = array_keys($this->get_points_name()); + + $set = array_intersect($user_set, $points_set); + + if ($set) + { + if ($this->charset != 'UTF8') + { + $username = ecs_iconv('UTF8', $this->charset, $username); + } + $tmp = array(); + foreach ($set as $credit) + { + $tmp[] = $credit . '=' . $credit . '+' . $credits[$credit]; + } + $sql = "UPDATE " . $this->table($this->user_table). + " SET " . implode(', ', $tmp). + " WHERE " . $this->field_name . " = '$username'"; + $this->db->query($sql); + } + + return true; + } + + /** + * 设置论坛cookie + * + * @access public + * @param + * + * @return void + */ + function set_cookie ($username="") + { + parent::set_cookie($username); + if (empty($username)) + { + $time = time() - 3600; + setcookie($this->cookie_prefix.'sid', '', $time, $this->cookie_path, $this->cookie_domain); + setcookie($this->cookie_prefix.'auth', '', $time, $this->cookie_path, $this->cookie_domain); + } + else + { + if ($this->charset != 'UTF8') + { + $username = ecs_iconv('UTF8', $this->charset, $username); + } + $sql = "SELECT " . $this->field_id . " AS user_id, secques AS salt, " . $this->field_pass . " As password ". + " FROM " . $this->table($this->user_table) . " WHERE " . $this->field_name . "='$username'"; + + $row = $this->db->getRow($sql); + + setcookie($this->prefix.'sid', '', time()-3600, $this->cookie_path, $this->cookie_domain); + setcookie($this->prefix.'auth', $this->authcode($row['password']."\t".$row['salt']."\t".$row['user_id'], 'ENCODE'), time() + 3600 * 24 * 30, $this->cookie_path, $this->cookie_domain); + } + } + + /** + * 检查cookie + * + * @access public + * @param + * + * @return void + */ + function check_cookie () + { + if (isset($_COOKIE[$this->cookie_prefix . 'auth'])) + { + $arr = addslashes_deep(explode("\t", $this->authcode($_COOKIE[$this->cookie_prefix . 'auth'], 'DECODE'))); + if (count($arr) != 3) + { + return false; + } + else + { + list($discuz_pw, $discuz_secques, $discuz_uid) = $arr; + } + + $sql = "SELECT " . $this->field_name ." AS user_name". + " FROM " . $this->table($this->user_table) . + " WHERE ".$this->field_id." = '$discuz_uid' AND ".$this->field_pass." = '$discuz_pw'"; + $username = $this->db->getOne($sql); + if ($username && ($this->charset != 'UTF8')) + { + $username = ecs_iconv($this->charset, 'UTF8', $username); + } + + return $username; + } + else + { + return ''; + } + } + + /** + * 添加新用户的函数 + * + * @access public + * @param string username 用户名 + * @param string password 登录密码 + * @param string email 邮件地址 + * @param string bday 生日 + * @param string gender 性别 + * @return int 返回最新的ID + */ + function add_user($username, $password, $email, $gender = -1, $bday = 0, $reg_date=0, $md5password='') + { + $result = parent::add_user($username, $password, $email, $gender, $bday, $reg_date, $md5password); + + if (!$result) + { + return false; + } + + /* 获得默认的用户组 */ + $sql = 'SELECT groupid FROM ' .$this->table('usergroups'). ' WHERE creditshigher <= 0 AND creditslower > 0'; + + $grp = $this->db->getOne($sql); + + if ($this->charset != 'UTF8') + { + $username = ecs_iconv('UTF8', $this->charset, $username); + } + + /* 更新组id */ + $sql = "UPDATE " . $this->table($this->user_table) . + " SET groupid= '$grp', ". + " regip = '" . real_ip() . "',". + " regdate = '" . time() . "'". + " WHERE " . $this->field_name . "='$username'"; + $this->db->query($sql); + + /* 更新memberfields表 */ + $sql = 'INSERT INTO '. $this->table('memberfields') .' ('. $this->field_id .") " . + " SELECT " . $this->field_id . + " FROM " . $this->table($this->user_table) . + " WHERE " . $this->field_name . "='$username'"; + $this->db->query($sql); + + return true; + } + + + /** + * discuz 5.0 加密函数,从/include/global.func.php获得 + * + * @access public + * @param + * + * @return void + */ + function authcode($string, $operation, $key = '') + { + $key = md5($key ? $key : $this->authkey); + $key_length = strlen($key); + + $string = $operation == 'DECODE' ? base64_decode($string) : substr(md5($string. $key), 0, 8) . $string; + $string_length = strlen($string); + + $rndkey = $box = array(); + $result = ''; + + for ($i = 0; $i <= 255; $i++) + { + $rndkey[$i] = ord($key[$i % $key_length]); + $box[$i] = $i; + } + + for ($j = $i = 0; $i < 256; $i++) + { + $j = ($j + $box[$i] + $rndkey[$i]) % 256; + $tmp = $box[$i]; + $box[$i] = $box[$j]; + $box[$j] = $tmp; + } + + for ($a = $j = $i = 0; $i < $string_length; $i++) + { + $a = ($a + 1) % 256; + $j = ($j + $box[$a]) % 256; + $tmp = $box[$a]; + $box[$a] = $box[$j]; + $box[$j] = $tmp; + $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256])); + } + + if ($operation == 'DECODE') + { + if (substr($result, 0, 8) == substr(md5(substr($result, 8) . $key), 0, 8)) + { + return substr($result, 8); + } + else + { + return ''; + } + } + else + { + return str_replace('=', '', base64_encode($result)); + } + + } +} + +?> \ No newline at end of file diff --git a/includes/modules/integrates/discuz55.php b/includes/modules/integrates/discuz55.php new file mode 100644 index 0000000..13e80b1 --- /dev/null +++ b/includes/modules/integrates/discuz55.php @@ -0,0 +1,414 @@ +discuz55($cfg); + } + + /** + * + * + * @access public + * @param + * + * @return void + */ + function discuz55($cfg) + { + parent::integrate($cfg); + if ($this->error) + { + /* 数据库连接出错 */ + return false; + } + $this->cookie_prefix = $cfg['cookie_prefix']; + $this->field_id = 'uid'; + $this->field_name = 'username'; + $this->field_email = 'email'; + $this->field_gender = 'gender'; + $this->field_bday = 'bday'; + $this->field_pass = 'password'; + $this->field_reg_date = 'regdate'; + $this->user_table = 'members'; + + /* 检查数据表是否存在 */ + $sql = "SHOW TABLES LIKE '" . $this->prefix . "%'"; + + $exist_tables = $this->db->getCol($sql); + + if (empty($exist_tables) || (!in_array($this->prefix.$this->user_table, $exist_tables)) || (!in_array($this->prefix.'settings', $exist_tables))) + { + $this->error = 2; + /* 缺少数据表 */ + return false; + } + + $key = $this->db->GetOne('SELECT value FROM ' . $this->table('settings') . " WHERE variable = 'authkey'"); + if (empty($_SERVER['HTTP_USER_AGENT'])) + { + $this->authkey = md5($key); + } + else + { + $this->authkey = md5($key . $_SERVER['HTTP_USER_AGENT']); + } + } + + /** + * 获取论坛有效积分及单位 + * + * @access public + * @param + * + * @return void + */ + function get_points_name () + { + static $ava_credits = NULL; + if ($ava_credits === NULL) + { + $sql = "SELECT value FROM " . $this->table('settings') . " WHERE variable='extcredits'"; + $str = $this->db->getOne($sql); + $extcredits = @unserialize($str); + + $ava_credits = array(); + if ($extcredits) + { + $count = count($extcredits); + for ($i=1; $i <= $count; $i++) + { + if (!empty($extcredits[$i]['available'])) + { + $ava_credits['extcredits' . $i]['title'] = empty($extcredits[$i]['title'])? '' : $extcredits[$i]['title']; + $ava_credits['extcredits' . $i]['unit'] = empty($extcredits[$i]['unit'])? '' : $extcredits[$i]['unit']; + } + } + } + } + + return $ava_credits; + } + + /** + * 获取用户积分 + * + * @access public + * @param + * + * @return array + */ + function get_points($username) + { + $credits = $this->get_points_name(); + $fileds = array_keys($credits); + if ($fileds) + { + if ($this->charset != 'UTF8') + { + $username = ecs_iconv('UTF8', $this->charset, $username); + } + $sql = "SELECT " . $this->field_id . ', ' . implode(', ',$fileds). + " FROM " . $this->table($this->user_table). + " WHERE " . $this->field_name . "='$username'"; + $row = $this->db->getRow($sql); + return $row; + } + else + { + return false; + } + } + + /** + * + * + * @access public + * @param + * + * @return void + */ + function set_points ($username, $credits) + { + $user_set = array_keys($credits); + $points_set = array_keys($this->get_points_name()); + + $set = array_intersect($user_set, $points_set); + + if ($set) + { + if ($this->charset != 'UTF8') + { + $username = ecs_iconv('UTF8', $this->charset, $username); + } + $tmp = array(); + foreach ($set as $credit) + { + $tmp[] = $credit . '=' . $credit . '+' . $credits[$credit]; + } + $sql = "UPDATE " . $this->table($this->user_table). + " SET " . implode(', ', $tmp). + " WHERE " . $this->field_name . " = '$username'"; + $this->db->query($sql); + } + + return true; + } + + /** + * 设置论坛cookie + * + * @access public + * @param + * + * @return void + */ + function set_cookie ($username="") + { + parent::set_cookie($username); + if (empty($username)) + { + $time = time() - 3600; + setcookie($this->cookie_prefix.'sid', '', $time, $this->cookie_path, $this->cookie_domain); + setcookie($this->cookie_prefix.'auth', '', $time, $this->cookie_path, $this->cookie_domain); + } + else + { + if ($this->charset != 'UTF8') + { + $username = ecs_iconv('UTF8', $this->charset, $username); + } + $sql = "SELECT " . $this->field_id . " AS user_id, secques AS salt, " . $this->field_pass . " As password ". + " FROM " . $this->table($this->user_table) . " WHERE " . $this->field_name . "='$username'"; + + $row = $this->db->getRow($sql); + + setcookie($this->cookie_prefix.'sid', $this->random(6), time() + 3600 * 24 * 30, $this->cookie_path, $this->cookie_domain); + setcookie($this->cookie_prefix.'auth', $this->authcode($row['password']."\t".$row['salt']."\t".$row['user_id'], 'ENCODE'), time() + 3600 * 24 * 30, $this->cookie_path, $this->cookie_domain); + } + } + + /** + * 检查cookie + * + * @access public + * @param + * + * @return void + */ + function check_cookie () + { + if (isset($_COOKIE[$this->cookie_prefix . 'auth'])) + { + $arr = addslashes_deep(explode("\t", $this->authcode($_COOKIE[$this->cookie_prefix . 'auth'], 'DECODE'))); + if (count($arr) != 3) + { + return false; + } + else + { + list($discuz_pw, $discuz_secques, $discuz_uid) = $arr; + } + + $sql = "SELECT " . $this->field_name ." AS user_name". + " FROM " . $this->table($this->user_table) . + " WHERE ".$this->field_id." = '$discuz_uid' AND ".$this->field_pass." = '$discuz_pw'"; + $username = $this->db->getOne($sql); + if ($username && ($this->charset != 'UTF8')) + { + $username = ecs_iconv($this->charset, 'UTF8', $username); + } + + return $username; + } + else + { + return ''; + } + } + + /** + * 添加新用户的函数 + * + * @access public + * @param string username 用户名 + * @param string password 登录密码 + * @param string email 邮件地址 + * @param string bday 生日 + * @param string gender 性别 + * @return int 返回最新的ID + */ + function add_user($username, $password, $email, $gender = -1, $bday = 0, $reg_date=0, $md5password='') + { + $result = parent::add_user($username, $password, $email, $gender, $bday, $reg_date, $md5password); + + if (!$result) + { + return false; + } + + /* 获得默认的用户组 */ + $sql = 'SELECT groupid FROM ' .$this->table('usergroups'). ' WHERE creditshigher <= 0 AND creditslower > 0'; + + $grp = $this->db->getOne($sql); + + if ($this->charset != 'UTF8') + { + $username = ecs_iconv('UTF8', $this->charset, $username); + } + + /* 更新组id */ + $sql = "UPDATE " . $this->table($this->user_table) . + " SET groupid= '$grp', ". + " regip = '" . real_ip() . "',". + " regdate = '" . time() . "'". + " WHERE " . $this->field_name . "='$username'"; + $this->db->query($sql); + + /* 更新memberfields表 */ + $sql = 'INSERT INTO '. $this->table('memberfields') .' ('. $this->field_id .") " . + " SELECT " . $this->field_id . + " FROM " . $this->table($this->user_table) . + " WHERE " . $this->field_name . "='$username'"; + $this->db->query($sql); + + return true; + } + + /** + * discuz 5.5 加密函数,从/include/global.func.php获得 + * + * @access public + * @param + * + * @return void + */ + function authcode($string, $operation, $key = '') + { + $key = md5($key ? $key : $this->authkey); + $key_length = strlen($key); + + $string = $operation == 'DECODE' ? base64_decode($string) : substr(md5($string.$key), 0, 8) . $string; + $string_length = strlen($string); + + $rndkey = $box = array(); + $result = ''; + + for ($i = 0; $i <= 255; $i++) + { + $rndkey[$i] = ord($key[$i % $key_length]); + $box[$i] = $i; + } + + for ($j = $i = 0; $i < 256; $i++) + { + $j = ($j + $box[$i] + $rndkey[$i]) % 256; + $tmp = $box[$i]; + $box[$i] = $box[$j]; + $box[$j] = $tmp; + } + + for ($a = $j = $i = 0; $i < $string_length; $i++) + { + $a = ($a + 1) % 256; + $j = ($j + $box[$a]) % 256; + $tmp = $box[$a]; + $box[$a] = $box[$j]; + $box[$j] = $tmp; + $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256])); + } + + if ($operation == 'DECODE') + { + if (substr($result, 0, 8) == substr(md5(substr($result, 8).$key), 0, 8)) + { + return substr($result, 8); + } + else + { + return ''; + } + } + else + { + return str_replace('=', '', base64_encode($result)); + } + } + + /** + * discuz 5.5 随机函数,从/include/global.func.php获得 + * + * @access public + * @param + * + * @return void + */ + + function random($length, $numeric = 0) { + PHP_VERSION < '4.2.0' && mt_srand((double)microtime() * 1000000); + if($numeric) { + $hash = sprintf('%0'.$length.'d', mt_rand(0, pow(10, $length) - 1)); + } else { + $hash = ''; + $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz'; + $max = strlen($chars) - 1; + for($i = 0; $i < $length; $i++) { + $hash .= $chars[mt_rand(0, $max)]; + } + } + return $hash; + } + +} \ No newline at end of file diff --git a/includes/modules/integrates/dvbbs.php b/includes/modules/integrates/dvbbs.php new file mode 100644 index 0000000..1724a8d --- /dev/null +++ b/includes/modules/integrates/dvbbs.php @@ -0,0 +1,288 @@ +dvbbs($cfg); + } + + /** + * + * + * @access public + * @param + * + * @return void + */ + function dvbbs($cfg) + { + parent::integrate($cfg); + if ($this->error) + { + /* 数据库连接出错 */ + return false; + } + $this->cookie_prefix = $cfg['cookie_prefix']; + $this->field_id = 'userid'; + $this->field_name = 'username'; + $this->field_email = 'useremail'; + $this->field_gender = 'usersex'; + $this->field_bday = 'userbirthday'; + $this->field_pass = 'userpassword'; + $this->field_reg_date = 'joindate'; + $this->user_table = 'user'; + + + /* 检查数据表是否存在 */ + $sql = "SHOW TABLES LIKE '" . $this->prefix . "%'"; + + $exist_tables = $this->db->getCol($sql); + + if (empty($exist_tables) || (!in_array($this->prefix.$this->user_table, $exist_tables))) + { + $this->error = 2; + /* 缺少数据表 */ + return false; + } + } + + /** + * 获取论坛有效积分及单位 + * + * @access public + * @param + * + * @return void + */ + function get_points_name () + { + static $ava_credits = NULL; + if ($ava_credits === NULL) + { + $ava_credits = array(); + $ava_credits['usermoney'] = array('title'=>'金钱', 'unit'=>''); + $ava_credits['userep'] = array('title'=>'经验', 'unit'=>''); + $ava_credits['usercp'] = array('title'=>'魅力', 'unit'=>''); + } + + return $ava_credits; + } + + /** + * 获取用户积分 + * + * @access public + * @param + * + * @return array + */ + function get_points($username) + { + $credits = $this->get_points_name(); + $fileds = array_keys($credits); + if ($fileds) + { + if ($this->charset != 'UTF8') + { + $username = ecs_iconv('UTF8', $this->charset, $username); + } + $sql = "SELECT " . $this->field_id . ', ' . implode(', ',$fileds). + " FROM " . $this->table($this->user_table). + " WHERE " . $this->field_name . "='$username'"; + $row = $this->db->getRow($sql); + return $row; + } + else + { + return false; + } + } + + /** + * + * + * @access public + * @param + * + * @return void + */ + function set_points ($username, $credits) + { + $user_set = array_keys($credits); + $points_set = array_keys($this->get_points_name()); + + $set = array_intersect($user_set, $points_set); + + if ($set) + { + if ($this->charset != 'UTF8') + { + $username = ecs_iconv('UTF8', $this->charset, $username); + } + $tmp = array(); + foreach ($set as $credit) + { + $tmp[] = $credit . '=' . $credit . '+' . $credits[$credit]; + } + $sql = "UPDATE " . $this->table($this->user_table). + " SET " . implode(', ', $tmp). + " WHERE " . $this->field_name . " = '$username'"; + $this->db->query($sql); + } + + return true; + } + + /** + * 设置论坛cookie + * + * @access public + * @param + * + * @return void + */ + function set_cookie ($username="") + { + parent::set_cookie($username); + if (empty($username)) + { + $time = time() - 3600; + setcookie($this->cookie_prefix . 'userid', '', $time, $this->cookie_path, $this->cookie_domain); + setcookie($this->cookie_prefix . 'username', '', $time, $this->cookie_path, $this->cookie_domain); + setcookie($this->cookie_prefix . 'password', '', $time, $this->cookie_path, $this->cookie_domain); + setcookie($this->cookie_prefix . 'userhidden', '', $time, $this->cookie_path, $this->cookie_domain); + setcookie($this->cookie_prefix . 'onlinecachetime', '', $time, $this->cookie_path, $this->cookie_domain); + } + else + { + if ($this->charset != 'UTF8') + { + $username = ecs_iconv('UTF8', $this->charset, $username); + } + $sql = "SELECT " . $this->field_id . " AS user_id, truepassword, userhidden ". + " FROM " . $this->table($this->user_table) . " WHERE " . $this->field_name . "='$username'"; + + $row = $this->db->getRow($sql); + + setcookie($this->cookie_prefix . 'userid', $row['user_id'], time() + 3600 * 24 * 30, $this->cookie_path, $this->cookie_domain); + setcookie($this->cookie_prefix . 'username', $username, time() + 3600 * 24 * 30, $this->cookie_path, $this->cookie_domain); + setcookie($this->cookie_prefix . 'password', $row['truepassword'], time() + 3600 * 24 * 30, $this->cookie_path, $this->cookie_domain); + setcookie($this->cookie_prefix . 'userhidden', $row['userhidden'], time() + 3600 * 24 * 30, $this->cookie_path, $this->cookie_domain); + } + } + + /** + * 检查cookie + * + * @access public + * @param + * + * @return void + */ + function check_cookie () + { + if (empty($_COOKIE[$this->cookie_prefix . 'userid']) || empty($_COOKIE[$this->cookie_prefix . 'password'])) + { + return ''; + } + + $user_id = intval($_COOKIE[$this->cookie_prefix . 'userid']); + $true_password = addslashes_deep($_COOKIE[$this->cookie_prefix . 'password']); + + $sql = "SELECT ". $this->field_name . " AS user_name ". + " FROM " . $this->table($this->user_table) . + " WHERE " . $this->field_id . "='$user_id' AND truepassword='$true_password'"; + + $username = $this->db->getOne($sql); + + if (empty($username)) + { + return ''; + } + + if ($this->charset != 'UTF8') + { + $username = ecs_iconv($this->charset, 'UTF8', $username); + } + + return $username; + } + +/** + * 编译密码函数 + * + * @access public + * @param array $cfg 包含参数为 $password, $md5password, $salt, $type + * + * @return void + */ + function compile_password ($cfg) + { + if ((!empty($cfg['password'])) && empty($cfg['md5password'])) + { + $cfg['md5password'] = md5($cfg['password']); + } + + if (empty($cfg['md5password'])) + { + return ''; + } + + return substr($cfg['md5password'], 8, 16); + + } + + +} \ No newline at end of file diff --git a/includes/modules/integrates/ecshop.php b/includes/modules/integrates/ecshop.php new file mode 100644 index 0000000..64edb0a --- /dev/null +++ b/includes/modules/integrates/ecshop.php @@ -0,0 +1,182 @@ +ecshop($cfg); + } + + /** + * + * + * @access public + * @param + * + * @return void + */ + function ecshop($cfg) + { + parent::integrate(array()); + $this->user_table = 'users'; + $this->field_id = 'user_id'; + $this->ec_salt = 'ec_salt'; + $this->field_name = 'user_name'; + $this->field_pass = 'password'; + $this->field_email = 'email'; + $this->field_gender = 'sex'; + $this->field_bday = 'birthday'; + $this->field_reg_date = 'reg_time'; + $this->need_sync = false; + $this->is_ecshop = 1; + } + + + /** + * 检查指定用户是否存在及密码是否正确(重载基类check_user函数,支持zc加密方法) + * + * @access public + * @param string $username 用户名 + * + * @return int + */ + function check_user($username, $password = null) + { + if ($this->charset != 'UTF8') + { + $post_username = ecs_iconv('UTF8', $this->charset, $username); + } + else + { + $post_username = $username; + } + + if ($password === null) + { + $sql = "SELECT " . $this->field_id . + " FROM " . $this->table($this->user_table). + " WHERE " . $this->field_name . "='" . $post_username . "'"; + + return $this->db->getOne($sql); + } + else + { + $sql = "SELECT user_id, password, salt,ec_salt " . + " FROM " . $this->table($this->user_table). + " WHERE user_name='$post_username'"; + $row = $this->db->getRow($sql); + $ec_salt=$row['ec_salt']; + if (empty($row)) + { + return 0; + } + + if (empty($row['salt'])) + { + if ($row['password'] != $this->compile_password(array('password'=>$password,'ec_salt'=>$ec_salt))) + { + return 0; + } + else + { + if(empty($ec_salt)) + { + $ec_salt=rand(1,9999); + $new_password=md5(md5($password).$ec_salt); + $sql = "UPDATE ".$this->table($this->user_table)."SET password= '" .$new_password."',ec_salt='".$ec_salt."'". + " WHERE user_name='$post_username'"; + $this->db->query($sql); + + } + return $row['user_id']; + } + } + else + { + /* 如果salt存在,使用salt方式加密验证,验证通过洗白用户密码 */ + $encrypt_type = substr($row['salt'], 0, 1); + $encrypt_salt = substr($row['salt'], 1); + + /* 计算加密后密码 */ + $encrypt_password = ''; + switch ($encrypt_type) + { + case ENCRYPT_ZC : + $encrypt_password = md5($encrypt_salt.$password); + break; + /* 如果还有其他加密方式添加到这里 */ + //case other : + // ---------------------------------- + // break; + case ENCRYPT_UC : + $encrypt_password = md5(md5($password).$encrypt_salt); + break; + + default: + $encrypt_password = ''; + + } + + if ($row['password'] != $encrypt_password) + { + return 0; + } + + $sql = "UPDATE " . $this->table($this->user_table) . + " SET password = '". $this->compile_password(array('password'=>$password)) . "', salt=''". + " WHERE user_id = '$row[user_id]'"; + $this->db->query($sql); + + return $row['user_id']; + } + } + } + + +} + +?> \ No newline at end of file diff --git a/includes/modules/integrates/integrate.php b/includes/modules/integrates/integrate.php new file mode 100644 index 0000000..72a6c3b --- /dev/null +++ b/includes/modules/integrates/integrate.php @@ -0,0 +1,870 @@ +charset = isset($cfg['db_charset']) ? $cfg['db_charset'] : 'UTF8'; + $this->prefix = isset($cfg['prefix']) ? $cfg['prefix'] : ''; + $this->db_name = isset($cfg['db_name']) ? $cfg['db_name'] : ''; + $this->cookie_domain = isset($cfg['cookie_domain']) ? $cfg['cookie_domain'] : ''; + $this->cookie_path = isset($cfg['cookie_path']) ? $cfg['cookie_path'] : '/'; + $this->need_sync = true; + + $quiet = empty($cfg['quiet']) ? 0 : 1; + + /* 初始化数据库 */ + if (empty($cfg['db_host'])) + { + $this->db_name = $GLOBALS['ecs']->db_name; + $this->prefix = $GLOBALS['ecs']->prefix; + $this->db = &$GLOBALS['db']; + } + else + { + if (empty($cfg['is_latin1'])) + { + $this->db = new cls_mysql($cfg['db_host'], $cfg['db_user'], $cfg['db_pass'], $cfg['db_name'], $this->charset, NULL, $quiet); + } + else + { + $this->db = new cls_mysql($cfg['db_host'], $cfg['db_user'], $cfg['db_pass'], $cfg['db_name'], 'latin1', NULL, $quiet) ; + } + } + + if (!is_resource($this->db->link_id)) + { + $this->error = 1; //数据库地址帐号 + } + else + { + $this->error = $this->db->errno(); + } + } + + /** + * 用户登录函数 + * + * @access public + * @param string $username + * @param string $password + * + * @return void + */ + function login($username, $password, $remember = null) + { + if ($this->check_user($username, $password) > 0) + { + if ($this->need_sync) + { + $this->sync($username,$password); + } + $this->set_session($username); + $this->set_cookie($username, $remember); + + return true; + } + else + { + return false; + } + } + + /** + * + * + * @access public + * @param + * + * @return void + */ + function logout () + { + $this->set_cookie(); //清除cookie + $this->set_session(); //清除session + } + + /** + * 添加一个新用户 + * + * @access public + * @param + * + * @return int + */ + function add_user($username, $password, $email, $gender = -1, $bday = 0, $reg_date=0, $md5password='') + { + /* 将用户添加到整合方 */ + if ($this->check_user($username) > 0) + { + $this->error = ERR_USERNAME_EXISTS; + + return false; + } + /* 检查email是否重复 */ + $sql = "SELECT " . $this->field_id . + " FROM " . $this->table($this->user_table). + " WHERE " . $this->field_email . " = '$email'"; + if ($this->db->getOne($sql, true) > 0) + { + $this->error = ERR_EMAIL_EXISTS; + + return false; + } + + $post_username = $username; + + if ($md5password) + { + $post_password = $this->compile_password(array('md5password'=>$md5password)); + } + else + { + $post_password = $this->compile_password(array('password'=>$password)); + } + + $fields = array($this->field_name, $this->field_email, $this->field_pass); + $values = array($post_username, $email, $post_password); + + if ($gender > -1) + { + $fields[] = $this->field_gender; + $values[] = $gender; + } + if ($bday) + { + $fields[] = $this->field_bday; + $values[] = $bday; + } + if ($reg_date) + { + $fields[] = $this->field_reg_date; + $values[] = $reg_date; + } + + $sql = "INSERT INTO " . $this->table($this->user_table). + " (" . implode(',', $fields) . ")". + " VALUES ('" . implode("', '", $values) . "')"; + + $this->db->query($sql); + + if ($this->need_sync) + { + $this->sync($username, $password); + } + + return true; + } + + /** + * 编辑用户信息($password, $email, $gender, $bday) + * + * @access public + * @param + * + * @return void + */ + function edit_user($cfg) + { + if (empty($cfg['username'])) + { + return false; + } + else + { + $cfg['post_username'] = $cfg['username']; + + } + + $values = array(); + if (!empty($cfg['password']) && empty($cfg['md5password'])) + { + $cfg['md5password'] = md5($cfg['password']); + } + if ((!empty($cfg['md5password'])) && $this->field_pass != 'NULL') + { + $values[] = $this->field_pass . "='" . $this->compile_password(array('md5password'=>$cfg['md5password'])) . "'"; + } + + if ((!empty($cfg['email'])) && $this->field_email != 'NULL') + { + /* 检查email是否重复 */ + $sql = "SELECT " . $this->field_id . + " FROM " . $this->table($this->user_table). + " WHERE " . $this->field_email . " = '$cfg[email]' ". + " AND " . $this->field_name . " != '$cfg[post_username]'"; + if ($this->db->getOne($sql, true) > 0) + { + $this->error = ERR_EMAIL_EXISTS; + + return false; + } + // 检查是否为新E-mail + $sql = "SELECT count(*)" . + " FROM " . $this->table($this->user_table). + " WHERE " . $this->field_email . " = '$cfg[email]' "; + if($this->db->getOne($sql, true) == 0) + { + // 新的E-mail + $sql = "UPDATE " . $GLOBALS['ecs']->table('users') . " SET is_validated = 0 WHERE user_name = '$cfg[post_username]'"; + $this->db->query($sql); + } + $values[] = $this->field_email . "='". $cfg['email'] . "'"; + } + + if (isset($cfg['gender']) && $this->field_gender != 'NULL') + { + $values[] = $this->field_gender . "='" . $cfg['gender'] . "'"; + } + + if ((!empty($cfg['bday'])) && $this->field_bday != 'NULL') + { + $values[] = $this->field_bday . "='" . $cfg['bday'] . "'"; + } + + if ($values) + { + $sql = "UPDATE " . $this->table($this->user_table). + " SET " . implode(', ', $values). + " WHERE " . $this->field_name . "='" . $cfg['post_username'] . "' LIMIT 1"; + + $this->db->query($sql); + + if ($this->need_sync) + { + if (empty($cfg['md5password'])) + { + $this->sync($cfg['username']); + } + else + { + $this->sync($cfg['username'], '', $cfg['md5password']); + } + } + } + + return true; + } + + /** + * 删除用户 + * + * @access public + * @param + * + * @return void + */ + function remove_user($id) + { + $post_id = $id; + + if ($this->need_sync || (isset($this->is_ecshop) && $this->is_ecshop)) + { + /* 如果需要同步或是ecshop插件执行这部分代码 */ + $sql = "SELECT user_id FROM " . $GLOBALS['ecs']->table('users') . " WHERE "; + $sql .= (is_array($post_id)) ? db_create_in($post_id, 'user_name') : "user_name='". $post_id . "' LIMIT 1"; + $col = $GLOBALS['db']->getCol($sql); + + if ($col) + { + $sql = "UPDATE " . $GLOBALS['ecs']->table('users') . " SET parent_id = 0 WHERE " . db_create_in($col, 'parent_id'); //将删除用户的下级的parent_id 改为0 + $GLOBALS['db']->query($sql); + $sql = "DELETE FROM " . $GLOBALS['ecs']->table('users') . " WHERE " . db_create_in($col, 'user_id'); //删除用户 + $GLOBALS['db']->query($sql); + /* 删除用户订单 */ + $sql = "SELECT order_id FROM " . $GLOBALS['ecs']->table('order_info') . " WHERE " . db_create_in($col, 'user_id'); + $GLOBALS['db']->query($sql); + $col_order_id = $GLOBALS['db']->getCol($sql); + if ($col_order_id) + { + $sql = "DELETE FROM " . $GLOBALS['ecs']->table('order_info') . " WHERE " . db_create_in($col_order_id, 'order_id'); + $GLOBALS['db']->query($sql); + $sql = "DELETE FROM " . $GLOBALS['ecs']->table('order_goods') . " WHERE " . db_create_in($col_order_id, 'order_id'); + $GLOBALS['db']->query($sql); + } + + $sql = "DELETE FROM " . $GLOBALS['ecs']->table('booking_goods') . " WHERE " . db_create_in($col, 'user_id'); //删除用户 + $GLOBALS['db']->query($sql); + $sql = "DELETE FROM " . $GLOBALS['ecs']->table('collect_goods') . " WHERE " . db_create_in($col, 'user_id'); //删除会员收藏商品 + $GLOBALS['db']->query($sql); + $sql = "DELETE FROM " . $GLOBALS['ecs']->table('feedback') . " WHERE " . db_create_in($col, 'user_id'); //删除用户留言 + $GLOBALS['db']->query($sql); + $sql = "DELETE FROM " . $GLOBALS['ecs']->table('user_address') . " WHERE " . db_create_in($col, 'user_id'); //删除用户地址 + $GLOBALS['db']->query($sql); + $sql = "DELETE FROM " . $GLOBALS['ecs']->table('user_bonus') . " WHERE " . db_create_in($col, 'user_id'); //删除用户红包 + $GLOBALS['db']->query($sql); + $sql = "DELETE FROM " . $GLOBALS['ecs']->table('user_account') . " WHERE " . db_create_in($col, 'user_id'); //删除用户帐号金额 + $GLOBALS['db']->query($sql); + $sql = "DELETE FROM " . $GLOBALS['ecs']->table('tag') . " WHERE " . db_create_in($col, 'user_id'); //删除用户标记 + $GLOBALS['db']->query($sql); + $sql = "DELETE FROM " . $GLOBALS['ecs']->table('account_log') . " WHERE " . db_create_in($col, 'user_id'); //删除用户日志 + $GLOBALS['db']->query($sql); + } + } + + if (isset($this->ecshop) && $this->ecshop) + { + /* 如果是ecshop插件直接退出 */ + return; + } + + $sql = "DELETE FROM " . $this->table($this->user_table) . " WHERE "; + if (is_array($post_id)) + { + $sql .= db_create_in($post_id, $this->field_name); + } + else + { + $sql .= $this->field_name . "='" . $post_id . "' LIMIT 1"; + } + + $this->db->query($sql); + } + + /** + * 获取指定用户的信息 + * + * @access public + * @param + * + * @return void + */ + function get_profile_by_name($username) + { + $post_username = $username; + + $sql = "SELECT " . $this->field_id . " AS user_id," . $this->field_name . " AS user_name," . + $this->field_email . " AS email," . $this->field_gender ." AS sex,". + $this->field_bday . " AS birthday," . $this->field_reg_date . " AS reg_time, ". + $this->field_pass . " AS password ". + " FROM " . $this->table($this->user_table) . + " WHERE " .$this->field_name . "='$post_username'"; + $row = $this->db->getRow($sql); + + return $row; + } + + /** + * 获取指定用户的信息 + * + * @access public + * @param + * + * @return void + */ + function get_profile_by_id($id) + { + $sql = "SELECT " . $this->field_id . " AS user_id," . $this->field_name . " AS user_name," . + $this->field_email . " AS email," . $this->field_gender ." AS sex,". + $this->field_bday . " AS birthday," . $this->field_reg_date . " AS reg_time, ". + $this->field_pass . " AS password ". + " FROM " . $this->table($this->user_table) . + " WHERE " .$this->field_id . "='$id'"; + $row = $this->db->getRow($sql); + + return $row; + } + + /** + * 根据登录状态设置cookie + * + * @access public + * @param + * + * @return void + */ + function get_cookie() + { + $id = $this->check_cookie(); + if ($id) + { + if ($this->need_sync) + { + $this->sync($id); + } + $this->set_session($id); + + return true; + } + else + { + return false; + } + } + + /** + * 检查指定用户是否存在及密码是否正确 + * + * @access public + * @param string $username 用户名 + * + * @return int + */ + function check_user($username, $password = null) + { + + $post_username = $username; + + /* 如果没有定义密码则只检查用户名 */ + if ($password === null) + { + $sql = "SELECT " . $this->field_id . + " FROM " . $this->table($this->user_table). + " WHERE " . $this->field_name . "='" . $post_username . "'"; + + return $this->db->getOne($sql); + } + else + { + $sql = "SELECT " . $this->field_id . + " FROM " . $this->table($this->user_table). + " WHERE " . $this->field_name . "='" . $post_username . "' AND " . $this->field_pass . " ='" . $this->compile_password(array('password'=>$password)) . "'"; + + return $this->db->getOne($sql); + } + } + + /** + * 检查指定邮箱是否存在 + * + * @access public + * @param string $email 用户邮箱 + * + * @return boolean + */ + function check_email($email) + { + if (!empty($email)) + { + /* 检查email是否重复 */ + $sql = "SELECT " . $this->field_id . + " FROM " . $this->table($this->user_table). + " WHERE " . $this->field_email . " = '$email' "; + if ($this->db->getOne($sql, true) > 0) + { + $this->error = ERR_EMAIL_EXISTS; + return true; + } + return false; + } + } + + + /** + * 检查cookie是正确,返回用户名 + * + * @access public + * @param + * + * @return void + */ + function check_cookie() + { + return ''; + } + + /** + * 设置cookie + * + * @access public + * @param + * + * @return void + */ + function set_cookie($username='', $remember= null ) + { + if (empty($username)) + { + /* 摧毁cookie */ + $time = time() - 3600; + setcookie("ECS[user_id]", '', $time, $this->cookie_path); + setcookie("ECS[password]", '', $time, $this->cookie_path); + + } + elseif ($remember) + { + /* 设置cookie */ + $time = time() + 3600 * 24 * 15; + + setcookie("ECS[username]", $username, $time, $this->cookie_path, $this->cookie_domain); + $sql = "SELECT user_id, password FROM " . $GLOBALS['ecs']->table('users') . " WHERE user_name='$username' LIMIT 1"; + $row = $GLOBALS['db']->getRow($sql); + if ($row) + { + setcookie("ECS[user_id]", $row['user_id'], $time, $this->cookie_path, $this->cookie_domain); + setcookie("ECS[password]", $row['password'], $time, $this->cookie_path, $this->cookie_domain); + } + } + } + + /** + * 设置指定用户SESSION + * + * @access public + * @param + * + * @return void + */ + function set_session ($username='') + { + if (empty($username)) + { + $GLOBALS['sess']->destroy_session(); + } + else + { + $sql = "SELECT user_id, password, email FROM " . $GLOBALS['ecs']->table('users') . " WHERE user_name='$username' LIMIT 1"; + $row = $GLOBALS['db']->getRow($sql); + + if ($row) + { + $_SESSION['user_id'] = $row['user_id']; + $_SESSION['user_name'] = $username; + $_SESSION['email'] = $row['email']; + } + } + } + + + /** + * 在给定的表名前加上数据库名以及前缀 + * + * @access private + * @param string $str 表名 + * + * @return void + */ + function table($str) + { + return '`' .$this->db_name. '`.`'.$this->prefix.$str.'`'; + } + + /** + * 编译密码函数 + * + * @access public + * @param array $cfg 包含参数为 $password, $md5password, $salt, $type + * + * @return void + */ + function compile_password ($cfg) + { + if (isset($cfg['password'])) + { + $cfg['md5password'] = md5($cfg['password']); + } + if (empty($cfg['type'])) + { + $cfg['type'] = PWD_MD5; + } + + switch ($cfg['type']) + { + case PWD_MD5 : + if(!empty($cfg['ec_salt'])) + { + return md5($cfg['md5password'].$cfg['ec_salt']); + } + else + { + return $cfg['md5password']; + } + + case PWD_PRE_SALT : + if (empty($cfg['salt'])) + { + $cfg['salt'] = ''; + } + + return md5($cfg['salt'] . $cfg['md5password']); + + case PWD_SUF_SALT : + if (empty($cfg['salt'])) + { + $cfg['salt'] = ''; + } + + return md5($cfg['md5password'] . $cfg['salt']); + + default: + return ''; + } + } + + /** + * 会员同步 + * + * @access public + * @param + * + * @return void + */ + function sync ($username, $password='', $md5password='') + { + if ((!empty($password)) && empty($md5password)) + { + $md5password = md5($password); + } + + $main_profile = $this->get_profile_by_name($username); + + if (empty($main_profile)) + { + return false; + } + + $sql = "SELECT user_name, email, password, sex, birthday". + " FROM " . $GLOBALS['ecs']->table('users'). + " WHERE user_name = '$username'"; + + $profile = $GLOBALS['db']->getRow($sql); + if (empty($profile)) + { + /* 向商城表插入一条新记录 */ + if (empty($md5password)) + { + $sql = "INSERT INTO " . $GLOBALS['ecs']->table('users'). + "(user_name, email, sex, birthday, reg_time)". + " VALUES('$username', '" .$main_profile['email']."','". + $main_profile['sex'] . "','" . $main_profile['birthday'] . "','" . $main_profile['reg_time'] . "')"; + } + else + { + $sql = "INSERT INTO " . $GLOBALS['ecs']->table('users'). + "(user_name, email, sex, birthday, reg_time, password)". + " VALUES('$username', '" .$main_profile['email']."','". + $main_profile['sex'] . "','" . $main_profile['birthday'] . "','" . + $main_profile['reg_time'] . "', '$md5password')"; + + } + + $GLOBALS['db']->query($sql); + + return true; + } + else + { + $values = array(); + if ($main_profile['email'] != $profile['email']) + { + $values[] = "email='" . $main_profile['email'] . "'"; + } + if ($main_profile['sex'] != $profile['sex']) + { + $values[] = "sex='" . $main_profile['sex'] . "'"; + } + if ($main_profile['birthday'] != $profile['birthday']) + { + $values[] = "birthday='" . $main_profile['birthday'] . "'"; + } + if ((!empty($md5password)) && ($md5password != $profile['password'])) + { + $values[] = "password='" . $md5password . "'"; + } + + if (empty($values)) + { + return true; + } + else + { + $sql = "UPDATE " . $GLOBALS['ecs']->table('users'). + " SET " . implode(", ", $values). + " WHERE user_name='$username'"; + + $GLOBALS['db']->query($sql); + + return true; + } + } + } + + /** + * 获取论坛有效积分及单位 + * + * @access public + * @param + * + * @return void + */ + function get_points_name () + { + return array(); + } + + /** + * 获取用户积分 + * + * @access public + * @param + * + * @return void + */ + function get_points($username) + { + $credits = $this->get_points_name(); + $fileds = array_keys($credits); + if ($fileds) + { + $sql = "SELECT " . $this->field_id . ', ' . implode(', ',$fileds). + " FROM " . $this->table($this->user_table). + " WHERE " . $this->field_name . "='$username'"; + $row = $this->db->getRow($sql); + return $row; + } + else + { + return false; + } + } + + /** + *设置用户积分 + * + * @access public + * @param + * + * @return void + */ + function set_points ($username, $credits) + { + $user_set = array_keys($credits); + $points_set = array_keys($this->get_points_name()); + + $set = array_intersect($user_set, $points_set); + + if ($set) + { + $tmp = array(); + foreach ($set as $credit) + { + $tmp[] = $credit . '=' . $credit . '+' . $credits[$credit]; + } + $sql = "UPDATE " . $this->table($this->user_table). + " SET " . implode(', ', $tmp). + " WHERE " . $this->field_name . " = '$username'"; + $this->db->query($sql); + } + + return true; + } + + function get_user_info($username) + { + return $this->get_profile_by_name($username); + } + + + /** + * 检查有无重名用户,有则返回重名用户 + * + * @access public + * @param + * + * @return void + */ + function test_conflict ($user_list) + { + if (empty($user_list)) + { + return array(); + } + + + $sql = "SELECT " . $this->field_name . " FROM " . $this->table($this->user_table) . " WHERE " . db_create_in($user_list, $this->field_name); + $user_list = $this->db->getCol($sql); + + return $user_list; + } +} diff --git a/includes/modules/integrates/ipb.php b/includes/modules/integrates/ipb.php new file mode 100644 index 0000000..2767e72 --- /dev/null +++ b/includes/modules/integrates/ipb.php @@ -0,0 +1,358 @@ +ipb($cfg); + } + + /** + * + * + * @access public + * @param + * + * @return void + */ + function ipb($cfg) + { + parent::integrate($cfg); + if ($this->error) + { + /* 数据库连接出错 */ + return false; + } + //$this->cookie_prefix = $cfg['cookie_prefix']; + $this->field_id = 'id'; + $this->field_name = 'name'; + $this->field_email = 'email'; + $this->field_gender = 'NULL'; + $this->field_bday = 'NULL'; + $this->field_pass = 'NULL'; + $this->field_reg_date = 'joined'; + $this->user_table = 'members'; + + + /* 检查数据表是否存在 */ + $sql = "SHOW TABLES LIKE '" . $this->prefix . "%'"; + + $exist_tables = $this->db->getCol($sql); + + if (empty($exist_tables) || (!in_array($this->prefix.$this->user_table, $exist_tables))) + { + $this->error = 2; + /* 缺少数据表 */ + return false; + } + } + + /** + * 检查指定用户是否存在及密码是否正确 + * + * @access public + * @param string $username 用户名 + * + * @return int + */ + function check_user($username, $password = null) + { + if ($this->charset != 'UTF8') + { + $post_username = ecs_iconv('UTF8', $this->charset, $username); + } + else + { + $post_username = $username; + } + + if ($password === null) + { + $sql = "SELECT " . $this->field_id . + " FROM " . $this->table($this->user_table). + " WHERE " . $this->field_name . "='" . $post_username . "'"; + + return $this->db->getOne($sql); + } + else + { + /*$sql = "SELECT " . $this->field_id . + " FROM " . $this->table($this->user_table). + " WHERE " . $this->field_name . "='" . $post_username . "' AND " . $this->field_pass . " ='" . $this->compile_password(array('password'=>$password)) . "'";*/ + + $sql = "SELECT m.id, m.name, m.email, m.member_login_key, mc.converge_pass_hash, mc.converge_pass_salt". + " FROM ".$this->table('members')." AS m, ".$this->table('members_converge')." AS mc". + " WHERE m.name = '$post_username' AND m.email = mc.converge_email"; + + $row = $this->db->getRow($sql); + + if ($row['converge_pass_hash'] != $this->compile_password(array('password'=>$password, 'salt'=>$row['converge_pass_salt']))) + { + return 0; + } + else + { + return $row['id']; + } + } + } + + /** + * 添加一个新用户 + * + * @access public + * @param + * + * @return int + */ + function add_user($username, $password, $email, $gender = -1, $bday = 0, $reg_date=0, $md5password='') + { + /* 将用户添加到整合方 */ + if ($this->check_user($username) > 0) + { + $this->error = ERR_USERNAME_EXISTS; + + return false; + } + /* 检查email是否重复 */ + $sql = "SELECT " . $this->field_id . + " FROM " . $this->table($this->user_table). + " WHERE " . $this->field_email . " = '$email'"; + if ($this->db->getOne($sql, true) > 0) + { + $this->error = ERR_EMAIL_EXISTS; + + return false; + } + + if ($this->charset != 'UTF8') + { + $post_username = ecs_iconv('UTF8', $this->charset, $username); + } + else + { + $post_username = $username; + } + + /* 生成随机串 */ + $salt = $this->generate_password_salt(5); + + /* 生成加密密码 */ + $converge_pass_hash = $this->compile_password(array('password'=>$password, 'salt'=>$salt)); + + /* 规格化随机串 */ + $converge_pass_salt = str_replace( '\\', "\\\\", $salt); + + /* 插入数据到members_converge表 */ + $sql = "INSERT INTO ".$this->table('members_converge')." (`converge_id`, `converge_email`,`converge_joined`, `converge_pass_hash`, `converge_pass_salt`) VALUES (null, '$email', " . time() . ", '$converge_pass_hash', '$converge_pass_salt')"; + $this->db->query($sql); + + /* 得到新加用户的UID */ + $uid = $this->db->Insert_ID(); + + /* 获得默认的用户组 */ + $grp = 3; + + /* 生成自动登录密钥,存于COOKIE中 */ + $auto_login_key = $this->generate_auto_log_in_key(); + + /* 插入数据到members表 */ + $sql = "INSERT INTO ".$this->table('members')." (`id`, `name`, `mgroup`, `email`, `joined`, `ip_address`, `member_login_key`, `members_display_name`, `members_l_username`) + VALUES ($uid, '$post_username', $grp, '$email', " . time() . ", '" . real_ip() . "', '$auto_login_key', '$post_username', '$post_username')"; + $result = $this->db->query($sql); + + if ($this->need_sync) + { + $this->sync($username); + } + + return true; + } + + /** + * 设置论坛cookie + * + * @access public + * @param + * + * @return void + */ + function set_cookie ($username="") + { + parent::set_cookie($username); + if (empty($username)) + { + $time = time() - 3600; + setcookie('session_id', '', $time, $this->cookie_path, $this->cookie_domain); + setcookie('member_id', '', $time, $this->cookie_path, $this->cookie_domain); + setcookie('pass_hash', '', $time, $this->cookie_path, $this->cookie_domain); + } + else + { + $time = time() + 3600 * 24 * 30; + if ($this->charset != 'UTF8') + { + $username = ecs_iconv('UTF8', $this->charset, $username); + } + $sql = "SELECT " . $this->field_id . " AS user_id, member_login_key ". + " FROM " . $this->table($this->user_table) . " WHERE " . $this->field_name . "='$username'"; + + $row = $this->db->getRow($sql); + + if ($row) + { + setcookie('member_id', $row['user_id'], $time, $this->cookie_path, $this->cookie_domain); + setcookie('pass_hash', $row['member_login_key'], $time, $this->cookie_path, $this->cookie_domain); + } + } + } + + /** + * 检查cookie + * + * @access public + * @param + * + * @return void + */ + function check_cookie () + { + if (empty($_COOKIE['member_id']) || empty($_COOKIE['pass_hash'])) + { + return ''; + } + + $user_id = intval($_COOKIE['member_id']); + $auto_login_key = addslashes_deep($_COOKIE['pass_hash']); + + $sql = "SELECT " . $this->field_name ." AS user_name". + " FROM " . $this->table($this->user_table) . + " WHERE `id` = '$user_id' AND `member_login_key` = '$auto_login_key'"; + + $username = $this->db->getOne($sql); + if ($username && ($this->charset != 'UTF8')) + { + $username = ecs_iconv($this->charset, 'UTF8', $username); + } + + return $username; + } + + /** + * 编译密码函数 + * + * @access public + * @param array $cfg 包含参数为 $password, $md5password, $salt, $type + * + * @return void + */ + function compile_password ($cfg) + { + if ((!empty($cfg['password'])) && empty($cfg['md5password'])) + { + $cfg['md5password'] = md5($cfg['password']); + } + + if (!isset($cfg['salt'])) + { + $cfg['salt'] = ''; + } + + return md5(md5($cfg['salt']).$cfg['md5password']); + } + + /** + * Generates a password salt + * + * Returns n length string of any char except backslash + * + * @access private + * @param integer Length of desired salt, 5 by default + * @return string n character random string + */ + function generate_password_salt($len = 5) + { + $salt = ''; + + //srand( (double)microtime() * 1000000 ); + // PHP 4.3 is now required ^ not needed + + for ($i = 0; $i < $len; $i++) + { + $num = mt_rand(33, 126); + + if ($num == '92') + { + $num = 93; + } + + $salt .= chr($num); + } + + return $salt; + } + + /** + * Generates a log in key + * + * @access private + * @param integer Length of desired random chars to MD5 + * @return string MD5 hash of random characters + */ + function generate_auto_log_in_key($len = 60) + { + $pass = $this->generate_password_salt(60); + + return md5($pass); + } +} \ No newline at end of file diff --git a/includes/modules/integrates/molyx.php b/includes/modules/integrates/molyx.php new file mode 100644 index 0000000..f184173 --- /dev/null +++ b/includes/modules/integrates/molyx.php @@ -0,0 +1,235 @@ +molyx($cfg); + } + + /** + * 初始化函数 + * + * @access public + * @param + * + * @return void + */ + function molyx($cfg) + { + parent::integrate($cfg); + if ($this->error) + { + /* 数据库连接出错 */ + return false; + } + $this->field_id = 'id'; + $this->field_name = 'name'; + $this->field_email = 'email'; + $this->field_gender = 'gender'; + $this->field_bday = 'birthday'; + $this->field_pass = 'password'; + $this->field_reg_date = 'joindate'; + $this->user_table = 'user'; + + /* 检查数据表是否存在 */ + $sql = "SHOW TABLES LIKE '" . $this->prefix . "%'"; + + $exist_tables = $this->db->getCol($sql); + + if (empty($exist_tables) || (!in_array($this->prefix.$this->user_table, $exist_tables)) || (!in_array($this->prefix.'setting', $exist_tables))) + { + $this->error = 2; + /* 缺少数据表 */ + return false; + } + + $cookie_prefix = $this->db->getOne("SELECT value FROM " .$this->table('setting'). " WHERE varname='cookieprefix'"); + } + + /** + * 检查指定用户是否存在及密码是否正确 + * + * @access public + * @param string $username 用户名 + * + * @return int + */ + function check_user($username, $password = null) + { + if ($this->charset != 'UTF8') + { + $post_username = strtolower(ecs_iconv('UTF8', $this->charset, $username)); + } + else + { + $post_username = strtolower($username); + } + + $sql = "SELECT " . $this->field_id . " AS user_id, ". $this->field_pass . " AS password, salt". + " FROM " . $this->table($this->user_table). + " WHERE " . $this->field_name . "='" . $post_username . "'"; + + $row = $this->db->getRow($sql); + + if (empty($row)) + { + return 0; + } + + if ($password === null) + { + return $row['user_id']; + } + + if ($row['password'] == $this->compile_password(array('type'=>PWD_SUF_SALT, 'salt'=>$row['salt'], 'md5password'=>md5($password)))) + { + return $row['user_id']; + } + else + { + return 0; + } + } + + /** + * 设置论坛cookie + * + * @access public + * @param + * + * @return void + */ + function set_cookie ($username="") + { + parent::set_cookie($username); + if (empty($username)) + { + $time = time() - 3600 * 24; + setcookie($this->cookie_prefix.'sessionid', '', $time, $this->cookie_path, $this->cookie_domain); + setcookie($this->cookie_prefix.'userid', '', $time, $this->cookie_path, $this->cookie_domain); + setcookie($this->cookie_prefix.'password', '', $time, $this->cookie_path, $this->cookie_domain); + } + else + { + if ($this->charset != 'UTF8') + { + $username = ecs_iconv('UTF8', $this->charset, $username); + } + $sql = "SELECT " . $this->field_id . " AS user_id, salt, " . $this->field_pass . " As password ". + " FROM " . $this->table($this->user_table) . + " WHERE " . $this->field_name . "='$username'"; + + $row = $this->db->getRow($sql); + + $time = time() + 3600 * 24 * 30; + setcookie($this->cookie_prefix.'sessionid', '', time() - 3600 * 24, $this->cookie_path, $this->cookie_domain); + setcookie($this->cookie_prefix.'userid', $row['user_id'], time() + 3600 * 24 * 30, $this->cookie_path, $this->cookie_domain); + setcookie($this->cookie_prefix.'password', $row['password'], time() + 3600 * 24 * 30, $this->cookie_path, $this->cookie_domain); + } + } + + /** + * 检查cookie + * + * @access public + * @param + * + * @return void + */ + function check_cookie () + { + if ((!isset($_COOKIE[$this->cookie_prefix.'userid'])) || (!isset($_COOKIE[$this->cookie_prefix.'password']))) + { + return false; + } + + $sql = "SELECT " . $this->field_name . + " FROM " .$this->table($this->user_table). + " WHERE " .$this->field_id ."='". $_COOKIE[$this->cookie_prefix.'userid'] . "'". + " AND " . $this->field_pass . "='" . $_COOKIE[$this->cookie_prefix.'password'] . "'"; + $username = $this->db->getOne($sql); + + if ($username && ($this->charset != 'UTF8')) + { + $username = ecs_iconv($this->charset, 'UTF8', $username); + } + + return $username; + } + + /** + * 获取论坛有效积分及单位 + * + * @access public + * @param + * + * @return void + */ + function get_points_name () + { + static $ava_credits = NULL; + if ($ava_credits === NULL) + { + $sql = "SELECT IF(value>'' , value, defaultvalue)". + " FROM " . $this->table('setting'). + " WHERE varname = 'bankcurrency'"; + $unit = $this->db->getOne($sql); + + $ava_credits['cash']['title'] = 'CASH'; + $ava_credits['cash']['unit'] = empty($unit)? '' : ($this->charset != 'UTF8') ? ecs_iconv($this->charset, 'UTF8', $unit) : $unit; + } + + return $ava_credits; + } +} +?> \ No newline at end of file diff --git a/includes/modules/integrates/phpbb.php b/includes/modules/integrates/phpbb.php new file mode 100644 index 0000000..ef0dc54 --- /dev/null +++ b/includes/modules/integrates/phpbb.php @@ -0,0 +1,232 @@ +phpbb($cfg); + } + + /** + * + * + * @access public + * @param + * + * @return void + */ + function phpbb($cfg) + { + parent::integrate($cfg); + if ($this->error) + { + /* 数据库连接出错 */ + return false; + } + //$this->cookie_prefix = $cfg['cookie_prefix']; + $this->field_id = 'user_id'; + $this->field_name = 'username'; + $this->field_email = 'user_email'; + $this->field_gender = 'NULL'; + $this->field_bday = 'NULL'; + $this->field_pass = 'user_password'; + $this->field_reg_date = 'user_regdate'; + $this->user_table = 'users'; + + /* 检查数据表是否存在 */ + $sql = "SHOW TABLES LIKE '" . $this->prefix . "%'"; + + $exist_tables = $this->db->getCol($sql); + + if (empty($exist_tables) || (!in_array($this->prefix.$this->user_table, $exist_tables)) || (!in_array($this->prefix.'config', $exist_tables))) + { + $this->error = 2; + /* 缺少数据表 */ + return false; + } + + $this->cookie_prefix = $this->db->getOne("SELECT config_value FROM " .$this->table('config'). " WHERE config_name='cookie_name'"); + } + + + /** + * 设置论坛cookie + * + * @access public + * @param + * + * @return void + */ + function set_cookie ($username="") + { + parent::set_cookie($username); + if (empty($username)) + { + $time = time() - 3600; + setcookie($this->cookie_prefix.'_data', '', $time, $this->cookie_path, $this->cookie_domain); + setcookie($this->cookie_prefix.'_sid', '', $time, $this->cookie_path, $this->cookie_domain); + } + else + { + if ($this->charset != 'UTF8') + { + $username = ecs_iconv('UTF8', $this->charset, $username); + } + + $sql = "SELECT " .$this->field_id. " AS user_id, " .$this->field_name. " AS user_name, " .$this->field_email." AS email ". + " FROM " .$this->table($this->user_table). + " WHERE " .$this->field_name. " = '$username'"; + + $row = $this->db->getRow($sql); + + $auto_login_key = md5($this->dss_rand() . $this->dss_rand()); + + /* 向整合对象的数据表里写入cookie值 */ + $this->db->query("INSERT INTO " .$this->table('sessions_keys')." (key_id, user_id, last_login) ". + "VALUES ('" .$auto_login_key. "', '$row[user_id]', '".time()."')"); + + $client_ip = ( !empty($HTTP_SERVER_VARS['REMOTE_ADDR']) ) ? $HTTP_SERVER_VARS['REMOTE_ADDR'] : ( ( !empty($HTTP_ENV_VARS['REMOTE_ADDR']) ) ? $HTTP_ENV_VARS['REMOTE_ADDR'] : getenv('REMOTE_ADDR') ); + $sql = "INSERT INTO ".$this->table('sessions')." (session_id, session_user_id, session_start, session_time, session_ip, session_logged_in, session_admin) VALUES('$auto_login_key', '".$row[$this->field_id]."','".time()."','".time()."','".$this->encode_ip($client_ip)."',1, 0)"; + $this->db->query($sql); + + $sessiondata = array('autologinid'=>$auto_login_key, 'userid'=>$row['user_id']); + + setcookie($this->cookie_prefix . '_data', serialize($sessiondata), time() + 31536000, $this->cookie_path, $this->cookie_domain); + setcookie($this->cookie_prefix . '_sid', $auto_login_key, time() + 31536000, $this->cookie_path, $this->cookie_domain); + } + } + + /** + * 检查cookie + * + * @access public + * @param + * + * @return void + */ + function check_cookie () + { + if (empty($_COOKIE[$this->cookie_prefix . '_data']) || empty($_COOKIE[$this->cookie_prefix . '_sid'])) + { + return ''; + } + + /* 序列化cookie,取得用户信息 */ + $cookie_data = addslashes_deep(@unserialize(stripslashes_deep($_COOKIE[$this->cookie_prefix . '_data']))); + $cookie_session_id = addslashes_deep(trim($_COOKIE[$this->cookie_prefix . '_sid'])); + + if (empty($cookie_data['userid']) || empty($cookie_data['autologinid'])) + { + return ''; + } + + $sql = "SELECT " . $this->field_name . + " FROM " . $this->table('sessions') . " AS s ". + " LEFT JOIN " . $this->table($this->user_table) . " AS u ON s.session_user_id = u.user_id". + " WHERE session_id = '$cookie_session_id' AND session_user_id = '$cookie_data[userid]'"; + + $username = $this->db->getOne($sql); + + if (empty($username)) + { + return ''; + } + else + { + if ($this->charset != 'UTF8') + { + $username = ecs_iconv($this->charset, 'UTF8', $username); + } + + return $username; + } + } + + /** + * Our own generator of random values + * This uses a constantly changing value as the base for generating the values + * The board wide setting is updated once per page if this code is called + * With thanks to Anthrax101 for the inspiration on this one + * Added in phpBB 2.0.20 + */ + function dss_rand() + { + $dss_seeded = false; + $rand_seed = $this->db->getOne("SELECT config_value FROM " .$this->table('config'). " WHERE config_name = 'rand_seed'"); + + $val = $rand_seed . microtime(); + $val = md5($val); + $rand_seed = md5($rand_seed . $val . 'a'); + + if ($dss_seeded !== true) + { + $sql = "UPDATE ".$this->table('config')." SET config_value = '".$rand_seed."' WHERE config_name = 'rand_seed'"; + if (!$this->db->query($sql)) + { + die('error'); + } + + $dss_seeded = true; + } + + return substr($val, 16); + } + + function encode_ip($dotquad_ip) + { + $ip_sep = explode('.', $dotquad_ip); + + return sprintf('%02x%02x%02x%02x', $ip_sep[0], $ip_sep[1], $ip_sep[2], $ip_sep[3]); + } + +} \ No newline at end of file diff --git a/includes/modules/integrates/phpwind.php b/includes/modules/integrates/phpwind.php new file mode 100644 index 0000000..0e39bf9 --- /dev/null +++ b/includes/modules/integrates/phpwind.php @@ -0,0 +1,344 @@ +phpwind($cfg); + } + + /** + * 插件类初始化函数 + * + * @access public + * @param + * + * @return void + */ + function phpwind ($cfg) + { + parent::integrate($cfg); + if ($this->error) + { + /* 数据库连接出错 */ + return false; + } + $this->field_id = 'uid'; + $this->field_name = 'username'; + $this->field_email = 'email'; + $this->field_gender = 'gender'; + $this->field_bday = 'bday'; + $this->field_pass = 'password'; + $this->field_reg_date = 'regdate'; + $this->user_table = 'members'; + + /* 检查数据表是否存在 */ + $sql = "SHOW TABLES LIKE '" . $this->prefix . "%'"; + + $exist_tables = $this->db->getCol($sql); + + if (empty($exist_tables) || (!in_array($this->prefix.$this->user_table, $exist_tables)) || (!in_array($this->prefix.'config', $exist_tables))) + { + $this->error = 2; + /* 缺少数据表 */ + return false; + } + + /* 设置论坛的加密密钥 */ + $this->db_hash = $this->db->GetOne("SELECT `db_value` FROM ".$this->table('config')." WHERE `db_name` = 'db_hash'"); + } + + + + /** + * 设置论坛cookie + * + * @access public + * @param + * + * @return void + */ + function set_cookie ($username="") + { + parent::set_cookie($username); + $cookie_name = 'winduser'; + if (empty($username)) + { + $time = time() - 3600; + setcookie($cookie_name, '', $time, $this->cookie_path, $this->cookie_domain); + } + else + { + /* + if ($this->charset != 'UTF8') + { + $username = ecs_iconv('UTF8', $this->charset, $username); + }*/ + + + $sql = "SELECT " . $this->field_id . " AS user_id, " . $this->field_pass . " As password ". + " FROM " . $this->table($this->user_table) . + " WHERE " . $this->field_name . "='$username'"; + + $row = $this->db->getRow($sql); + + $cookie_name = 'winduser'; + $salt = md5($_SERVER["HTTP_USER_AGENT"] . $row['password'] . $this->db_hash); + + //$auto_login_key = $this->code_string($row['user_id'] . "\t" . $salt, 'ENCODE'); + $auto_login_key = $row['user_id'] . "\t" . $salt; + + setcookie($cookie_name, $auto_login_key, time()+3600*24*30, $this->cookie_path, $this->cookie_domain); + } + } + + /** + * 检查cookie + * + * @access public + * @param + * + * @return void + */ + function check_cookie () + { + $cookie_name = 'winduser'; + + if (!isset($_COOKIE[$cookie_name])) + { + return ''; + } + + $arr = addslashes_deep(explode("\t", $_COOKIE[$cookie_name])); + if (count($arr) != 2) + { + return false; + } + list($user_id, $salt_probe) = $arr; + + $sql = "SELECT " .$this->field_id. " AS user_id, " . $this->field_name . " As user_name, ". + $this->field_pass . " AS password ". + " FROM ".$this->table($this->user_table). + " WHERE " . $this->field_id . " = '$user_id'"; + $row = $this->db->getRow($sql); + + if (!$row) + { + return ''; + } + + $salt = md5($_SERVER["HTTP_USER_AGENT"] . $row['password'] . $this->db_hash); + + if ($salt != $salt_probe) + { + return ''; + } + + /* + if ($this->charset != 'UTF8') + { + $row['user_name'] = ecs_iconv($this->charset, 'UTF8', $row['user_name']); + } + */ + + return $row['user_name']; + + } + + + /** + * 获取论坛有效积分及单位 + * + * @access public + * @param + * + * @return void + */ + function get_points_name () + { + static $ava_credits = NULL; + if ($ava_credits === NULL) + { + $sql = "SELECT db_value FROM " . $this->table('config') . " WHERE db_name='db_credits'"; + $str = $this->db->getOne($sql); + if (empty($str)) + { + return array(); + } + + /* + if ($this->charset != 'UTF8') + { + $str = empty($str) ? '' : ecs_iconv($this->charset, 'UTF8', $str); + } + */ + + list($ava_credits['money']['title'], $ava_credits['money']['unit'],$ava_credits['rvrc']['title'],$ava_credits['rvrc']['unit'],$ava_credits['credit']['title'], $ava_credits['credit']['unit'])=explode("\t",$str); + } + + return $ava_credits; + } + + /** + * 获取用户积分 + * + * @access public + * @param + * + * @return array + */ + function get_points($username) + { + $credits = $this->get_points_name(); + $fileds = array_keys($credits); + + if ($fileds) + { + /* + if ($this->charset != 'UTF8') + { + $username = ecs_iconv('UTF8', $this->charset, $username); + } + */ + $sql = "SELECT ud." . $this->field_id . ', ' . implode(', ',$fileds). + " FROM " . $this->table('memberdata'). "AS ud, ". + $this->table($this->user_table). " AS u ". + " WHERE u." . $this->field_id . "= ud." .$this->field_id . " AND u." . $this->field_name . "='$username'"; + $row = $this->db->getRow($sql); + if (isset($row['rvrc'])) + { + $row['rvrc'] = floor($row['rvrc'] /10); + } + return $row; + } + else + { + return false; + } + } + + /** + * 积分设置 + * + * @access public + * @param + * + * @return void + */ + function set_points ($username, $credits) + { + /* + If ($this->charset != 'UTF8') + { + $username = ecs_iconv('UTF8', $this->charset, $username); + } + */ + + if (isset($credits['rvrc'])) + { + $credits['rvrc'] = $credits['rvrc'] * 10; + } + + $sql = "SELECT " . $this->field_id . + " FROM " . $this->table($this->user_table). + " WHERE " . $this->field_name . "='$username'"; + $uid = $this->db->getOne($sql); + + $user_set = array_keys($credits); + $points_set = array_keys($this->get_points_name()); + + $set = array_intersect($user_set, $points_set); + + if ($set) + { + $tmp = array(); + foreach ($set as $credit) + { + $tmp[] = $credit . '=' . $credit . '+' . $credits[$credit]; + } + $sql = "UPDATE " . $this->table('memberdata'). + " SET " . implode(', ', $tmp). + " WHERE " . $this->field_id . " = '$uid'"; + $this->db->query($sql); + } + + return true; + } + + /** + * + * + * @access public + * @param + * + * @return void + */ + function add_user($username, $password, $email, $gender = -1, $bday = 0, $reg_date=0, $md5password='') + { + $result = parent::add_user($username, $password, $email, $gender, $bday, $reg_date, $md5password); + if (!$result) + { + return false; + } + + $user_id = $this->check_user($username); + if ($user_id > 0) + { + $sql = "REPLACE INTO " . $this->table('memberdata') . " (" . $this->field_id .") VALUES ('$user_id')"; + $this->db->query($sql); + } + + return true; + } +} +?> \ No newline at end of file diff --git a/includes/modules/integrates/phpwind5.php b/includes/modules/integrates/phpwind5.php new file mode 100644 index 0000000..87d0a29 --- /dev/null +++ b/includes/modules/integrates/phpwind5.php @@ -0,0 +1,371 @@ +phpwind5($cfg); + } + + /** + * 插件类初始化函数 + * + * @access public + * @param + * + * @return void + */ + function phpwind5 ($cfg) + { + parent::integrate($cfg); + if ($this->error) + { + /* 数据库连接出错 */ + return false; + } + $this->field_id = 'uid'; + $this->field_name = 'username'; + $this->field_email = 'email'; + $this->field_gender = 'gender'; + $this->field_bday = 'bday'; + $this->field_pass = 'password'; + $this->field_reg_date = 'regdate'; + $this->user_table = 'members'; + + /* 检查数据表是否存在 */ + $sql = "SHOW TABLES LIKE '" . $this->prefix . "%'"; + + $exist_tables = $this->db->getCol($sql); + + if (empty($exist_tables) || (!in_array($this->prefix.$this->user_table, $exist_tables)) || (!in_array($this->prefix.'config', $exist_tables))) + { + $this->error = 2; + /* 缺少数据表 */ + return false; + } + + /* 设置论坛的加密密钥 */ + $this->db_hash = $this->db->GetOne("SELECT `db_value` FROM ".$this->table('config')." WHERE `db_name` = 'db_hash'"); + } + + + + /** + * 设置论坛cookie + * + * @access public + * @param + * + * @return void + */ + function set_cookie ($username="") + { + parent::set_cookie($username); + $cookie_name = substr(md5($this->db_hash), 0, 5) . '_winduser'; + if (empty($username)) + { + $time = time() - 3600; + setcookie($cookie_name, '', $time, $this->cookie_path, $this->cookie_domain); + } + else + { + /*if ($this->charset != 'UTF8') + { + $username = ecs_iconv('UTF8', $this->charset, $username); + }*/ + + + $sql = "SELECT " . $this->field_id . " AS user_id, " . $this->field_pass . " As password ". + " FROM " . $this->table($this->user_table) . + " WHERE " . $this->field_name . "='$username'"; + + $row = $this->db->getRow($sql); + + $cookie_name = substr(md5($this->db_hash), 0, 5) . '_winduser'; + $salt = md5($_SERVER["HTTP_USER_AGENT"] . $row['password'] . $this->db_hash); + + $auto_login_key = $this->code_string($row['user_id'] . "\t" . $salt, 'ENCODE'); + + setcookie($cookie_name, $auto_login_key, time()+3600*24*30, $this->cookie_path, $this->cookie_domain); + } + } + + /** + * 检查cookie + * + * @access public + * @param + * + * @return void + */ + function check_cookie () + { + $cookie_name = substr(md5($this->db_hash), 0, 5) . '_winduser'; + + if (!isset($_COOKIE[$cookie_name])) + { + return ''; + } + + $arr = addslashes_deep(explode("\t", $this->code_string($_COOKIE[$cookie_name], 'DECODE'))); + if (count($arr) != 2) + { + return false; + } + list($user_id, $salt_probe) = $arr; + + $sql = "SELECT " .$this->field_id. " AS user_id, " . $this->field_name . " As user_name, ". + $this->field_pass . " AS password ". + " FROM ".$this->table($this->user_table). + " WHERE " . $this->field_id . " = '$user_id'"; + $row = $this->db->getRow($sql); + + if (!$row) + { + return ''; + } + + $salt = md5($_SERVER["HTTP_USER_AGENT"] . $row['password'] . $this->db_hash); + + if ($salt != $salt_probe) + { + return ''; + } + + /* + if ($this->charset != 'UTF8') + { + $row['user_name'] = ecs_iconv($this->charset, 'UTF8', $row['user_name']); + } + */ + + return $row['user_name']; + + } + + /* 加密解密函数,自动登录密钥也是用该函数进行加密解密 */ + function code_string($string, $action='ENCODE') + { + $key = substr(md5($_SERVER["HTTP_USER_AGENT"] . $this->db_hash), 8, 18); + $string = $action == 'ENCODE' ? $string : base64_decode($string); + $len = strlen($key); + $code = ''; + for ($i = 0, $count = strlen($string); $i < $count; $i++) + { + $k = $i % $len; + $code .= $string[$i] ^ $key[$k]; + } + + $code = $action == 'DECODE' ? $code : base64_encode($code); + + return $code; + } + + /** + * 获取论坛有效积分及单位 + * + * @access public + * @param + * + * @return void + */ + function get_points_name () + { + static $ava_credits = NULL; + if ($ava_credits === NULL) + { + $sql = "SELECT db_value FROM " . $this->table('config') . " WHERE db_name='db_credits'"; + $str = $this->db->getOne($sql); + if (empty($str)) + { + return array(); + } + + /* + if ($this->charset != 'UTF8') + { + $str = empty($str) ? '' : ecs_iconv($this->charset, 'UTF8', $str); + } + */ + + list($ava_credits['money']['title'], $ava_credits['money']['unit'],$ava_credits['rvrc']['title'],$ava_credits['rvrc']['unit'],$ava_credits['credit']['title'], $ava_credits['credit']['unit'])=explode("\t",$str); + } + + return $ava_credits; + } + + /** + * 获取用户积分 + * + * @access public + * @param + * + * @return array + */ + function get_points($username) + { + $credits = $this->get_points_name(); + $fileds = array_keys($credits); + if ($fileds) + { + /* + if ($this->charset != 'UTF8') + { + $username = ecs_iconv('UTF8', $this->charset, $username); + } + */ + $sql = "SELECT ud." . $this->field_id . ', ' . implode(', ',$fileds). + " FROM " . $this->table('memberdata'). "AS ud, ". + $this->table($this->user_table). " AS u ". + " WHERE u." . $this->field_id . "= ud." .$this->field_id . " AND u." . $this->field_name . "='$username'"; + $row = $this->db->getRow($sql); + if (isset($row['rvrc'])) + { + $row['rvrc'] = floor($row['rvrc'] /10); + } + return $row; + } + else + { + return false; + } + } + + /** + * 积分设置 + * + * @access public + * @param + * + * @return void + */ + function set_points ($username, $credits) + { + /* + If ($this->charset != 'UTF8') + { + $username = ecs_iconv('UTF8', $this->charset, $username); + } + */ + + if (isset($credits['rvrc'])) + { + $credits['rvrc'] = $credits['rvrc'] * 10; + } + + $sql = "SELECT " . $this->field_id . + " FROM " . $this->table($this->user_table). + " WHERE " . $this->field_name . "='$username'"; + $uid = $this->db->getOne($sql); + + $user_set = array_keys($credits); + $points_set = array_keys($this->get_points_name()); + + $set = array_intersect($user_set, $points_set); + + if ($set) + { + $tmp = array(); + foreach ($set as $credit) + { + $tmp[] = $credit . '=' . $credit . '+' . $credits[$credit]; + } + $sql = "UPDATE " . $this->table('memberdata'). + " SET " . implode(', ', $tmp). + " WHERE " . $this->field_id . " = '$uid'"; + $this->db->query($sql); + } + + return true; + } + + + /** + * 添加新用户的函数 + * + * @access public + * @param string username 用户名 + * @param string password 登录密码 + * @param string email 邮件地址 + * @param string bday 生日 + * @param string gender 性别 + * @return int 返回最新的ID + */ + function add_user($username, $password, $email, $gender = -1, $bday = 0, $reg_date=0, $md5password='') + { + $result = parent::add_user($username, $password, $email, $gender, $bday, $reg_date, $md5password); + + if (!$result) + { + return false; + } + + /* + if ($this->charset != 'UTF8') + { + $username = ecs_iconv('UTF8', $this->charset, $username); + } + /* + + /* 更新memberdata表 */ + $sql = 'INSERT INTO '. $this->table('memberdata') .' ('. $this->field_id .") " . + " SELECT " . $this->field_id . + " FROM " . $this->table($this->user_table) . + " WHERE " . $this->field_name . "='$username'"; + $this->db->query($sql); + + return true; + } +} + +?> \ No newline at end of file diff --git a/includes/modules/integrates/phpwind6.php b/includes/modules/integrates/phpwind6.php new file mode 100644 index 0000000..df5e32c --- /dev/null +++ b/includes/modules/integrates/phpwind6.php @@ -0,0 +1,355 @@ +phpwind6($cfg); + } + + /** + * 插件类初始化函数 + * + * @access public + * @param + * + * @return void + */ + function phpwind6 ($cfg) + { + parent::integrate($cfg); + if ($this->error) + { + /* 数据库连接出错 */ + return false; + } + $this->field_id = 'uid'; + $this->field_name = 'username'; + $this->field_email = 'email'; + $this->field_gender = 'gender'; + $this->field_safecv = 'safecv'; + $this->field_bday = 'bday'; + $this->field_pass = 'password'; + $this->field_reg_date = 'regdate'; + $this->user_table = 'members'; + + /* 检查数据表是否存在 */ + $sql = "SHOW TABLES LIKE '" . $this->prefix . "%'"; + + $exist_tables = $this->db->getCol($sql); + + if (empty($exist_tables) || (!in_array($this->prefix.$this->user_table, $exist_tables)) || (!in_array($this->prefix.'config', $exist_tables))) + { + $this->error = 2; + /* 缺少数据表 */ + return false; + } + + /* 设置论坛的加密密钥 */ + $this->db_hash = $this->db->GetOne("SELECT `db_value` FROM ".$this->table('config')." WHERE `db_name` = 'db_hash'"); + $this->db_sitehash = $this->db->GetOne("SELECT `db_value` FROM ".$this->table('config')." WHERE `db_name` = 'db_sitehash'"); + } + + + + /** + * 设置论坛cookie + * + * @access public + * @param + * + * @return void + */ + function set_cookie ($username="") + { + parent::set_cookie($username); + $cookie_name = substr(md5($this->db_sitehash), 0, 5) . '_winduser'; + if (empty($username)) + { + $time = time() - 3600; + setcookie($cookie_name, '', $time, $this->cookie_path, $this->cookie_domain); + } + else + { + + $sql = "SELECT " . $this->field_id . " AS user_id, " . $this->field_pass . " As password," . $this->field_safecv ." AS safecv". + " FROM " . $this->table($this->user_table) . + " WHERE " . $this->field_name . "='$username'"; + + $row = $this->db->getRow($sql); + + $cookie_name = substr(md5($this->db_sitehash), 0, 5) . '_winduser'; + $salt = md5($_SERVER["HTTP_USER_AGENT"] . $row['password'] . $this->db_hash); + + $auto_login_key = $this->code_string($row['user_id']."\t".$salt."\t".$row['safecv'], 'ENCODE'); + + setcookie($cookie_name, $auto_login_key, time()+3600*24*30, $this->cookie_path, $this->cookie_domain); + } + } + + /** + * 检查cookie + * + * @access public + * @param + * + * @return void + */ + function check_cookie () + { + $cookie_name = substr(md5($this->db_sitehash), 0, 5) . '_winduser'; + + if (!isset($_COOKIE[$cookie_name])) + { + return ''; + } + + $arr = addslashes_deep(explode("\t", $this->code_string($_COOKIE[$cookie_name], 'DECODE'))); + + if (count($arr) != 3) + { + return false; + } + list($user_id, $salt_probe) = $arr; + + $sql = "SELECT " .$this->field_id. " AS user_id, " . $this->field_name . " As user_name, ". + $this->field_pass . " AS password ". + " FROM ".$this->table($this->user_table). + " WHERE " . $this->field_id . " = '$user_id'"; + $row = $this->db->getRow($sql); + + if (!$row) + { + return ''; + } + + $salt = md5($_SERVER["HTTP_USER_AGENT"] . $row['password'] . $this->db_hash); + + if ($salt != $salt_probe) + { + return ''; + } + + return $row['user_name']; + + } + + /* 加密解密函数,自动登录密钥也是用该函数进行加密解密 */ + function code_string($string, $action='ENCODE') + { + $key = substr(md5($_SERVER["HTTP_USER_AGENT"] . $this->db_hash), 8, 18); + + $string = $action == 'ENCODE' ? $string : base64_decode($string); + $keylen = strlen($key); + $strlen = strlen($string); + $code = ''; + for ($i = 0; $i < $strlen; $i++) + { + $k = $i % $keylen; + $code .= $string[$i] ^ $key[$k]; + } + + $code = $action == 'DECODE' ? $code : base64_encode($code); + + return $code; + } + + + /** + * 获取论坛有效积分及单位 + * + * @access public + * @param + * + * @return void + */ + function get_points_name () + { + static $ava_credits = NULL; + if ($ava_credits === NULL) + { + $sql = "SELECT db_value FROM " . $this->table('config') . " WHERE db_name='db_credits'"; + $str = $this->db->getOne($sql); + if (empty($str)) + { + $change_arr = array( + 'credit' => 'db_credit', + 'money'=>'db_money', + 'rvrc' => 'db_rvrc', + ); + foreach ($change_arr as $key => $name) + { + $sql = "SELECT db_value FROM " . $this->table('config') . " WHERE db_name='".$name."unit'"; + $ava_credits[$key]['unit'] = $this->db->getOne($sql); + + $sql = "SELECT db_value FROM " . $this->table('config') . " WHERE db_name='".$name."name'"; + $ava_credits[$key]['title'] = $this->db->getOne($sql); + } + } + else + { + list($ava_credits['money']['title'], $ava_credits['money']['unit'],$ava_credits['rvrc']['title'],$ava_credits['rvrc']['unit'],$ava_credits['credit']['title'], $ava_credits['credit']['unit'])=explode("\t",$str); + + } + + } + + return $ava_credits; + } + + /** + * 获取用户积分 + * + * @access public + * @param + * + * @return array + */ + function get_points($username) + { + $credits = $this->get_points_name(); + $fileds = array_keys($credits); + if ($fileds) + { + $sql = "SELECT ud." . $this->field_id . ', ' . implode(', ',$fileds). + " FROM " . $this->table('memberdata'). "AS ud, ". + $this->table($this->user_table). " AS u ". + " WHERE u." . $this->field_id . "= ud." .$this->field_id . " AND u." . $this->field_name . "='$username'"; + $row = $this->db->getRow($sql); + if (isset($row['rvrc'])) + { + $row['rvrc'] = floor($row['rvrc'] /10); + } + return $row; + } + else + { + return false; + } + } + + /** + * 积分设置 + * + * @access public + * @param + * + * @return void + */ + function set_points ($username, $credits) + { + if (isset($credits['rvrc'])) + { + $credits['rvrc'] = $credits['rvrc'] * 10; + } + + $sql = "SELECT " . $this->field_id . + " FROM " . $this->table($this->user_table). + " WHERE " . $this->field_name . "='$username'"; + $uid = $this->db->getOne($sql); + + $user_set = array_keys($credits); + $points_set = array_keys($this->get_points_name()); + + $set = array_intersect($user_set, $points_set); + + if ($set) + { + $tmp = array(); + foreach ($set as $credit) + { + $tmp[] = $credit . '=' . $credit . '+' . $credits[$credit]; + } + $sql = "UPDATE " . $this->table('memberdata'). + " SET " . implode(', ', $tmp). + " WHERE " . $this->field_id . " = '$uid'"; + $this->db->query($sql); + } + + return true; + } + + + /** + * 添加新用户的函数 + * + * @access public + * @param string username 用户名 + * @param string password 登录密码 + * @param string email 邮件地址 + * @param string bday 生日 + * @param string gender 性别 + * @return int 返回最新的ID + */ + function add_user($username, $password, $email, $gender = -1, $bday = 0, $reg_date=0, $md5password='') + { + $result = parent::add_user($username, $password, $email, $gender, $bday, $reg_date, $md5password); + + if (!$result) + { + return false; + } + + /* 更新memberdata表 */ + $sql = 'INSERT INTO '. $this->table('memberdata') .' ('. $this->field_id .") " . + " SELECT " . $this->field_id . + " FROM " . $this->table($this->user_table) . + " WHERE " . $this->field_name . "='$username'"; + $this->db->query($sql); + + return true; + } +} + +?> \ No newline at end of file diff --git a/includes/modules/integrates/ucenter.php b/includes/modules/integrates/ucenter.php new file mode 100644 index 0000000..bfad323 --- /dev/null +++ b/includes/modules/integrates/ucenter.php @@ -0,0 +1,632 @@ +ucenter($cfg); + } + + /** + * 构造函数 + * + * @access public + * @param + * + * @return void + */ + function ucenter($cfg) + { + parent::integrate(array()); + $this->user_table = 'users'; + $this->field_id = 'user_id'; + $this->field_name = 'user_name'; + $this->field_pass = 'password'; + $this->field_email = 'email'; + $this->field_gender = 'sex'; + $this->field_bday = 'birthday'; + $this->field_reg_date = 'reg_time'; + $this->need_sync = false; + $this->is_ecshop = 1; + + /* 初始化UC需要常量 */ + if (!defined('UC_CONNECT') && isset($cfg['uc_id']) && isset($cfg['db_host']) && isset($cfg['db_user']) && isset($cfg['db_name'])) + { + if(strpos($cfg['db_pre'], '`' . $cfg['db_name'] . '`') === 0) + { + $db_pre = $cfg['db_pre']; + } + else + { + $db_pre = '`' . $cfg['db_name'] . '`.' . $cfg['db_pre']; + } + + define('UC_CONNECT', isset($cfg['uc_connect'])?$cfg['uc_connect']:''); + define('UC_DBHOST', isset($cfg['db_host'])?$cfg['db_host']:''); + define('UC_DBUSER', isset($cfg['db_user'])?$cfg['db_user']:''); + define('UC_DBPW', isset($cfg['db_pass'])?$cfg['db_pass']:''); + define('UC_DBNAME', isset($cfg['db_name'])?$cfg['db_name']:''); + define('UC_DBCHARSET', isset($cfg['db_charset'])?$cfg['db_charset']:''); + define('UC_DBTABLEPRE', $db_pre); + define('UC_DBCONNECT', '0'); + define('UC_KEY', isset($cfg['uc_key'])?$cfg['uc_key']:''); + define('UC_API', isset($cfg['uc_url'])?$cfg['uc_url']:''); + define('UC_CHARSET', isset($cfg['uc_charset'])?$cfg['uc_charset']:''); + define('UC_IP', isset($cfg['uc_ip'])?$cfg['uc_ip']:''); + define('UC_APPID', isset($cfg['uc_id'])?$cfg['uc_id']:''); + define('UC_PPP', '20'); + } + } + + /** + * 用户登录函数 + * + * @access public + * @param string $username + * @param string $password + * + * @return void + */ + function login($username, $password) + { + list($uid, $uname, $pwd, $email, $repeat) = uc_call("uc_user_login", array($username, $password)); + $uname = addslashes($uname); + + if($uid > 0) + { + //检查用户是否存在,不存在直接放入用户表 + $result = $this->db->getRow("SELECT user_id,ec_salt FROM " . $GLOBALS['ecs']->table("users") . " WHERE user_name='$username'"); + $name_exist =$result['user_id']; + if(empty($result['ec_salt'])) + { + $user_exist = $this->db->getOne("SELECT user_id FROM " . $GLOBALS['ecs']->table("users") . " WHERE user_name='$username' AND password = '" . MD5($password) ."'"); + if(!empty($user_exist)) + { + $ec_salt=rand(1,9999); + $this->db->query('UPDATE ' . $GLOBALS['ecs']->table("users") . "SET `password`='".MD5(MD5($password). $ec_salt)."',`ec_salt`='". $ec_salt."' WHERE user_id = '" . $uid . "'"); + + } + } + else + { + $user_exist = $this->db->getOne("SELECT user_id FROM " . $GLOBALS['ecs']->table("users") . " WHERE user_name='$username' AND password = '" . MD5(MD5($password). $result['ec_salt'])."'"); + } + + + + if (empty($user_exist)) + { + if(empty($name_exist)) + { + $reg_date = time(); + $ip = real_ip(); + $password = $this->compile_password(array('password'=>$password)); + $this->db->query('INSERT INTO ' . $GLOBALS['ecs']->table("users") . "(`user_id`, `email`, `user_name`, `password`, `reg_time`, `last_login`, `last_ip`) VALUES ('$uid', '$email', '$uname', '$password', '$reg_date', '$reg_date', '$ip')"); + } + else + { + if(empty($result['ec_salt'])) + { + $result['ec_salt']=0; + } + $this->db->query('UPDATE ' . $GLOBALS['ecs']->table("users") . "SET `password`='".MD5(MD5($password). $result['ec_salt'])."',`ec_salt`='". $result['ec_salt']."' WHERE user_id = '" . $uid . "'"); + } + } + $this->set_session($uname); + $this->set_cookie($uname); + $this->ucdata = uc_call("uc_user_synlogin", array($uid)); + return true; + } + elseif($uid == -1) + { + $this->error = ERR_INVALID_USERNAME; + return false; + } + elseif ($uid == -2) + { + $this->error = ERR_INVALID_PASSWORD; + return false; + } + else + { + return false; + } + } + + /** + * 用户退出 + * + * @access public + * @param + * + * @return void + */ + function logout() + { + $this->set_cookie(); //清除cookie + $this->set_session(); //清除session + $this->ucdata = uc_call("uc_user_synlogout"); //同步退出 + return true; + } + + /*添加用户*/ + function add_user($username, $password, $email) + { + /* 检测用户名 */ + if ($this->check_user($username)) + { + $this->error = ERR_USERNAME_EXISTS; + return false; + } + + $uid = uc_call("uc_user_register", array($username, $password, $email)); + if ($uid <= 0) + { + if($uid == -1) + { + $this->error = ERR_INVALID_USERNAME; + return false; + } + elseif($uid == -2) + { + $this->error = ERR_USERNAME_NOT_ALLOW; + return false; + } + elseif($uid == -3) + { + $this->error = ERR_USERNAME_EXISTS; + return false; + } + elseif($uid == -4) + { + $this->error = ERR_INVALID_EMAIL; + return false; + } + elseif($uid == -5) + { + $this->error = ERR_EMAIL_NOT_ALLOW; + return false; + } + elseif($uid == -6) + { + $this->error = ERR_EMAIL_EXISTS; + return false; + } + else + { + return false; + } + } + else + { + //注册成功,插入用户表 + $reg_date = time(); + $ip = real_ip(); + $password = $this->compile_password(array('password'=>$password)); + $this->db->query('INSERT INTO ' . $GLOBALS['ecs']->table("users") . "(`user_id`, `email`, `user_name`, `password`, `reg_time`, `last_login`, `last_ip`) VALUES ('$uid', '$email', '$username', '$password', '$reg_date', '$reg_date', '$ip')"); + return true; + } + } + + /** + * 检查指定用户是否存在及密码是否正确 + * + * @access public + * @param string $username 用户名 + * + * @return int + */ + function check_user($username, $password = null) + { + $userdata = uc_call("uc_user_checkname", array($username)); + if ($userdata == 1) + { + return false; + } + else + { + return true; + } + } + + /** + * 检测Email是否合法 + * + * @access public + * @param string $email 邮箱 + * + * @return blob + */ + function check_email($email) + { + if (!empty($email)) + { + $email_exist = uc_call('uc_user_checkemail', array($email)); + if ($email_exist == 1) + { + return false; + } + else + { + $this->error = ERR_EMAIL_EXISTS; + return true; + } + } + return true; + } + + /* 编辑用户信息 */ + function edit_user($cfg, $forget_pwd = '0') + { + $real_username = $cfg['username']; + $cfg['username'] = addslashes($cfg['username']); + $set_str = ''; + $valarr =array('email'=>'email', 'gender'=>'sex', 'bday'=>'birthday'); + foreach ($cfg as $key => $val) + { + if ($key == 'username' || $key == 'password' || $key == 'old_password') + { + continue; + } + $set_str .= $valarr[$key] . '=' . "'$val',"; + } + $set_str = substr($set_str, 0, -1); + if (!empty($set_str)) + { + $sql = "UPDATE " . $GLOBALS['ecs']->table('users') . " SET $set_str WHERE user_name = '$cfg[username]'"; + $GLOBALS['db']->query($sql); + $flag = true; + } + + if (!empty($cfg['email'])) + { + $ucresult = uc_call("uc_user_edit", array($cfg['username'], '', '', $cfg['email'], 1)); + if ($ucresult > 0 ) + { + $flag = true; + } + elseif($ucresult == -4) + { + //echo 'Email 格式有误'; + $this->error = ERR_INVALID_EMAIL; + + return false; + } + elseif($ucresult == -5) + { + //echo 'Email 不允许注册'; + $this->error = ERR_INVALID_EMAIL; + + return false; + } + elseif($ucresult == -6) + { + //echo '该 Email 已经被注册'; + $this->error = ERR_EMAIL_EXISTS; + + return false; + } + elseif ($ucresult < 0 ) + { + return false; + } + } + if (!empty($cfg['old_password']) && !empty($cfg['password']) && $forget_pwd == 0) + { + $ucresult = uc_call("uc_user_edit", array($real_username, $cfg['old_password'], $cfg['password'], '')); + if ($ucresult > 0 ) + { + return true; + } + else + { + $this->error = ERR_INVALID_PASSWORD; + return false; + } + } + elseif (!empty($cfg['password']) && $forget_pwd == 1) + { + $ucresult = uc_call("uc_user_edit", array($real_username, '', $cfg['password'], '', '1')); + if ($ucresult > 0 ) + { + $flag = true; + } + } + + return true; + } + + /** + * 获取指定用户的信息 + * + * @access public + * @param + * + * @return void + */ + function get_profile_by_name($username) + { + //$username = addslashes($username); + + $sql = "SELECT user_id, user_name, email, sex, reg_time FROM " . $GLOBALS['ecs']->table('users') . " WHERE user_name='$username'"; + $row = $this->db->getRow($sql); + return $row; + } + + /** + * 检查cookie是正确,返回用户名 + * + * @access public + * @param + * + * @return void + */ + function check_cookie() + { + return ''; + } + + /** + * 根据登录状态设置cookie + * + * @access public + * @param + * + * @return void + */ + function get_cookie() + { + $id = $this->check_cookie(); + if ($id) + { + if ($this->need_sync) + { + $this->sync($id); + } + $this->set_session($id); + + return true; + } + else + { + return false; + } + } + + /** + * 设置cookie + * + * @access public + * @param + * + * @return void + */ + function set_cookie($username='') + { + if (empty($username)) + { + /* 摧毁cookie */ + $time = time() - 3600; + setcookie("ECS[user_id]", '', $time, $this->cookie_path); + setcookie("ECS[password]", '', $time, $this->cookie_path); + } + else + { + /* 设置cookie */ + $time = time() + 3600 * 24 * 30; + + setcookie("ECS[username]", stripslashes($username), $time, $this->cookie_path, $this->cookie_domain); + $sql = "SELECT user_id, password FROM " . $GLOBALS['ecs']->table('users') . " WHERE user_name='$username' LIMIT 1"; + $row = $GLOBALS['db']->getRow($sql); + if ($row) + { + setcookie("ECS[user_id]", $row['user_id'], $time, $this->cookie_path, $this->cookie_domain); + setcookie("ECS[password]", $row['password'], $time, $this->cookie_path, $this->cookie_domain); + } + } + } + + /** + * 设置指定用户SESSION + * + * @access public + * @param + * + * @return void + */ + function set_session ($username='') + { + if (empty($username)) + { + $GLOBALS['sess']->destroy_session(); + } + else + { + $sql = "SELECT user_id, password, email FROM " . $GLOBALS['ecs']->table('users') . " WHERE user_name='$username' LIMIT 1"; + $row = $GLOBALS['db']->getRow($sql); + + if ($row) + { + $_SESSION['user_id'] = $row['user_id']; + $_SESSION['user_name'] = $username; + $_SESSION['email'] = $row['email']; + } + } + } + + /** + * 获取指定用户的信息 + * + * @access public + * @param + * + * @return void + */ + function get_profile_by_id($id) + { + $sql = "SELECT user_id, user_name, email, sex, birthday, reg_time FROM " . $GLOBALS['ecs']->table('users') . " WHERE user_id='$id'"; + $row = $this->db->getRow($sql); + + return $row; + } + + function get_user_info($username) + { + return $this->get_profile_by_name($username); + } + + /** + * 删除用户 + * + * @access public + * @param + * + * @return void + */ + function remove_user($id) + { + if (is_array($id)) + { + $post_id = array(); + foreach ($id as $val) + { + $post_id[] = $val; + } + } + else + { + $post_id = $id; + } + + /* 如果需要同步或是ecshop插件执行这部分代码 */ + $sql = "SELECT user_id FROM " . $GLOBALS['ecs']->table('users') . " WHERE "; + $sql .= (is_array($post_id)) ? db_create_in($post_id, 'user_name') : "user_name='". $post_id . "' LIMIT 1"; + $col = $GLOBALS['db']->getCol($sql); + + if ($col) + { + $sql = "UPDATE " . $GLOBALS['ecs']->table('users') . " SET parent_id = 0 WHERE " . db_create_in($col, 'parent_id'); //将删除用户的下级的parent_id 改为0 + $GLOBALS['db']->query($sql); + $sql = "DELETE FROM " . $GLOBALS['ecs']->table('users') . " WHERE " . db_create_in($col, 'user_id'); //删除用户 + $GLOBALS['db']->query($sql); + /* 删除用户订单 */ + $sql = "SELECT order_id FROM " . $GLOBALS['ecs']->table('order_info') . " WHERE " . db_create_in($col, 'user_id'); + $GLOBALS['db']->query($sql); + $col_order_id = $GLOBALS['db']->getCol($sql); + if ($col_order_id) + { + $sql = "DELETE FROM " . $GLOBALS['ecs']->table('order_info') . " WHERE " . db_create_in($col_order_id, 'order_id'); + $GLOBALS['db']->query($sql); + $sql = "DELETE FROM " . $GLOBALS['ecs']->table('order_goods') . " WHERE " . db_create_in($col_order_id, 'order_id'); + $GLOBALS['db']->query($sql); + } + + $sql = "DELETE FROM " . $GLOBALS['ecs']->table('booking_goods') . " WHERE " . db_create_in($col, 'user_id'); //删除用户 + $GLOBALS['db']->query($sql); + $sql = "DELETE FROM " . $GLOBALS['ecs']->table('collect_goods') . " WHERE " . db_create_in($col, 'user_id'); //删除会员收藏商品 + $GLOBALS['db']->query($sql); + $sql = "DELETE FROM " . $GLOBALS['ecs']->table('feedback') . " WHERE " . db_create_in($col, 'user_id'); //删除用户留言 + $GLOBALS['db']->query($sql); + $sql = "DELETE FROM " . $GLOBALS['ecs']->table('user_address') . " WHERE " . db_create_in($col, 'user_id'); //删除用户地址 + $GLOBALS['db']->query($sql); + $sql = "DELETE FROM " . $GLOBALS['ecs']->table('user_bonus') . " WHERE " . db_create_in($col, 'user_id'); //删除用户红包 + $GLOBALS['db']->query($sql); + $sql = "DELETE FROM " . $GLOBALS['ecs']->table('user_account') . " WHERE " . db_create_in($col, 'user_id'); //删除用户帐号金额 + $GLOBALS['db']->query($sql); + $sql = "DELETE FROM " . $GLOBALS['ecs']->table('tag') . " WHERE " . db_create_in($col, 'user_id'); //删除用户标记 + $GLOBALS['db']->query($sql); + $sql = "DELETE FROM " . $GLOBALS['ecs']->table('account_log') . " WHERE " . db_create_in($col, 'user_id'); //删除用户日志 + $GLOBALS['db']->query($sql); + } + + if (isset($this->ecshop) && $this->ecshop) + { + /* 如果是ecshop插件直接退出 */ + return; + } + + $sql = "DELETE FROM " . $GLOBALS['ecs']->table('users') . " WHERE "; + if (is_array($post_id)) + { + $sql .= db_create_in($post_id, 'user_name'); + } + else + { + $sql .= "user_name='" . $post_id . "' LIMIT 1"; + } + + $this->db->query($sql); + } + + /** + * 获取论坛有效积分及单位 + * + * @access public + * @param + * + * @return void + */ + function get_points_name () + { + return 'ucenter'; + } +} + +?> \ No newline at end of file diff --git a/includes/modules/integrates/vbb.php b/includes/modules/integrates/vbb.php new file mode 100644 index 0000000..f7e4f8e --- /dev/null +++ b/includes/modules/integrates/vbb.php @@ -0,0 +1,300 @@ +vbb($cfg); + } + + /** + * + * + * @access public + * @param + * + * @return void + */ + function vbb($cfg) + { + parent::integrate($cfg); + if ($this->error) + { + /* 数据库连接出错 */ + return false; + } + + $this->cookie_salt = $cfg['cookie_salt']; + $this->field_id = 'userid'; + $this->field_name = 'username'; + $this->field_email = 'email'; + $this->field_gender = 'NULL'; + $this->field_bday = 'birthday'; + $this->field_pass = 'password'; + $this->field_reg_date = 'joindate'; + $this->user_table = 'user'; + + /* 检查数据表是否存在 */ + $sql = "SHOW TABLES LIKE '" . $this->prefix . "%'"; + + $exist_tables = $this->db->getCol($sql); + + if (empty($exist_tables) || (!in_array($this->prefix.$this->user_table, $exist_tables))) + { + $this->error = 2; + /* 缺少数据表 */ + return false; + } + } + + + + + /** + * 设置论坛cookie + * + * @access public + * @param + * + * @return void + */ + function set_cookie ($username="") + { + parent::set_cookie($username); + if (empty($username)) + { + $time = time() - 3600; + setcookie('bbuserid', '', $time, $this->cookie_path, $this->cookie_domain); + setcookie('bbpassword', '', $time, $this->cookie_path, $this->cookie_domain); + } + else + { + if ($this->charset != 'UTF8') + { + $username = ecs_iconv('UTF8', $this->charset, $username); + } + $sql = "SELECT " . $this->field_id . " AS user_id, " . $this->field_pass . " As password ". + " FROM " . $this->table($this->user_table) . " WHERE " . $this->field_name . "='$username'"; + + $row = $this->db->getRow($sql); + + setcookie('bbuserid', $row['user_id'], time() + 3600 * 24 * 30, $this->cookie_path, $this->cookie_domain); + setcookie('bbpassword', md5($row['password'] . $this->cookie_salt), time() + 3600 * 24 * 30, $this->cookie_path, $this->cookie_domain); + } + } + + /** + * 添加新用户的函数 + * + * @access public + * @param string username 用户名 + * @param string password 登录密码 + * @param string email 邮件地址 + * @param string bday 生日 + * @param string gender 性别 + * @return int 返回最新的ID + */ + function add_user($username, $password, $email, $gender = -1, $bday = 0, $reg_date=0, $md5password='') + { + $result = parent::add_user($username, $password, $email, $gender, $bday, $reg_date, $md5password); + + if (!$result) + { + return false; + } + + $user_title = $this->db->GetOne("SELECT title FROM " .$this->table('usertitle'). " ORDER BY minposts LIMIT 1"); + + if ($this->charset != 'UTF8') + { + $username = ecs_iconv('UTF8', $this->charset, $username); + } + + + /* 编译密码 */ + $salt = addslashes($this->fetch_user_salt()); + + /* 更新数据 */ + $sql = "UPDATE " . $this->table($this->user_table) . + " SET " . $this->field_pass . " = '" . $this->compile_password(array('type'=>PWD_SUF_SALT, 'password'=>$password, 'salt'=>$salt)) . "', ". + " salt = '$salt', ". + " ipaddress = '" . real_ip() . "', ". + " usergroupid = 2, ". + " usertitle = '$user_title' ". + " WHERE " . $this->field_name . "='$username'"; + + $this->db->query($sql); + + $sql = 'INSERT INTO '. $this->table('userfield') .' ('. $this->field_id .") " . + " SELECT " . $this->field_id . + " FROM " . $this->table($this->user_table) . + " WHERE " . $this->field_name . "='$username'"; + $this->db->query($sql); + + $sql = 'INSERT INTO '. $this->table('usertextfield') .' ('. $this->field_id .") " . + " SELECT " . $this->field_id . + " FROM " . $this->table($this->user_table) . + " WHERE " . $this->field_name . "='$username'"; + $this->db->query($sql); + + return true; + } + + /** + * 检查cookie + * + * @access public + * @param + * + * @return void + */ + function check_cookie () + { + if (empty($_COOKIE['bbuserid']) || empty($_COOKIE['bbpassword'])) + { + return ''; + } + + $user_id = intval($_COOKIE['bbuserid']); + $bbpassword = addslashes_deep($_COOKIE['bbpassword']); + + $row = $this->db->getRow("SELECT " . $this->field_name . " AS user_name, " . $this->field_pass . " As password ". + " FROM " . $this->table($this->user_table) . " WHERE " . $this->field_id . "='$user_id'"); + if (empty($row)) + { + return ''; + } + + if ($bbpassword != md5($row['password'].$this->cookie_salt)) + { + return ''; + } + + if ($this->charset != 'UTF8') + { + $row['user_name'] = ecs_iconv($this->charset, 'UTF8', $row['user_name']); + } + + return $row['user_name']; + + } + + + /** + * 检查指定用户是否存在及密码是否正确 + * + * @access public + * @param string $username 用户名 + * + * @return int + */ + function check_user($username, $password = null) + { + if ($this->charset != 'UTF8') + { + $post_username = ecs_iconv('UTF8', $this->charset, $username); + } + else + { + $post_username = $username; + } + + if ($password === null) + { + $sql = "SELECT " . $this->field_id . + " FROM " . $this->table($this->user_table). + " WHERE " . $this->field_name . "='" . $post_username . "'"; + + return $this->db->getOne($sql); + } + else + { + $sql = "SELECT " . $this->field_id . " AS user_id, " . $this->field_pass . " AS password, salt". + " FROM " . $this->table($this->user_table). + " WHERE " . $this->field_name . "='" . $post_username . "'"; + $row = $this->db->getRow($sql); + + if (empty($row)) + { + return 0; + } + + if ($row['password'] != $this->compile_password(array('type'=>PWD_SUF_SALT, 'password'=>$password, 'salt'=>$row['salt']))) + { + return 0; + } + + return $row['user_id']; + + } + } + + /** + * 生成密码种子的函数 + * + * @access private + * @param int length 长度 + * @return string + */ + function fetch_user_salt($length = 3) + { + $salt = ''; + for ($i = 0; $i < $length; $i++) + { + $salt .= chr(mt_rand(32, 126)); + } + + return $salt; + } + +} \ No newline at end of file diff --git a/includes/modules/payment/alipay.php b/includes/modules/payment/alipay.php new file mode 100644 index 0000000..dd96ae6 --- /dev/null +++ b/includes/modules/payment/alipay.php @@ -0,0 +1,272 @@ + 'alipay_account', 'type' => 'text', 'value' => ''), + array('name' => 'alipay_key', 'type' => 'text', 'value' => ''), + array('name' => 'alipay_partner', 'type' => 'text', 'value' => ''), +// array('name' => 'alipay_real_method', 'type' => 'select', 'value' => '0'), +// array('name' => 'alipay_virtual_method', 'type' => 'select', 'value' => '0'), +// array('name' => 'is_instant', 'type' => 'select', 'value' => '0') + array('name' => 'alipay_pay_method', 'type' => 'select', 'value' => '') + ); + + return; +} + +/** + * 类 + */ +class alipay +{ + + /** + * 构造函数 + * + * @access public + * @param + * + * @return void + */ + function alipay() + { + } + + function __construct() + { + $this->alipay(); + } + + /** + * 生成支付代码 + * @param array $order 订单信息 + * @param array $payment 支付方式信息 + */ + function get_code($order, $payment) + { + if (!defined('EC_CHARSET')) + { + $charset = 'utf-8'; + } + else + { + $charset = EC_CHARSET; + } +// if (empty($payment['is_instant'])) +// { +// /* 未开通即时到帐 */ +// $service = 'trade_create_by_buyer'; +// } +// else +// { +// if (!empty($order['order_id'])) +// { +// /* 检查订单是否全部为虚拟商品 */ +// $sql = "SELECT COUNT(*) FROM " .$GLOBALS['ecs']->table('order_goods'). +// " WHERE is_real=1 AND order_id='$order[order_id]'"; +// +// if ($GLOBALS['db']->getOne($sql) > 0) +// { +// /* 订单中存在实体商品 */ +// $service = (!empty($payment['alipay_real_method']) && $payment['alipay_real_method'] == 1) ? +// 'create_direct_pay_by_user' : 'trade_create_by_buyer'; +// } +// else +// { +// /* 订单中全部为虚拟商品 */ +// $service = (!empty($payment['alipay_virtual_method']) && $payment['alipay_virtual_method'] == 1) ? +// 'create_direct_pay_by_user' : 'create_digital_goods_trade_p'; +// } +// } +// else +// { +// /* 非订单方式,按照虚拟商品处理 */ +// $service = (!empty($payment['alipay_virtual_method']) && $payment['alipay_virtual_method'] == 1) ? +// 'create_direct_pay_by_user' : 'create_digital_goods_trade_p'; +// } +// } + + $real_method = $payment['alipay_pay_method']; + + switch ($real_method){ + case '0': + $service = 'trade_create_by_buyer'; + break; + case '1': + $service = 'create_partner_trade_by_buyer'; + break; + case '2': + $service = 'create_direct_pay_by_user'; + break; + } + + $extend_param = 'isv^sh22'; + + $parameter = array( + 'extend_param' => $extend_param, + 'service' => $service, + 'partner' => $payment['alipay_partner'], + //'partner' => ALIPAY_ID, + '_input_charset' => $charset, + 'notify_url' => return_url(basename(__FILE__, '.php')), + 'return_url' => return_url(basename(__FILE__, '.php')), + /* 业务参数 */ + 'subject' => $order['order_sn'], + 'out_trade_no' => $order['order_sn'] . $order['log_id'], + 'price' => $order['order_amount'], + 'quantity' => 1, + 'payment_type' => 1, + /* 物流参数 */ + 'logistics_type' => 'EXPRESS', + 'logistics_fee' => 0, + 'logistics_payment' => 'BUYER_PAY_AFTER_RECEIVE', + /* 买卖双方信息 */ + 'seller_email' => $payment['alipay_account'] + ); + + ksort($parameter); + reset($parameter); + + $param = ''; + $sign = ''; + + foreach ($parameter AS $key => $val) + { + $param .= "$key=" .urlencode($val). "&"; + $sign .= "$key=$val&"; + } + + $param = substr($param, 0, -1); + $sign = substr($sign, 0, -1). $payment['alipay_key']; + //$sign = substr($sign, 0, -1). ALIPAY_AUTH; + + $button = '
    '; + + return $button; + } + + /** + * 响应操作 + */ + function respond() + { + if (!empty($_POST)) + { + foreach($_POST as $key => $data) + { + $_GET[$key] = $data; + } + } + $payment = get_payment($_GET['code']); + $seller_email = rawurldecode($_GET['seller_email']); + $order_sn = str_replace($_GET['subject'], '', $_GET['out_trade_no']); + $order_sn = trim($order_sn); + + /* 检查支付的金额是否相符 */ + if (!check_money($order_sn, $_GET['total_fee'])) + { + return false; + } + + /* 检查数字签名是否正确 */ + ksort($_GET); + reset($_GET); + + $sign = ''; + foreach ($_GET AS $key=>$val) + { + if ($key != 'sign' && $key != 'sign_type' && $key != 'code') + { + $sign .= "$key=$val&"; + } + } + + $sign = substr($sign, 0, -1) . $payment['alipay_key']; + //$sign = substr($sign, 0, -1) . ALIPAY_AUTH; + if (md5($sign) != $_GET['sign']) + { + return false; + } + + if ($_GET['trade_status'] == 'WAIT_SELLER_SEND_GOODS') + { + /* 改变订单状态 */ + order_paid($order_sn, 2); + + return true; + } + elseif ($_GET['trade_status'] == 'TRADE_FINISHED') + { + /* 改变订单状态 */ + order_paid($order_sn); + + return true; + } + elseif ($_GET['trade_status'] == 'TRADE_SUCCESS') + { + /* 改变订单状态 */ + order_paid($order_sn, 2); + + return true; + } + else + { + return false; + } + } +} + +?> \ No newline at end of file diff --git a/includes/modules/payment/balance.php b/includes/modules/payment/balance.php new file mode 100644 index 0000000..bc889a0 --- /dev/null +++ b/includes/modules/payment/balance.php @@ -0,0 +1,101 @@ +balance(); + } + + /** + * 提交函数 + */ + function get_code() + { + return ''; + } + + /** + * 处理函数 + */ + function response() + { + return; + } +} + +?> \ No newline at end of file diff --git a/includes/modules/payment/bank.php b/includes/modules/payment/bank.php new file mode 100644 index 0000000..7d55bcf --- /dev/null +++ b/includes/modules/payment/bank.php @@ -0,0 +1,101 @@ +bank(); + } + + /** + * 提交函数 + */ + function get_code() + { + return ''; + } + + /** + * 处理函数 + */ + function response() + { + return; + } +} + +?> \ No newline at end of file diff --git a/includes/modules/payment/cappay.php b/includes/modules/payment/cappay.php new file mode 100644 index 0000000..e6cbbd3 --- /dev/null +++ b/includes/modules/payment/cappay.php @@ -0,0 +1,239 @@ + 'cappay_account', 'type' => 'text', 'value' => ''), + array('name' => 'cappay_key', 'type' => 'text', 'value' => ''), + array('name' => 'cappay_currency', 'type' => 'select', 'value' => 'USD') + ); + + return; +} + +class cappay +{ + /** + * 构造函数 + * + * @access public + * @param + * + * @return void + */ + function cappay() + { + } + + function __construct() + { + $this->cappay(); + } + + /** + * 生成支付代码 + * @param array $order 订单信息 + * @param array $payment 支付方式信息 + */ + function get_code($order, $payment) + { + $v_rcvname = trim($payment['cappay_account']); + $m_orderid = $order['log_id']; + $v_amount = $order['order_amount']; + $v_moneytype = trim($payment['cappay_currency']);; + $v_url = return_url(basename(__FILE__, '.php')); + $m_ocomment = '欢迎使用首信易支付'; + $v_ymd = date('Ymd',time()); + + /*易支付平台*/ + $MD5Key = $payment['cappay_key']; //<--支付密钥--> 注:此处密钥必须与商家后台里的密钥一致 + $v_oid = "$v_ymd-$v_rcvname-$m_orderid"; + $sourcedata = $v_moneytype.$v_ymd.$v_amount.$v_rcvname.$v_oid.$v_rcvname.$v_url; + $result = $this->hmac_md5($MD5Key,$sourcedata); + $def_url = '
    '; + $def_url .= ""; //商户编号 + $def_url .= ""; //订单编号 + $def_url .= ""; //收货人姓名 + $def_url .= ""; //收货人地址 + $def_url .= ""; //收货人电话 + $def_url .= ""; //收货人邮编 + $def_url .= ""; //订单总金额 + $def_url .= ""; //订单产生日期 + $def_url .= ""; //配货状态 + $def_url .= ""; //订货人姓名 + $def_url .= ""; //币种,0为人民币,1为美元 + $def_url .= ""; //支付动作完成后返回到该url,支付结果以GET方式发送 + $def_url .= ""; //订单数字指纹 + $def_url .= ""; + + $def_url .= '
    '; + + /*易支付会员通道 + $def_url = "
    "; + $def_url .= ""; //商户编号 + $def_url .= ""; //订单编号 + $def_url .= ""; //收货人姓名 + $def_url .= ""; //收货人地址 + $def_url .= ""; //收货人电话 + $def_url .= ""; //收货人邮编 + $def_url .= ""; //订单总金额 + $def_url .= ""; //订单产生日期 + $def_url .= ""; //配货状态 + $def_url .= ""; //订货人姓名 + $def_url .= ""; //币种,0为人民币,1为美元 + $def_url .= ""; //支付动作完成后返回到该url,支付结果以GET方式发送 + $def_url .= ""; //订单数字指纹 + $def_url .= ""; + + $def_url .= '
    '; + + //易支付手机通道 + $def_url = "
    "; + $def_url .= ""; //商户编号 + $def_url .= ""; //订单编号 + $def_url .= ""; //收货人姓名 + $def_url .= ""; //收货人地址 + $def_url .= ""; //收货人电话 + $def_url .= ""; //收货人邮编 + $def_url .= ""; //订单总金额 + $def_url .= ""; //订单产生日期 + $def_url .= ""; //配货状态 + $def_url .= ""; //订货人姓名 + $def_url .= ""; //币种,0为人民币,1为美元 + $def_url .= ""; //支付动作完成后返回到该url,支付结果以GET方式发送 + $def_url .= ""; //订单数字指纹 + $def_url .= ""; + + $def_url .= '
    '; + + //易支付英文通道 + $def_url = "
    "; + $def_url .= ""; //商户编号 + $def_url .= ""; //订单编号 + $def_url .= ""; //收货人姓名 + $def_url .= ""; //收货人地址 + $def_url .= ""; //收货人电话 + $def_url .= ""; //收货人邮编 + $def_url .= ""; //订单总金额 + $def_url .= ""; //订单产生日期 + $def_url .= ""; //配货状态 + $def_url .= ""; //订货人姓名 + $def_url .= ""; //币种,0为人民币,1为美元 + $def_url .= ""; //支付动作完成后返回到该url,支付结果以GET方式发送 + $def_url .= ""; //订单数字指纹 + $def_url .= ""; + + $def_url .= '
    ';*/ + + return $def_url; + } + + /** + * 响应操作 + */ + + function respond() + { + $payment = get_payment(basename(__FILE__, '.php')); + $v_tempdate = explode('-', $_REQUEST['v_oid']); + + //接受返回数据验证开始 + //v_md5info验证 + $md5info_paramet = $_REQUEST['v_oid'].$_REQUEST['v_pstatus'].$_REQUEST['v_pstring'].$_REQUEST['v_pmode']; + $md5info_tem = $this->hmac_md5($payment['cappay_key'],$md5info_paramet); + + //v_md5money验证 + $md5money_paramet = $_REQUEST['v_amount'].$_REQUEST['v_moneytype']; + $md5money_tem = $this->hmac_md5($payment['cappay_key'],$md5money_paramet); + if ($md5info_tem == $_REQUEST['v_md5info'] && $md5money_tem == $_REQUEST['v_md5money']) + { + //改变订单状态 + order_paid($v_tempdate[2]); + + return true; + } + else + { + return false; + } + + } + function hmac_md5($key, $data) + { + if (extension_loaded('mhash')) + { + return bin2hex(mhash(MHASH_MD5, $data, $key)); + } + + // RFC 2104 HMAC implementation for php. Hacked by Lance Rushing + $b = 64; + if (strlen($key) > $b) + { + $key = pack('H*', md5($key)); + } + $key = str_pad($key, $b, chr(0x00)); + $ipad = str_pad('', $b, chr(0x36)); + $opad = str_pad('', $b, chr(0x5c)); + + $k_ipad = $key ^ $ipad; + $k_opad = $key ^ $opad; + + return md5($k_opad . pack('H*', md5($k_ipad . $data))); + } + +} + +?> \ No newline at end of file diff --git a/includes/modules/payment/chinabank.php b/includes/modules/payment/chinabank.php new file mode 100644 index 0000000..f27960d --- /dev/null +++ b/includes/modules/payment/chinabank.php @@ -0,0 +1,181 @@ + 'chinabank_account', 'type' => 'text', 'value' => ''), + array('name' => 'chinabank_key', 'type' => 'text', 'value' => ''), + ); + + return; +} + +/** + * 类 + */ +class chinabank +{ + /** + * 构造函数 + * + * @access public + * @param + * + * @return void + */ + function chinabank() + { + } + + function __construct() + { + $this->chinabank(); + } + + /** + * 生成支付代码 + * @param array $order 订单信息 + * @param array $payment 支付方式信息 + */ + function get_code($order, $payment) + { + $data_vid = trim($payment['chinabank_account']); + $data_orderid = $order['order_sn']; + $data_vamount = $order['order_amount']; + $data_vmoneytype = 'CNY'; + $data_vpaykey = trim($payment['chinabank_key']); + $data_vreturnurl = return_url(basename(__FILE__, '.php')); + if (empty($order['order_id'])) + { + $remark1 = "voucher"; //商户需要在支付结果通知中转发的商户参数二 + } + else + { + $remark1 = ''; + } + + $MD5KEY =$data_vamount.$data_vmoneytype.$data_orderid.$data_vid.$data_vreturnurl.$data_vpaykey; + $MD5KEY = strtoupper(md5($MD5KEY)); + + $def_url = '
    '; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= "
    "; + + return $def_url; + } + + /** + * 响应操作 + */ + function respond() + { + $payment = get_payment(basename(__FILE__, '.php')); + + $v_oid = trim($_POST['v_oid']); + $v_pmode = trim($_POST['v_pmode']); + $v_pstatus = trim($_POST['v_pstatus']); + $v_pstring = trim($_POST['v_pstring']); + $v_amount = trim($_POST['v_amount']); + $v_moneytype = trim($_POST['v_moneytype']); + $remark1 = trim($_POST['remark1' ]); + $remark2 = trim($_POST['remark2' ]); + $v_md5str = trim($_POST['v_md5str' ]); + + /** + * 重新计算md5的值 + */ + $key = $payment['chinabank_key']; + + $md5string=strtoupper(md5($v_oid.$v_pstatus.$v_amount.$v_moneytype.$key)); + + /* 检查秘钥是否正确 */ + if ($v_md5str==$md5string) + { + //验证通过后,将订单sn转换为ID 来操作ec订单表 + if ($remark1 == 'voucher') + { + $v_oid = get_order_id_by_sn($v_oid, "true"); + } + else + { + $v_oid = get_order_id_by_sn($v_oid); + } + + if ($v_pstatus == '20') + { + /* 改变订单状态 */ + order_paid($v_oid); + + return true; + } + } + else + { + return false; + } + } +} + +?> \ No newline at end of file diff --git a/includes/modules/payment/cncard.php b/includes/modules/payment/cncard.php new file mode 100644 index 0000000..e0fa1d0 --- /dev/null +++ b/includes/modules/payment/cncard.php @@ -0,0 +1,283 @@ + 'c_mid', 'type' => 'text', 'value' => ''), + array('name' => 'c_pass', 'type' => 'text', 'value' => ''), + array('name' => 'c_memo1', 'type' => 'text', 'value' => 'ecshop'), + array('name' => 'c_moneytype', 'type' => 'select', 'value' => '0'), + array('name' => 'c_language', 'type' => 'select', 'value' => '0'), + array('name' => 'c_paygate', 'type' => 'select', 'value' => '') + ); + + return; +} + +class cncard +{ + /** + * 构造函数 + * + * @access public + * @param + * + * @return void + */ + function cncard() + { + } + + function __construct() + { + $this->cncard(); + } + + /** + * 生成支付代码 + * @param array $order 订单信息 + * @param array $payment 支付方式信息 + */ + function get_code($order, $payment) + { + $c_mid = trim($payment['c_mid']); //商户编号,在申请商户成功后即可获得,可以在申请商户成功的邮件中获取该编号 + $c_order = $order['order_sn']; //商户网站依照订单号规则生成的订单号,不能重复 + $c_name = ""; //商户订单中的收货人姓名 + $c_address = ""; //商户订单中的收货人地址 + $c_tel = ""; //商户订单中的收货人电话 + $c_post = ""; //商户订单中的收货人邮编 + $c_email = ""; //商户订单中的收货人Email + $c_orderamount = $order['order_amount']; //商户订单总金额 + if (!empty($order['add_time'])) + { + $c_ymd = local_date('Ymd', $order['add_time']); + } + else + { + $c_ymd = local_date('Ymd', gmtime()); + } + //$c_ymd = substr($order['order_sn'], 0, 8); //商户订单的产生日期,格式为"yyyymmdd",如20050102 + $c_moneytype= $payment['c_moneytype']; //支付币种,0为人民币 + $c_retflag = "1"; //商户订单支付成功后是否需要返回商户指定的文件,0:不用返回 1:需要返回 + $c_paygate = empty($payment['c_paygate']) ? '' : trim($payment['c_paygate']); //如果在商户网站选择银行则设置该值,具体值可参见《云网支付@网技术接口手册》附录一;如果来云网支付@网选择银行此项为空值。 + $c_returl = return_url(basename(__FILE__, '.php')); //如果c_retflag为1时,该地址代表商户接收云网支付结果通知的页面,请提交完整文件名(对应范例文件:GetPayNotify.php) + $c_memo1 = abs(crc32(trim($payment['c_memo1']))); //商户需要在支付结果通知中转发的商户参数一 + if (empty($order['order_id'])) + { + $c_memo2 = "voucher"; //商户需要在支付结果通知中转发的商户参数二 + } + else + { + $c_memo2 = ''; + } + $c_pass = trim($payment['c_pass']); //支付密钥,请登录商户管理后台,在帐户信息-基本信息-安全信息中的支付密钥项 + $notifytype = "0"; //0普通通知方式/1服务器通知方式,空值为普通通知方式 + $c_language = trim($payment['c_language']); //对启用了国际卡支付时,可使用该值定义消费者在银行支付时的页面语种,值为:0银行页面显示为中文/1银行页面显示为英文 + + $srcStr = $c_mid . $c_order . $c_orderamount . $c_ymd . $c_moneytype . $c_retflag . $c_returl . $c_paygate . $c_memo1 . $c_memo2 . $notifytype . $c_language . $c_pass; //说明:如果您想指定支付方式(c_paygate)的值时,需要先让用户选择支付方式,然后再根据用户选择的结果在这里进行MD5加密,也就是说,此时,本页面应该拆分为两个页面,分为两个步骤完成。 + + //--对订单信息进行MD5加密 + //商户对订单信息进行MD5签名后的字符串 + $c_signstr = md5($srcStr); + + $def_url = '
    '. + "". + "". + "". + "". + "". + "". + "". + "". + "". + "". + "". + "". + "". + "". + "". + "". + "". + "". + "". + "
    "; + + return $def_url; + } + + /** + * 响应操作 + */ + + function respond() + { + $payment = get_payment($_GET['code']); + + //--获取云网支付网关向商户发送的支付通知信息(以下简称为通知信息) + $c_mid = $_REQUEST['c_mid']; //商户编号,在申请商户成功后即可获得,可以在申请商户成功的邮件中获取该编号 + $c_order = $_REQUEST['c_order']; //商户提供的订单号 + $c_orderamount = $_REQUEST['c_orderamount']; //商户提供的订单总金额,以元为单位,小数点后保留两位,如:13.05 + $c_ymd = $_REQUEST['c_ymd']; //商户传输过来的订单产生日期,格式为"yyyymmdd",如20050102 + $c_transnum = $_REQUEST['c_transnum']; //云网支付网关提供的该笔订单的交易流水号,供日后查询、核对使用; + $c_succmark = $_REQUEST['c_succmark']; //交易成功标志,Y-成功 N-失败 + $c_moneytype = $_REQUEST['c_moneytype']; //支付币种,0为人民币 + $c_cause = $_REQUEST['c_cause']; //如果订单支付失败,则该值代表失败原因 + $c_memo1 = $_REQUEST['c_memo1']; //商户提供的需要在支付结果通知中转发的商户参数一 + $c_memo2 = $_REQUEST['c_memo2']; //商户提供的需要在支付结果通知中转发的商户参数二 + $c_signstr = $_REQUEST['c_signstr']; //云网支付网关对已上信息进行MD5加密后的字符串 + + //--校验信息完整性--- + if($c_mid=="" || $c_order=="" || $c_orderamount=="" || $c_ymd=="" || $c_moneytype=="" || $c_transnum=="" || $c_succmark=="" || $c_signstr=="") + { + //echo "支付信息有误!"; + + return false; + } + + //--将获得的通知信息拼成字符串,作为准备进行MD5加密的源串,需要注意的是,在拼串时,先后顺序不能改变 + //商户的支付密钥,登录商户管理后台(https://www.cncard.net/admin/),在管理首页可找到该值 + $c_pass = trim($payment['c_pass']); + + $srcStr = $c_mid . $c_order . $c_orderamount . $c_ymd . $c_transnum . $c_succmark . $c_moneytype . $c_memo1 . $c_memo2 . $c_pass; + + //--对支付通知信息进行MD5加密 + $r_signstr = md5($srcStr); + + //--校验商户网站对通知信息的MD5加密的结果和云网支付网关提供的MD5加密结果是否一致 + if($r_signstr!=$c_signstr) + { + //echo "签名验证失败"; + + return false; + } + //验证通过后,将订单sn转换为ID 来操作ec订单表 + if ($c_memo2 == 'voucher') + { + $c_order = get_order_id_by_sn($c_order, "true"); + } + else + { + $c_order = get_order_id_by_sn($c_order); + } + + /* 检查支付的金额是否相符 */ + if (!check_money($c_order, $c_orderamount)) + { + //echo "订单金额不对"; + + return false; + } + + //--校验商户编号 + $MerchantID= trim($payment['c_mid']); //商户自己的编号 + if($MerchantID!=$c_mid){ + //echo "提交的商户编号有误"; + + return false; + } + + if ($c_memo1 != abs(crc32($payment['c_memo1']))) + { + //echo "个性签名不一致"; + + //return false; + } + + +// $r_orderamount = $row["订单金额"]; //商户从自己订单系统获取该值 +// if($r_orderamount!=$c_orderamount){ +// echo "支付金额有误"; +// exit; +// } + + //--校验商户订单系统中记录的订单生成日期和云网支付网关通知信息中的订单生成日期是否一致 +// $r_ymd = $row["订单生成日期"]; //商户从自己订单系统获取该值 +// if($r_ymd!=$c_ymd){ +// echo "订单时间有误"; +// exit; +// } + + + + //--校验返回的支付结果的格式是否正确 + if($c_succmark!="Y" && $c_succmark!="N") + { + //echo "参数提交有误"; + + return false; + } + + //--根据返回的支付结果,商户进行自己的发货等操作 + if($c_succmark="Y") + { + //根据商户自己商务规则,进行发货等系列操作 + + /* 改变订单状态 */ + order_paid($c_order); + + return true; + } + else + { + //echo $c_cause; + + return false; + } + } +} + +?> \ No newline at end of file diff --git a/includes/modules/payment/cod.php b/includes/modules/payment/cod.php new file mode 100644 index 0000000..b144b1f --- /dev/null +++ b/includes/modules/payment/cod.php @@ -0,0 +1,104 @@ +cod(); + } + + /** + * 提交函数 + */ + function get_code() + { + return ''; + } + + /** + * 处理函数 + */ + function response() + { + return; + } +} + +?> \ No newline at end of file diff --git a/includes/modules/payment/ctopay.php b/includes/modules/payment/ctopay.php new file mode 100644 index 0000000..2861dcc --- /dev/null +++ b/includes/modules/payment/ctopay.php @@ -0,0 +1,169 @@ + 'MerNo', 'type' => 'text', 'value' => ''), + array('name' => 'MD5key', 'type' => 'text', 'value' => ''), + array('name' => 'Currency', 'type' => 'select', 'value' => ''), + array('name' => 'Language', 'type' => 'select', 'value' => ''), + ); + + return; +} + +/** + * 类 + */ +class ctopay +{ + + /** + * 构造函数 + * + * @access public + * @param + * + * @return void + */ + function ctopay() + { + } + + function __construct() + { + $this->ctopay(); + } + + /** + * 生成支付代码 + * @param array $order 订单信息 + * @param array $payment 支付方式信息 + */ + function get_code($order, $payment) + { + $MD5key = $payment['MD5key']; //MD5私钥 + $MerNo = $payment['MerNo']; //商户号 + $BillNo = $order['log_id']; //订单号 + $Currency = $payment['Currency']; //币种 + $Amount = $order['order_amount']; //金额 + $DispAmount= 0; //外币金额 + $Language = $payment['Language']; //语言 + $ReturnURL = return_url(basename(__FILE__, '.php')); //返回地址 + $Remark = "From ECShop order sn : " . $order['order_sn']; //备注 + + $md5src = $MerNo.$BillNo.$Currency.$Amount.$Language.$ReturnURL.$MD5key; //校验源字符串 + $MD5info = strtoupper(md5($md5src)); //MD5检验结果 + + $button = '
    '. + " ". + " ". + " ". + " ". + " ". + " ". + " ". + " ". + " ". + " ". + "
    "; + + return $button; + } + + /** + * 响应操作 + */ + function respond() + { + $payment = get_payment($_GET['code']); + + $BillNo = $_REQUEST["BillNo"]; //订单号 + $Currency = $_REQUEST["Currency"]; //币种 + $BankID = $_REQUEST["BankID"]; //银行ID号 + $Amount = $_REQUEST["Amount"]; //金额 + $Succeed = $_REQUEST["Succeed"]; //支付状态 + $TradeNo = $_REQUEST["TradeNo"]; //支付平台流水号 + $Result = $_REQUEST["Result"]; //支付结果 + $MD5info = $_REQUEST["MD5info"]; //取得的MD5校验信息 + $Remark = $_REQUEST["Remark"]; //备注 + //$Drawee = $_REQUEST["Drawee"]; //支付人名称 + + + $MD5key = $payment['MD5key']; //MD5私钥 + $md5src = $BillNo.$Currency.$Amount.$Succeed.$MD5key; //校验源字符串 + $md5sign = strtoupper(md5($md5src)); //MD5检验结果 + + /* 验证 */ + if ($MD5info!= $md5sign) + { + return false; + } + + if ($Succeed == 1) + { + /* 改变订单状态 */ + order_paid($BillNo, PS_PAYED); + + return true; + } + else + { + return false; + } + } +} + +?> \ No newline at end of file diff --git a/includes/modules/payment/express.php b/includes/modules/payment/express.php new file mode 100644 index 0000000..0ae3407 --- /dev/null +++ b/includes/modules/payment/express.php @@ -0,0 +1,171 @@ + + * @version: v1.0 + * --------------------------------------------- + */ + +if (!defined('IN_ECS')) +{ + die('Hacking attempt'); +} + +$payment_lang = ROOT_PATH . 'languages/' .$GLOBALS['_CFG']['lang']. '/payment/express.php'; +if (file_exists($payment_lang)) +{ + global $_LANG; + + include_once($payment_lang); +} + +/* 模块的基本信息 */ +if (isset($set_modules) && $set_modules == TRUE) +{ + $i = isset($modules) ? count($modules) : 0; + + /* 代码 */ + $modules[$i]['code'] = basename(__FILE__, '.php'); + + /* 描述对应的语言项 */ + $modules[$i]['desc'] = 'express_desc'; + + /* 是否支持货到付款 */ + $modules[$i]['is_cod'] = '0'; + + /* 是否支持在线支付 */ + $modules[$i]['is_online'] = '1'; + + /* 作者 */ + $modules[$i]['author'] = 'ECSHOP TEAM'; + + /* 网址 */ + $modules[$i]['website'] = 'http://express.ips.com.cn/'; + + /* 版本号 */ + $modules[$i]['version'] = '1.0.0'; + + /* 配置信息 */ + $modules[$i]['config'] = array( + array('name' => 'ips_account', 'type' => 'text', 'value' => ''), + array('name' => 'ips_key', 'type' => 'text', 'value' => '') + ); + + return; +} + +class express +{ + /** + * 构造函数 + * + * @access public + * @param + * + * @return void + */ + function express() + { + + } + + function __construct() + { + $this->express(); + } + + /** + * 生成支付代码 + * @param array $order 订单信息 + * @param array $payment 支付方式信息 + */ + + function get_code($order, $payment) + { + $mer_code = $payment['ips_account']; + $billno = $order['log_id']; + $amount = sprintf("%0.02f", $order['order_amount']); + $strcert = $payment['ips_key']; + + $remark = ''; + $signmd5 = MD5($mer_code . $billno . $amount . $remark . $strcert); + + $def_url = '
    '; + $def_url .= "\n"; //商户帐号 + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= $GLOBALS['_LANG']['please_select_bank'] . ':'; + $def_url .= "

    "; + return $def_url; + } + + function respond() + { + $payment = get_payment('express'); + $merchant = $payment['ips_account']; // 商户号 + $amount = $_REQUEST['Amount']; //金额 + $billno = $_REQUEST['BillNo']; //订单号 + $success = $_REQUEST['Success']; //是否成功Y/N + $remark = $_REQUEST['Remark']; //附加信息 + $sign = $_REQUEST['Sign']; + + $strcert = $payment['ips_key']; + $signmd5 = md5($merchant . $billno . $amount . $remark . $success . $payment['ips_key']); + if ($sign != $signmd5) + { + echo $billno; + return false; + } + + if ($success != 'Y') + { + return false; + } + else + { + if (!check_money($billno, $amount)) + { + return false; + } + } + $fp = @fopen("http://express.ips.com.cn/merchant/confirm.asp?Merchant=".$merchant ."&BillNo=".$billno."&Amount=".$amount."&Success=".$success."&Remark=".$remark. "&sign=".$sign, 'rb'); + if (!empty($fp)) + { + fclose($fp); + } + order_paid($bid, PS_PAYED); + return true; + } +} + +?> \ No newline at end of file diff --git a/includes/modules/payment/ips.php b/includes/modules/payment/ips.php new file mode 100644 index 0000000..43d4546 --- /dev/null +++ b/includes/modules/payment/ips.php @@ -0,0 +1,165 @@ + + * @version: v1.0 + * --------------------------------------------- + */ + +if (!defined('IN_ECS')) +{ + die('Hacking attempt'); +} + +$payment_lang = ROOT_PATH . 'languages/' .$GLOBALS['_CFG']['lang']. '/payment/ips.php'; +if (file_exists($payment_lang)) +{ + global $_LANG; + + include_once($payment_lang); +} + +/* 模块的基本信息 */ +if (isset($set_modules) && $set_modules == TRUE) +{ + $i = isset($modules) ? count($modules) : 0; + + /* 代码 */ + $modules[$i]['code'] = basename(__FILE__, '.php'); + + /* 描述对应的语言项 */ + $modules[$i]['desc'] = 'ips_desc'; + + /* 是否支持货到付款 */ + $modules[$i]['is_cod'] = '0'; + + /* 是否支持在线支付 */ + $modules[$i]['is_online'] = '1'; + + /* 作者 */ + $modules[$i]['author'] = 'ECSHOP TEAM'; + + /* 网址 */ + $modules[$i]['website'] = 'http://www.ips.com.cn'; + + /* 版本号 */ + $modules[$i]['version'] = '1.0.0'; + + /* 配置信息 */ + $modules[$i]['config'] = array( + array('name' => 'ips_account', 'type' => 'text', 'value' => ''), + array('name' => 'ips_key', 'type' => 'text', 'value' => ''), + array('name' => 'ips_currency', 'type' => 'select', 'value' => '01'), + array('name' => 'ips_lang', 'type' => 'select', 'value' => 'GB') + ); + + return; +} + +class ips +{ + /** + * 构造函数 + * + * @access public + * @param + * + * @return void + */ + function ips() + { + + } + + function __construct() + { + $this->ips(); + } + + /** + * 生成支付代码 + * @param array $order 订单信息 + * @param array $payment 支付方式信息 + */ + + function get_code($order, $payment) + { + $billstr = date('His', time()); + $datestr = date('Ymd', time()); + $mer_code = $payment['ips_account']; + $billno = str_pad($order['log_id'], 10, '0', STR_PAD_LEFT) . $billstr; + $amount = sprintf("%0.02f", $order['order_amount']); + $strcert = $payment['ips_key']; + $strcontent = $billno . $amount . $datestr . 'RMB' . $strcert; // 签名验证串 // + $signmd5 = MD5($strcontent); + + $def_url = '
    '; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= ""; + $def_url .= "

    "; + + return $def_url; + } + + function respond() + { + $payment = get_payment($_GET['code']); + $billno = $_GET['billno']; + $amount = $_GET['amount']; + $mydate = $_GET['date']; + $succ = $_GET['succ']; + $msg = $_GET['msg']; + $ipsbillno = $_GET['ipsbillno']; + $retEncodeType = $_GET['retencodetype']; + $currency_type = $_GET['Currency_type']; + $signature = $_GET['signature']; + $order_sn = intval(substr($billno, 0, 10)); + + if ($succ == 'Y') + { + $content = $billno . $amount . $mydate . $succ . $ipsbillno . $currency_type; + $cert = $payment['ips_key']; + $signature_1ocal = md5($content . $cert); + + if ($signature_1ocal == $signature) + { + if (!check_money($order_sn, $amount)) + { + return false; + } + order_paid($order_sn); + + return true; + } + else + { + return false; + } + } + else + { + return false; + } + } +} + +?> \ No newline at end of file diff --git a/includes/modules/payment/kuaiqian.php b/includes/modules/payment/kuaiqian.php new file mode 100644 index 0000000..36cc869 --- /dev/null +++ b/includes/modules/payment/kuaiqian.php @@ -0,0 +1,287 @@ + 'kq_account', 'type' => 'text', 'value' => ''), + array('name' => 'kq_key', 'type' => 'text', 'value' => ''), + ); + + return; + +} + +class kuaiqian +{ + /** + * 构造函数 + * + * @access public + * @param + * + * @return void + */ + + function kuaiqian() + { + } + + function __construct() + { + $this->kuaiqian(); + } + + /** + * 生成支付代码 + * @param array $order 订单信息 + * @param array $payment 支付方式信息 + */ + function get_code($order, $payment) + { + $merchant_acctid = trim($payment['kq_account']); //人民币账号 不可空 + $key = trim($payment['kq_key']); + $input_charset = 1; //字符集 默认1=utf-8 + $page_url = return_url(basename(__FILE__, '.php')); + $bg_url = ''; + $version = 'v2.0'; + $language = 1; + $sign_type = 1; //签名类型 不可空 固定值 1:md5 + $payer_name = ''; + $payer_contact_type = ''; + $payer_contact = ''; + $order_id = $order['order_sn']; //商户订单号 不可空 + $order_amount = $order['order_amount'] * 100; //商户订单金额 不可空 + $order_time = local_date('YmdHis', $order['add_time']); //商户订单提交时间 不可空 14位 + $product_name = ''; + $product_num = ''; + $product_id = ''; + $product_desc = ''; + $ext1 = $order['log_id']; + $ext2 = ''; + $pay_type = '00'; //支付方式 不可空 + $bank_id = ''; + $redo_flag = '0'; + $pid = ''; + + /* 生成加密签名串 请务必按照如下顺序和规则组成加密串!*/ + $signmsgval = ''; + $signmsgval = $this->append_param($signmsgval, "inputCharset", $input_charset); + $signmsgval = $this->append_param($signmsgval, "pageUrl", $page_url); + $signmsgval = $this->append_param($signmsgval, "bgUrl", $bg_url); + $signmsgval = $this->append_param($signmsgval, "version", $version); + $signmsgval = $this->append_param($signmsgval, "language", $language); + $signmsgval = $this->append_param($signmsgval, "signType", $sign_type); + $signmsgval = $this->append_param($signmsgval, "merchantAcctId", $merchant_acctid); + $signmsgval = $this->append_param($signmsgval, "payerName", $payer_name); + $signmsgval = $this->append_param($signmsgval, "payerContactType", $payer_contact_type); + $signmsgval = $this->append_param($signmsgval, "payerContact", $payer_contact); + $signmsgval = $this->append_param($signmsgval, "orderId", $order_id); + $signmsgval = $this->append_param($signmsgval, "orderAmount", $order_amount); + $signmsgval = $this->append_param($signmsgval, "orderTime", $order_time); + $signmsgval = $this->append_param($signmsgval, "productName", $product_name); + $signmsgval = $this->append_param($signmsgval, "productNum", $product_num); + $signmsgval = $this->append_param($signmsgval, "productId", $product_id); + $signmsgval = $this->append_param($signmsgval, "productDesc", $product_desc); + $signmsgval = $this->append_param($signmsgval, "ext1", $ext1); + $signmsgval = $this->append_param($signmsgval, "ext2", $ext2); + $signmsgval = $this->append_param($signmsgval, "payType", $pay_type); + $signmsgval = $this->append_param($signmsgval, "bankId", $bank_id); + $signmsgval = $this->append_param($signmsgval, "redoFlag", $redo_flag); + $signmsgval = $this->append_param($signmsgval, "pid", $pid); + $signmsgval = $this->append_param($signmsgval, "key", $key); + $signmsg = strtoupper(md5($signmsgval)); //签名字符串 不可空 + + + $def_url = '
    '; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= "

    "; + + return $def_url; + } + + /** + * 响应操作 + */ + function respond() + { + $payment = get_payment($_GET['code']); + $merchant_acctid = $payment['kq_account']; //人民币账号 不可空 + $key = $payment['kq_key']; + $get_merchant_acctid = trim($_REQUEST['merchantAcctId']); + $pay_result = trim($_REQUEST['payResult']); + $version = trim($_REQUEST['version']); + $language = trim($_REQUEST['language']); + $sign_type = trim($_REQUEST['signType']); + $pay_type = trim($_REQUEST['payType']); + $bank_id = trim($_REQUEST['bankId']); + $order_id = trim($_REQUEST['orderId']); + $order_time = trim($_REQUEST['orderTime']); + $order_amount = trim($_REQUEST['orderAmount']); + $deal_id = trim($_REQUEST['dealId']); + $bank_deal_id = trim($_REQUEST['bankDealId']); + $deal_time = trim($_REQUEST['dealTime']); + $pay_amount = trim($_REQUEST['payAmount']); + $fee = trim($_REQUEST['fee']); + $ext1 = trim($_REQUEST['ext1']); + $ext2 = trim($_REQUEST['ext2']); + $err_code = trim($_REQUEST['errCode']); + $sign_msg = trim($_REQUEST['signMsg']); + + //生成加密串。必须保持如下顺序。 + $merchant_signmsgval = ''; + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"merchantAcctId",$merchant_acctid); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"version",$version); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"language",$language); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"signType",$sign_type); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"payType",$pay_type); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"bankId",$bank_id); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"orderId",$order_id); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"orderTime",$order_time); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"orderAmount",$order_amount); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"dealId",$deal_id); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"bankDealId",$bank_deal_id); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"dealTime",$deal_time); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"payAmount",$pay_amount); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"fee",$fee); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"ext1",$ext1); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"ext2",$ext2); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"payResult",$pay_result); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"errCode",$err_code); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"key",$key); + $merchant_signmsg = md5($merchant_signmsgval); + + //首先对获得的商户号进行比对 + if ($get_merchant_acctid != $merchant_acctid) + { + //商户号错误 + return false; + } + + if (strtoupper($sign_msg) == strtoupper($merchant_signmsg)) + { + if ($pay_result == 10 || $pay_result == 00) + { + order_paid($ext1); + + return true; + } + else + { + //'支付结果失败'; + return false; + } + + } + else + { + //'密钥校对错误'; + return false; + } + } + + /** + * 将变量值不为空的参数组成字符串 + * @param string $strs 参数字符串 + * @param string $key 参数键名 + * @param string $val 参数键对应值 + */ + function append_param($strs,$key,$val) + { + if($strs != "") + { + if($key != '' && $val != '') + { + $strs .= '&' . $key . '=' . $val; + } + } + else + { + if($val != '') + { + $strs = $key . '=' . $val; + } + } + return $strs; + } + +} + +?> \ No newline at end of file diff --git a/includes/modules/payment/kuaiqian_abc.php b/includes/modules/payment/kuaiqian_abc.php new file mode 100644 index 0000000..16312ca --- /dev/null +++ b/includes/modules/payment/kuaiqian_abc.php @@ -0,0 +1,287 @@ + 'kq_account', 'type' => 'text', 'value' => ''), + array('name' => 'kq_key', 'type' => 'text', 'value' => ''), + ); + + return; + +} + +class kuaiqian_abc +{ + /** + * 构造函数 + * + * @access public + * @param + * + * @return void + */ + + function kuaiqian_abc() + { + } + + function __construct() + { + $this->kuaiqian_abc(); + } + + /** + * 生成支付代码 + * @param array $order 订单信息 + * @param array $payment 支付方式信息 + */ + function get_code($order, $payment) + { + $merchant_acctid = trim($payment['kq_account']); //人民币账号 不可空 + $key = trim($payment['kq_key']); + $input_charset = 1; //字符集 默认1=utf-8 + $page_url = return_url(basename(__FILE__, '.php')); + $bg_url = ''; + $version = 'v2.0'; + $language = 1; + $sign_type = 1; //签名类型 不可空 固定值 1:md5 + $payer_name = ''; + $payer_contact_type = ''; + $payer_contact = ''; + $order_id = $order['order_sn']; //商户订单号 不可空 + $order_amount = $order['order_amount'] * 100; //商户订单金额 不可空 + $order_time = local_date('YmdHis', $order['add_time']); //商户订单提交时间 不可空 14位 + $product_name = ''; + $product_num = ''; + $product_id = ''; + $product_desc = ''; + $ext1 = $order['log_id']; + $ext2 = ''; + $pay_type = '10'; //支付方式 不可空 + $bank_id = 'ABC'; + $redo_flag = '0'; + $pid = ''; + + /* 生成加密签名串 请务必按照如下顺序和规则组成加密串!*/ + $signmsgval = ''; + $signmsgval = $this->append_param($signmsgval, "inputCharset", $input_charset); + $signmsgval = $this->append_param($signmsgval, "pageUrl", $page_url); + $signmsgval = $this->append_param($signmsgval, "bgUrl", $bg_url); + $signmsgval = $this->append_param($signmsgval, "version", $version); + $signmsgval = $this->append_param($signmsgval, "language", $language); + $signmsgval = $this->append_param($signmsgval, "signType", $sign_type); + $signmsgval = $this->append_param($signmsgval, "merchantAcctId", $merchant_acctid); + $signmsgval = $this->append_param($signmsgval, "payerName", $payer_name); + $signmsgval = $this->append_param($signmsgval, "payerContactType", $payer_contact_type); + $signmsgval = $this->append_param($signmsgval, "payerContact", $payer_contact); + $signmsgval = $this->append_param($signmsgval, "orderId", $order_id); + $signmsgval = $this->append_param($signmsgval, "orderAmount", $order_amount); + $signmsgval = $this->append_param($signmsgval, "orderTime", $order_time); + $signmsgval = $this->append_param($signmsgval, "productName", $product_name); + $signmsgval = $this->append_param($signmsgval, "productNum", $product_num); + $signmsgval = $this->append_param($signmsgval, "productId", $product_id); + $signmsgval = $this->append_param($signmsgval, "productDesc", $product_desc); + $signmsgval = $this->append_param($signmsgval, "ext1", $ext1); + $signmsgval = $this->append_param($signmsgval, "ext2", $ext2); + $signmsgval = $this->append_param($signmsgval, "payType", $pay_type); + $signmsgval = $this->append_param($signmsgval, "bankId", $bank_id); + $signmsgval = $this->append_param($signmsgval, "redoFlag", $redo_flag); + $signmsgval = $this->append_param($signmsgval, "pid", $pid); + $signmsgval = $this->append_param($signmsgval, "key", $key); + $signmsg = strtoupper(md5($signmsgval)); //签名字符串 不可空 + + + $def_url = '
    '; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= "

    "; + + return $def_url; + } + + /** + * 响应操作 + */ + function respond() + { + $payment = get_payment($_GET['code']); + $merchant_acctid = $payment['kq_account']; //人民币账号 不可空 + $key = $payment['kq_key']; + $get_merchant_acctid = trim($_REQUEST['merchantAcctId']); + $pay_result = trim($_REQUEST['payResult']); + $version = trim($_REQUEST['version']); + $language = trim($_REQUEST['language']); + $sign_type = trim($_REQUEST['signType']); + $pay_type = trim($_REQUEST['payType']); + $bank_id = trim($_REQUEST['bankId']); + $order_id = trim($_REQUEST['orderId']); + $order_time = trim($_REQUEST['orderTime']); + $order_amount = trim($_REQUEST['orderAmount']); + $deal_id = trim($_REQUEST['dealId']); + $bank_deal_id = trim($_REQUEST['bankDealId']); + $deal_time = trim($_REQUEST['dealTime']); + $pay_amount = trim($_REQUEST['payAmount']); + $fee = trim($_REQUEST['fee']); + $ext1 = trim($_REQUEST['ext1']); + $ext2 = trim($_REQUEST['ext2']); + $err_code = trim($_REQUEST['errCode']); + $sign_msg = trim($_REQUEST['signMsg']); + + //生成加密串。必须保持如下顺序。 + $merchant_signmsgval = ''; + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"merchantAcctId",$merchant_acctid); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"version",$version); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"language",$language); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"signType",$sign_type); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"payType",$pay_type); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"bankId",$bank_id); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"orderId",$order_id); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"orderTime",$order_time); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"orderAmount",$order_amount); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"dealId",$deal_id); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"bankDealId",$bank_deal_id); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"dealTime",$deal_time); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"payAmount",$pay_amount); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"fee",$fee); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"ext1",$ext1); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"ext2",$ext2); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"payResult",$pay_result); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"errCode",$err_code); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"key",$key); + $merchant_signmsg = md5($merchant_signmsgval); + + //首先对获得的商户号进行比对 + if ($get_merchant_acctid != $merchant_acctid) + { + //商户号错误 + return false; + } + + if (strtoupper($sign_msg) == strtoupper($merchant_signmsg)) + { + if ($pay_result == 10 || $pay_result == 00) + { + order_paid($ext1); + + return true; + } + else + { + //'支付结果失败'; + return false; + } + + } + else + { + //'密钥校对错误'; + return false; + } + } + + /** + * 将变量值不为空的参数组成字符串 + * @param string $strs 参数字符串 + * @param string $key 参数键名 + * @param string $val 参数键对应值 + */ + function append_param($strs,$key,$val) + { + if($strs != "") + { + if($key != '' && $val != '') + { + $strs .= '&' . $key . '=' . $val; + } + } + else + { + if($val != '') + { + $strs = $key . '=' . $val; + } + } + return $strs; + } + +} + +?> \ No newline at end of file diff --git a/includes/modules/payment/kuaiqian_bcom.php b/includes/modules/payment/kuaiqian_bcom.php new file mode 100644 index 0000000..c03b3f2 --- /dev/null +++ b/includes/modules/payment/kuaiqian_bcom.php @@ -0,0 +1,287 @@ + 'kq_account', 'type' => 'text', 'value' => ''), + array('name' => 'kq_key', 'type' => 'text', 'value' => ''), + ); + + return; + +} + +class kuaiqian_bcom +{ + /** + * 构造函数 + * + * @access public + * @param + * + * @return void + */ + + function kuaiqian_bcom() + { + } + + function __construct() + { + $this->kuaiqian_bcom(); + } + + /** + * 生成支付代码 + * @param array $order 订单信息 + * @param array $payment 支付方式信息 + */ + function get_code($order, $payment) + { + $merchant_acctid = trim($payment['kq_account']); //人民币账号 不可空 + $key = trim($payment['kq_key']); + $input_charset = 1; //字符集 默认1=utf-8 + $page_url = return_url(basename(__FILE__, '.php')); + $bg_url = ''; + $version = 'v2.0'; + $language = 1; + $sign_type = 1; //签名类型 不可空 固定值 1:md5 + $payer_name = ''; + $payer_contact_type = ''; + $payer_contact = ''; + $order_id = $order['order_sn']; //商户订单号 不可空 + $order_amount = $order['order_amount'] * 100; //商户订单金额 不可空 + $order_time = local_date('YmdHis', $order['add_time']); //商户订单提交时间 不可空 14位 + $product_name = ''; + $product_num = ''; + $product_id = ''; + $product_desc = ''; + $ext1 = $order['log_id']; + $ext2 = ''; + $pay_type = '10'; //支付方式 不可空 + $bank_id = 'BCOM'; + $redo_flag = '0'; + $pid = ''; + + /* 生成加密签名串 请务必按照如下顺序和规则组成加密串!*/ + $signmsgval = ''; + $signmsgval = $this->append_param($signmsgval, "inputCharset", $input_charset); + $signmsgval = $this->append_param($signmsgval, "pageUrl", $page_url); + $signmsgval = $this->append_param($signmsgval, "bgUrl", $bg_url); + $signmsgval = $this->append_param($signmsgval, "version", $version); + $signmsgval = $this->append_param($signmsgval, "language", $language); + $signmsgval = $this->append_param($signmsgval, "signType", $sign_type); + $signmsgval = $this->append_param($signmsgval, "merchantAcctId", $merchant_acctid); + $signmsgval = $this->append_param($signmsgval, "payerName", $payer_name); + $signmsgval = $this->append_param($signmsgval, "payerContactType", $payer_contact_type); + $signmsgval = $this->append_param($signmsgval, "payerContact", $payer_contact); + $signmsgval = $this->append_param($signmsgval, "orderId", $order_id); + $signmsgval = $this->append_param($signmsgval, "orderAmount", $order_amount); + $signmsgval = $this->append_param($signmsgval, "orderTime", $order_time); + $signmsgval = $this->append_param($signmsgval, "productName", $product_name); + $signmsgval = $this->append_param($signmsgval, "productNum", $product_num); + $signmsgval = $this->append_param($signmsgval, "productId", $product_id); + $signmsgval = $this->append_param($signmsgval, "productDesc", $product_desc); + $signmsgval = $this->append_param($signmsgval, "ext1", $ext1); + $signmsgval = $this->append_param($signmsgval, "ext2", $ext2); + $signmsgval = $this->append_param($signmsgval, "payType", $pay_type); + $signmsgval = $this->append_param($signmsgval, "bankId", $bank_id); + $signmsgval = $this->append_param($signmsgval, "redoFlag", $redo_flag); + $signmsgval = $this->append_param($signmsgval, "pid", $pid); + $signmsgval = $this->append_param($signmsgval, "key", $key); + $signmsg = strtoupper(md5($signmsgval)); //签名字符串 不可空 + + + $def_url = '
    '; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= "

    "; + + return $def_url; + } + + /** + * 响应操作 + */ + function respond() + { + $payment = get_payment($_GET['code']); + $merchant_acctid = $payment['kq_account']; //人民币账号 不可空 + $key = $payment['kq_key']; + $get_merchant_acctid = trim($_REQUEST['merchantAcctId']); + $pay_result = trim($_REQUEST['payResult']); + $version = trim($_REQUEST['version']); + $language = trim($_REQUEST['language']); + $sign_type = trim($_REQUEST['signType']); + $pay_type = trim($_REQUEST['payType']); + $bank_id = trim($_REQUEST['bankId']); + $order_id = trim($_REQUEST['orderId']); + $order_time = trim($_REQUEST['orderTime']); + $order_amount = trim($_REQUEST['orderAmount']); + $deal_id = trim($_REQUEST['dealId']); + $bank_deal_id = trim($_REQUEST['bankDealId']); + $deal_time = trim($_REQUEST['dealTime']); + $pay_amount = trim($_REQUEST['payAmount']); + $fee = trim($_REQUEST['fee']); + $ext1 = trim($_REQUEST['ext1']); + $ext2 = trim($_REQUEST['ext2']); + $err_code = trim($_REQUEST['errCode']); + $sign_msg = trim($_REQUEST['signMsg']); + + //生成加密串。必须保持如下顺序。 + $merchant_signmsgval = ''; + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"merchantAcctId",$merchant_acctid); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"version",$version); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"language",$language); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"signType",$sign_type); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"payType",$pay_type); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"bankId",$bank_id); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"orderId",$order_id); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"orderTime",$order_time); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"orderAmount",$order_amount); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"dealId",$deal_id); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"bankDealId",$bank_deal_id); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"dealTime",$deal_time); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"payAmount",$pay_amount); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"fee",$fee); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"ext1",$ext1); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"ext2",$ext2); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"payResult",$pay_result); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"errCode",$err_code); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"key",$key); + $merchant_signmsg = md5($merchant_signmsgval); + + //首先对获得的商户号进行比对 + if ($get_merchant_acctid != $merchant_acctid) + { + //商户号错误 + return false; + } + + if (strtoupper($sign_msg) == strtoupper($merchant_signmsg)) + { + if ($pay_result == 10 || $pay_result == 00) + { + order_paid($ext1); + + return true; + } + else + { + //'支付结果失败'; + return false; + } + + } + else + { + //'密钥校对错误'; + return false; + } + } + + /** + * 将变量值不为空的参数组成字符串 + * @param string $strs 参数字符串 + * @param string $key 参数键名 + * @param string $val 参数键对应值 + */ + function append_param($strs,$key,$val) + { + if($strs != "") + { + if($key != '' && $val != '') + { + $strs .= '&' . $key . '=' . $val; + } + } + else + { + if($val != '') + { + $strs = $key . '=' . $val; + } + } + return $strs; + } + +} + +?> \ No newline at end of file diff --git a/includes/modules/payment/kuaiqian_bob.php b/includes/modules/payment/kuaiqian_bob.php new file mode 100644 index 0000000..b851bc2 --- /dev/null +++ b/includes/modules/payment/kuaiqian_bob.php @@ -0,0 +1,287 @@ + 'kq_account', 'type' => 'text', 'value' => ''), + array('name' => 'kq_key', 'type' => 'text', 'value' => ''), + ); + + return; + +} + +class kuaiqian_bob +{ + /** + * 构造函数 + * + * @access public + * @param + * + * @return void + */ + + function kuaiqian_bob() + { + } + + function __construct() + { + $this->kuaiqian_bob(); + } + + /** + * 生成支付代码 + * @param array $order 订单信息 + * @param array $payment 支付方式信息 + */ + function get_code($order, $payment) + { + $merchant_acctid = trim($payment['kq_account']); //人民币账号 不可空 + $key = trim($payment['kq_key']); + $input_charset = 1; //字符集 默认1=utf-8 + $page_url = return_url(basename(__FILE__, '.php')); + $bg_url = ''; + $version = 'v2.0'; + $language = 1; + $sign_type = 1; //签名类型 不可空 固定值 1:md5 + $payer_name = ''; + $payer_contact_type = ''; + $payer_contact = ''; + $order_id = $order['order_sn']; //商户订单号 不可空 + $order_amount = $order['order_amount'] * 100; //商户订单金额 不可空 + $order_time = local_date('YmdHis', $order['add_time']); //商户订单提交时间 不可空 14位 + $product_name = ''; + $product_num = ''; + $product_id = ''; + $product_desc = ''; + $ext1 = $order['log_id']; + $ext2 = ''; + $pay_type = '10'; //支付方式 不可空 + $bank_id = 'BOB'; + $redo_flag = '0'; + $pid = ''; + + /* 生成加密签名串 请务必按照如下顺序和规则组成加密串!*/ + $signmsgval = ''; + $signmsgval = $this->append_param($signmsgval, "inputCharset", $input_charset); + $signmsgval = $this->append_param($signmsgval, "pageUrl", $page_url); + $signmsgval = $this->append_param($signmsgval, "bgUrl", $bg_url); + $signmsgval = $this->append_param($signmsgval, "version", $version); + $signmsgval = $this->append_param($signmsgval, "language", $language); + $signmsgval = $this->append_param($signmsgval, "signType", $sign_type); + $signmsgval = $this->append_param($signmsgval, "merchantAcctId", $merchant_acctid); + $signmsgval = $this->append_param($signmsgval, "payerName", $payer_name); + $signmsgval = $this->append_param($signmsgval, "payerContactType", $payer_contact_type); + $signmsgval = $this->append_param($signmsgval, "payerContact", $payer_contact); + $signmsgval = $this->append_param($signmsgval, "orderId", $order_id); + $signmsgval = $this->append_param($signmsgval, "orderAmount", $order_amount); + $signmsgval = $this->append_param($signmsgval, "orderTime", $order_time); + $signmsgval = $this->append_param($signmsgval, "productName", $product_name); + $signmsgval = $this->append_param($signmsgval, "productNum", $product_num); + $signmsgval = $this->append_param($signmsgval, "productId", $product_id); + $signmsgval = $this->append_param($signmsgval, "productDesc", $product_desc); + $signmsgval = $this->append_param($signmsgval, "ext1", $ext1); + $signmsgval = $this->append_param($signmsgval, "ext2", $ext2); + $signmsgval = $this->append_param($signmsgval, "payType", $pay_type); + $signmsgval = $this->append_param($signmsgval, "bankId", $bank_id); + $signmsgval = $this->append_param($signmsgval, "redoFlag", $redo_flag); + $signmsgval = $this->append_param($signmsgval, "pid", $pid); + $signmsgval = $this->append_param($signmsgval, "key", $key); + $signmsg = strtoupper(md5($signmsgval)); //签名字符串 不可空 + + + $def_url = '
    '; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= "

    "; + + return $def_url; + } + + /** + * 响应操作 + */ + function respond() + { + $payment = get_payment($_GET['code']); + $merchant_acctid = $payment['kq_account']; //人民币账号 不可空 + $key = $payment['kq_key']; + $get_merchant_acctid = trim($_REQUEST['merchantAcctId']); + $pay_result = trim($_REQUEST['payResult']); + $version = trim($_REQUEST['version']); + $language = trim($_REQUEST['language']); + $sign_type = trim($_REQUEST['signType']); + $pay_type = trim($_REQUEST['payType']); + $bank_id = trim($_REQUEST['bankId']); + $order_id = trim($_REQUEST['orderId']); + $order_time = trim($_REQUEST['orderTime']); + $order_amount = trim($_REQUEST['orderAmount']); + $deal_id = trim($_REQUEST['dealId']); + $bank_deal_id = trim($_REQUEST['bankDealId']); + $deal_time = trim($_REQUEST['dealTime']); + $pay_amount = trim($_REQUEST['payAmount']); + $fee = trim($_REQUEST['fee']); + $ext1 = trim($_REQUEST['ext1']); + $ext2 = trim($_REQUEST['ext2']); + $err_code = trim($_REQUEST['errCode']); + $sign_msg = trim($_REQUEST['signMsg']); + + //生成加密串。必须保持如下顺序。 + $merchant_signmsgval = ''; + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"merchantAcctId",$merchant_acctid); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"version",$version); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"language",$language); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"signType",$sign_type); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"payType",$pay_type); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"bankId",$bank_id); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"orderId",$order_id); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"orderTime",$order_time); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"orderAmount",$order_amount); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"dealId",$deal_id); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"bankDealId",$bank_deal_id); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"dealTime",$deal_time); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"payAmount",$pay_amount); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"fee",$fee); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"ext1",$ext1); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"ext2",$ext2); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"payResult",$pay_result); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"errCode",$err_code); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"key",$key); + $merchant_signmsg = md5($merchant_signmsgval); + + //首先对获得的商户号进行比对 + if ($get_merchant_acctid != $merchant_acctid) + { + //商户号错误 + return false; + } + + if (strtoupper($sign_msg) == strtoupper($merchant_signmsg)) + { + if ($pay_result == 10 || $pay_result == 00) + { + order_paid($ext1); + + return true; + } + else + { + //'支付结果失败'; + return false; + } + + } + else + { + //'密钥校对错误'; + return false; + } + } + + /** + * 将变量值不为空的参数组成字符串 + * @param string $strs 参数字符串 + * @param string $key 参数键名 + * @param string $val 参数键对应值 + */ + function append_param($strs,$key,$val) + { + if($strs != "") + { + if($key != '' && $val != '') + { + $strs .= '&' . $key . '=' . $val; + } + } + else + { + if($val != '') + { + $strs = $key . '=' . $val; + } + } + return $strs; + } + +} + +?> \ No newline at end of file diff --git a/includes/modules/payment/kuaiqian_boc.php b/includes/modules/payment/kuaiqian_boc.php new file mode 100644 index 0000000..60aa754 --- /dev/null +++ b/includes/modules/payment/kuaiqian_boc.php @@ -0,0 +1,287 @@ + 'kq_account', 'type' => 'text', 'value' => ''), + array('name' => 'kq_key', 'type' => 'text', 'value' => ''), + ); + + return; + +} + +class kuaiqian_boc +{ + /** + * 构造函数 + * + * @access public + * @param + * + * @return void + */ + + function kuaiqian_boc() + { + } + + function __construct() + { + $this->kuaiqian_boc(); + } + + /** + * 生成支付代码 + * @param array $order 订单信息 + * @param array $payment 支付方式信息 + */ + function get_code($order, $payment) + { + $merchant_acctid = trim($payment['kq_account']); //人民币账号 不可空 + $key = trim($payment['kq_key']); + $input_charset = 1; //字符集 默认1=utf-8 + $page_url = return_url(basename(__FILE__, '.php')); + $bg_url = ''; + $version = 'v2.0'; + $language = 1; + $sign_type = 1; //签名类型 不可空 固定值 1:md5 + $payer_name = ''; + $payer_contact_type = ''; + $payer_contact = ''; + $order_id = $order['order_sn']; //商户订单号 不可空 + $order_amount = $order['order_amount'] * 100; //商户订单金额 不可空 + $order_time = local_date('YmdHis', $order['add_time']); //商户订单提交时间 不可空 14位 + $product_name = ''; + $product_num = ''; + $product_id = ''; + $product_desc = ''; + $ext1 = $order['log_id']; + $ext2 = ''; + $pay_type = '10'; //支付方式 不可空 + $bank_id = 'BOC'; + $redo_flag = '0'; + $pid = ''; + + /* 生成加密签名串 请务必按照如下顺序和规则组成加密串!*/ + $signmsgval = ''; + $signmsgval = $this->append_param($signmsgval, "inputCharset", $input_charset); + $signmsgval = $this->append_param($signmsgval, "pageUrl", $page_url); + $signmsgval = $this->append_param($signmsgval, "bgUrl", $bg_url); + $signmsgval = $this->append_param($signmsgval, "version", $version); + $signmsgval = $this->append_param($signmsgval, "language", $language); + $signmsgval = $this->append_param($signmsgval, "signType", $sign_type); + $signmsgval = $this->append_param($signmsgval, "merchantAcctId", $merchant_acctid); + $signmsgval = $this->append_param($signmsgval, "payerName", $payer_name); + $signmsgval = $this->append_param($signmsgval, "payerContactType", $payer_contact_type); + $signmsgval = $this->append_param($signmsgval, "payerContact", $payer_contact); + $signmsgval = $this->append_param($signmsgval, "orderId", $order_id); + $signmsgval = $this->append_param($signmsgval, "orderAmount", $order_amount); + $signmsgval = $this->append_param($signmsgval, "orderTime", $order_time); + $signmsgval = $this->append_param($signmsgval, "productName", $product_name); + $signmsgval = $this->append_param($signmsgval, "productNum", $product_num); + $signmsgval = $this->append_param($signmsgval, "productId", $product_id); + $signmsgval = $this->append_param($signmsgval, "productDesc", $product_desc); + $signmsgval = $this->append_param($signmsgval, "ext1", $ext1); + $signmsgval = $this->append_param($signmsgval, "ext2", $ext2); + $signmsgval = $this->append_param($signmsgval, "payType", $pay_type); + $signmsgval = $this->append_param($signmsgval, "bankId", $bank_id); + $signmsgval = $this->append_param($signmsgval, "redoFlag", $redo_flag); + $signmsgval = $this->append_param($signmsgval, "pid", $pid); + $signmsgval = $this->append_param($signmsgval, "key", $key); + $signmsg = strtoupper(md5($signmsgval)); //签名字符串 不可空 + + + $def_url = '
    '; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= "

    "; + + return $def_url; + } + + /** + * 响应操作 + */ + function respond() + { + $payment = get_payment($_GET['code']); + $merchant_acctid = $payment['kq_account']; //人民币账号 不可空 + $key = $payment['kq_key']; + $get_merchant_acctid = trim($_REQUEST['merchantAcctId']); + $pay_result = trim($_REQUEST['payResult']); + $version = trim($_REQUEST['version']); + $language = trim($_REQUEST['language']); + $sign_type = trim($_REQUEST['signType']); + $pay_type = trim($_REQUEST['payType']); + $bank_id = trim($_REQUEST['bankId']); + $order_id = trim($_REQUEST['orderId']); + $order_time = trim($_REQUEST['orderTime']); + $order_amount = trim($_REQUEST['orderAmount']); + $deal_id = trim($_REQUEST['dealId']); + $bank_deal_id = trim($_REQUEST['bankDealId']); + $deal_time = trim($_REQUEST['dealTime']); + $pay_amount = trim($_REQUEST['payAmount']); + $fee = trim($_REQUEST['fee']); + $ext1 = trim($_REQUEST['ext1']); + $ext2 = trim($_REQUEST['ext2']); + $err_code = trim($_REQUEST['errCode']); + $sign_msg = trim($_REQUEST['signMsg']); + + //生成加密串。必须保持如下顺序。 + $merchant_signmsgval = ''; + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"merchantAcctId",$merchant_acctid); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"version",$version); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"language",$language); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"signType",$sign_type); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"payType",$pay_type); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"bankId",$bank_id); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"orderId",$order_id); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"orderTime",$order_time); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"orderAmount",$order_amount); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"dealId",$deal_id); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"bankDealId",$bank_deal_id); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"dealTime",$deal_time); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"payAmount",$pay_amount); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"fee",$fee); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"ext1",$ext1); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"ext2",$ext2); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"payResult",$pay_result); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"errCode",$err_code); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"key",$key); + $merchant_signmsg = md5($merchant_signmsgval); + + //首先对获得的商户号进行比对 + if ($get_merchant_acctid != $merchant_acctid) + { + //商户号错误 + return false; + } + + if (strtoupper($sign_msg) == strtoupper($merchant_signmsg)) + { + if ($pay_result == 10 || $pay_result == 00) + { + order_paid($ext1); + + return true; + } + else + { + //'支付结果失败'; + return false; + } + + } + else + { + //'密钥校对错误'; + return false; + } + } + + /** + * 将变量值不为空的参数组成字符串 + * @param string $strs 参数字符串 + * @param string $key 参数键名 + * @param string $val 参数键对应值 + */ + function append_param($strs,$key,$val) + { + if($strs != "") + { + if($key != '' && $val != '') + { + $strs .= '&' . $key . '=' . $val; + } + } + else + { + if($val != '') + { + $strs = $key . '=' . $val; + } + } + return $strs; + } + +} + +?> \ No newline at end of file diff --git a/includes/modules/payment/kuaiqian_ccb.php b/includes/modules/payment/kuaiqian_ccb.php new file mode 100644 index 0000000..39ee0bf --- /dev/null +++ b/includes/modules/payment/kuaiqian_ccb.php @@ -0,0 +1,287 @@ + 'kq_account', 'type' => 'text', 'value' => ''), + array('name' => 'kq_key', 'type' => 'text', 'value' => ''), + ); + + return; + +} + +class kuaiqian_ccb +{ + /** + * 构造函数 + * + * @access public + * @param + * + * @return void + */ + + function kuaiqian_ccb() + { + } + + function __construct() + { + $this->kuaiqian_ccb(); + } + + /** + * 生成支付代码 + * @param array $order 订单信息 + * @param array $payment 支付方式信息 + */ + function get_code($order, $payment) + { + $merchant_acctid = trim($payment['kq_account']); //人民币账号 不可空 + $key = trim($payment['kq_key']); + $input_charset = 1; //字符集 默认1=utf-8 + $page_url = return_url(basename(__FILE__, '.php')); + $bg_url = ''; + $version = 'v2.0'; + $language = 1; + $sign_type = 1; //签名类型 不可空 固定值 1:md5 + $payer_name = ''; + $payer_contact_type = ''; + $payer_contact = ''; + $order_id = $order['order_sn']; //商户订单号 不可空 + $order_amount = $order['order_amount'] * 100; //商户订单金额 不可空 + $order_time = local_date('YmdHis', $order['add_time']); //商户订单提交时间 不可空 14位 + $product_name = ''; + $product_num = ''; + $product_id = ''; + $product_desc = ''; + $ext1 = $order['log_id']; + $ext2 = ''; + $pay_type = '10'; //支付方式 不可空 + $bank_id = 'CCB'; + $redo_flag = '0'; + $pid = ''; + + /* 生成加密签名串 请务必按照如下顺序和规则组成加密串!*/ + $signmsgval = ''; + $signmsgval = $this->append_param($signmsgval, "inputCharset", $input_charset); + $signmsgval = $this->append_param($signmsgval, "pageUrl", $page_url); + $signmsgval = $this->append_param($signmsgval, "bgUrl", $bg_url); + $signmsgval = $this->append_param($signmsgval, "version", $version); + $signmsgval = $this->append_param($signmsgval, "language", $language); + $signmsgval = $this->append_param($signmsgval, "signType", $sign_type); + $signmsgval = $this->append_param($signmsgval, "merchantAcctId", $merchant_acctid); + $signmsgval = $this->append_param($signmsgval, "payerName", $payer_name); + $signmsgval = $this->append_param($signmsgval, "payerContactType", $payer_contact_type); + $signmsgval = $this->append_param($signmsgval, "payerContact", $payer_contact); + $signmsgval = $this->append_param($signmsgval, "orderId", $order_id); + $signmsgval = $this->append_param($signmsgval, "orderAmount", $order_amount); + $signmsgval = $this->append_param($signmsgval, "orderTime", $order_time); + $signmsgval = $this->append_param($signmsgval, "productName", $product_name); + $signmsgval = $this->append_param($signmsgval, "productNum", $product_num); + $signmsgval = $this->append_param($signmsgval, "productId", $product_id); + $signmsgval = $this->append_param($signmsgval, "productDesc", $product_desc); + $signmsgval = $this->append_param($signmsgval, "ext1", $ext1); + $signmsgval = $this->append_param($signmsgval, "ext2", $ext2); + $signmsgval = $this->append_param($signmsgval, "payType", $pay_type); + $signmsgval = $this->append_param($signmsgval, "bankId", $bank_id); + $signmsgval = $this->append_param($signmsgval, "redoFlag", $redo_flag); + $signmsgval = $this->append_param($signmsgval, "pid", $pid); + $signmsgval = $this->append_param($signmsgval, "key", $key); + $signmsg = strtoupper(md5($signmsgval)); //签名字符串 不可空 + + + $def_url = '
    '; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= "

    "; + + return $def_url; + } + + /** + * 响应操作 + */ + function respond() + { + $payment = get_payment($_GET['code']); + $merchant_acctid = $payment['kq_account']; //人民币账号 不可空 + $key = $payment['kq_key']; + $get_merchant_acctid = trim($_REQUEST['merchantAcctId']); + $pay_result = trim($_REQUEST['payResult']); + $version = trim($_REQUEST['version']); + $language = trim($_REQUEST['language']); + $sign_type = trim($_REQUEST['signType']); + $pay_type = trim($_REQUEST['payType']); + $bank_id = trim($_REQUEST['bankId']); + $order_id = trim($_REQUEST['orderId']); + $order_time = trim($_REQUEST['orderTime']); + $order_amount = trim($_REQUEST['orderAmount']); + $deal_id = trim($_REQUEST['dealId']); + $bank_deal_id = trim($_REQUEST['bankDealId']); + $deal_time = trim($_REQUEST['dealTime']); + $pay_amount = trim($_REQUEST['payAmount']); + $fee = trim($_REQUEST['fee']); + $ext1 = trim($_REQUEST['ext1']); + $ext2 = trim($_REQUEST['ext2']); + $err_code = trim($_REQUEST['errCode']); + $sign_msg = trim($_REQUEST['signMsg']); + + //生成加密串。必须保持如下顺序。 + $merchant_signmsgval = ''; + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"merchantAcctId",$merchant_acctid); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"version",$version); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"language",$language); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"signType",$sign_type); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"payType",$pay_type); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"bankId",$bank_id); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"orderId",$order_id); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"orderTime",$order_time); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"orderAmount",$order_amount); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"dealId",$deal_id); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"bankDealId",$bank_deal_id); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"dealTime",$deal_time); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"payAmount",$pay_amount); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"fee",$fee); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"ext1",$ext1); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"ext2",$ext2); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"payResult",$pay_result); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"errCode",$err_code); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"key",$key); + $merchant_signmsg = md5($merchant_signmsgval); + + //首先对获得的商户号进行比对 + if ($get_merchant_acctid != $merchant_acctid) + { + //商户号错误 + return false; + } + + if (strtoupper($sign_msg) == strtoupper($merchant_signmsg)) + { + if ($pay_result == 10 || $pay_result == 00) + { + order_paid($ext1); + + return true; + } + else + { + //'支付结果失败'; + return false; + } + + } + else + { + //'密钥校对错误'; + return false; + } + } + + /** + * 将变量值不为空的参数组成字符串 + * @param string $strs 参数字符串 + * @param string $key 参数键名 + * @param string $val 参数键对应值 + */ + function append_param($strs,$key,$val) + { + if($strs != "") + { + if($key != '' && $val != '') + { + $strs .= '&' . $key . '=' . $val; + } + } + else + { + if($val != '') + { + $strs = $key . '=' . $val; + } + } + return $strs; + } + +} + +?> \ No newline at end of file diff --git a/includes/modules/payment/kuaiqian_cmb.php b/includes/modules/payment/kuaiqian_cmb.php new file mode 100644 index 0000000..696ae06 --- /dev/null +++ b/includes/modules/payment/kuaiqian_cmb.php @@ -0,0 +1,287 @@ + 'kq_account', 'type' => 'text', 'value' => ''), + array('name' => 'kq_key', 'type' => 'text', 'value' => ''), + ); + + return; + +} + +class kuaiqian_cmb +{ + /** + * 构造函数 + * + * @access public + * @param + * + * @return void + */ + + function kuaiqian_cmb() + { + } + + function __construct() + { + $this->kuaiqian_cmb(); + } + + /** + * 生成支付代码 + * @param array $order 订单信息 + * @param array $payment 支付方式信息 + */ + function get_code($order, $payment) + { + $merchant_acctid = trim($payment['kq_account']); //人民币账号 不可空 + $key = trim($payment['kq_key']); + $input_charset = 1; //字符集 默认1=utf-8 + $page_url = return_url(basename(__FILE__, '.php')); + $bg_url = ''; + $version = 'v2.0'; + $language = 1; + $sign_type = 1; //签名类型 不可空 固定值 1:md5 + $payer_name = ''; + $payer_contact_type = ''; + $payer_contact = ''; + $order_id = $order['order_sn']; //商户订单号 不可空 + $order_amount = $order['order_amount'] * 100; //商户订单金额 不可空 + $order_time = local_date('YmdHis', $order['add_time']); //商户订单提交时间 不可空 14位 + $product_name = ''; + $product_num = ''; + $product_id = ''; + $product_desc = ''; + $ext1 = $order['log_id']; + $ext2 = ''; + $pay_type = '10'; //支付方式 不可空 + $bank_id = 'CMB'; + $redo_flag = '0'; + $pid = ''; + + /* 生成加密签名串 请务必按照如下顺序和规则组成加密串!*/ + $signmsgval = ''; + $signmsgval = $this->append_param($signmsgval, "inputCharset", $input_charset); + $signmsgval = $this->append_param($signmsgval, "pageUrl", $page_url); + $signmsgval = $this->append_param($signmsgval, "bgUrl", $bg_url); + $signmsgval = $this->append_param($signmsgval, "version", $version); + $signmsgval = $this->append_param($signmsgval, "language", $language); + $signmsgval = $this->append_param($signmsgval, "signType", $sign_type); + $signmsgval = $this->append_param($signmsgval, "merchantAcctId", $merchant_acctid); + $signmsgval = $this->append_param($signmsgval, "payerName", $payer_name); + $signmsgval = $this->append_param($signmsgval, "payerContactType", $payer_contact_type); + $signmsgval = $this->append_param($signmsgval, "payerContact", $payer_contact); + $signmsgval = $this->append_param($signmsgval, "orderId", $order_id); + $signmsgval = $this->append_param($signmsgval, "orderAmount", $order_amount); + $signmsgval = $this->append_param($signmsgval, "orderTime", $order_time); + $signmsgval = $this->append_param($signmsgval, "productName", $product_name); + $signmsgval = $this->append_param($signmsgval, "productNum", $product_num); + $signmsgval = $this->append_param($signmsgval, "productId", $product_id); + $signmsgval = $this->append_param($signmsgval, "productDesc", $product_desc); + $signmsgval = $this->append_param($signmsgval, "ext1", $ext1); + $signmsgval = $this->append_param($signmsgval, "ext2", $ext2); + $signmsgval = $this->append_param($signmsgval, "payType", $pay_type); + $signmsgval = $this->append_param($signmsgval, "bankId", $bank_id); + $signmsgval = $this->append_param($signmsgval, "redoFlag", $redo_flag); + $signmsgval = $this->append_param($signmsgval, "pid", $pid); + $signmsgval = $this->append_param($signmsgval, "key", $key); + $signmsg = strtoupper(md5($signmsgval)); //签名字符串 不可空 + + + $def_url = '
    '; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= "

    "; + + return $def_url; + } + + /** + * 响应操作 + */ + function respond() + { + $payment = get_payment($_GET['code']); + $merchant_acctid = $payment['kq_account']; //人民币账号 不可空 + $key = $payment['kq_key']; + $get_merchant_acctid = trim($_REQUEST['merchantAcctId']); + $pay_result = trim($_REQUEST['payResult']); + $version = trim($_REQUEST['version']); + $language = trim($_REQUEST['language']); + $sign_type = trim($_REQUEST['signType']); + $pay_type = trim($_REQUEST['payType']); + $bank_id = trim($_REQUEST['bankId']); + $order_id = trim($_REQUEST['orderId']); + $order_time = trim($_REQUEST['orderTime']); + $order_amount = trim($_REQUEST['orderAmount']); + $deal_id = trim($_REQUEST['dealId']); + $bank_deal_id = trim($_REQUEST['bankDealId']); + $deal_time = trim($_REQUEST['dealTime']); + $pay_amount = trim($_REQUEST['payAmount']); + $fee = trim($_REQUEST['fee']); + $ext1 = trim($_REQUEST['ext1']); + $ext2 = trim($_REQUEST['ext2']); + $err_code = trim($_REQUEST['errCode']); + $sign_msg = trim($_REQUEST['signMsg']); + + //生成加密串。必须保持如下顺序。 + $merchant_signmsgval = ''; + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"merchantAcctId",$merchant_acctid); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"version",$version); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"language",$language); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"signType",$sign_type); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"payType",$pay_type); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"bankId",$bank_id); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"orderId",$order_id); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"orderTime",$order_time); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"orderAmount",$order_amount); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"dealId",$deal_id); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"bankDealId",$bank_deal_id); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"dealTime",$deal_time); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"payAmount",$pay_amount); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"fee",$fee); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"ext1",$ext1); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"ext2",$ext2); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"payResult",$pay_result); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"errCode",$err_code); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"key",$key); + $merchant_signmsg = md5($merchant_signmsgval); + + //首先对获得的商户号进行比对 + if ($get_merchant_acctid != $merchant_acctid) + { + //商户号错误 + return false; + } + + if (strtoupper($sign_msg) == strtoupper($merchant_signmsg)) + { + if ($pay_result == 10 || $pay_result == 00) + { + order_paid($ext1); + + return true; + } + else + { + //'支付结果失败'; + return false; + } + + } + else + { + //'密钥校对错误'; + return false; + } + } + + /** + * 将变量值不为空的参数组成字符串 + * @param string $strs 参数字符串 + * @param string $key 参数键名 + * @param string $val 参数键对应值 + */ + function append_param($strs,$key,$val) + { + if($strs != "") + { + if($key != '' && $val != '') + { + $strs .= '&' . $key . '=' . $val; + } + } + else + { + if($val != '') + { + $strs = $key . '=' . $val; + } + } + return $strs; + } + +} + +?> \ No newline at end of file diff --git a/includes/modules/payment/kuaiqian_cmbc.php b/includes/modules/payment/kuaiqian_cmbc.php new file mode 100644 index 0000000..d6a7a97 --- /dev/null +++ b/includes/modules/payment/kuaiqian_cmbc.php @@ -0,0 +1,287 @@ + 'kq_account', 'type' => 'text', 'value' => ''), + array('name' => 'kq_key', 'type' => 'text', 'value' => ''), + ); + + return; + +} + +class kuaiqian_cmbc +{ + /** + * 构造函数 + * + * @access public + * @param + * + * @return void + */ + + function kuaiqian_cmbc() + { + } + + function __construct() + { + $this->kuaiqian_cmbc(); + } + + /** + * 生成支付代码 + * @param array $order 订单信息 + * @param array $payment 支付方式信息 + */ + function get_code($order, $payment) + { + $merchant_acctid = trim($payment['kq_account']); //人民币账号 不可空 + $key = trim($payment['kq_key']); + $input_charset = 1; //字符集 默认1=utf-8 + $page_url = return_url(basename(__FILE__, '.php')); + $bg_url = ''; + $version = 'v2.0'; + $language = 1; + $sign_type = 1; //签名类型 不可空 固定值 1:md5 + $payer_name = ''; + $payer_contact_type = ''; + $payer_contact = ''; + $order_id = $order['order_sn']; //商户订单号 不可空 + $order_amount = $order['order_amount'] * 100; //商户订单金额 不可空 + $order_time = local_date('YmdHis', $order['add_time']); //商户订单提交时间 不可空 14位 + $product_name = ''; + $product_num = ''; + $product_id = ''; + $product_desc = ''; + $ext1 = $order['log_id']; + $ext2 = ''; + $pay_type = '10'; //支付方式 不可空 + $bank_id = 'CMBC'; + $redo_flag = '0'; + $pid = ''; + + /* 生成加密签名串 请务必按照如下顺序和规则组成加密串!*/ + $signmsgval = ''; + $signmsgval = $this->append_param($signmsgval, "inputCharset", $input_charset); + $signmsgval = $this->append_param($signmsgval, "pageUrl", $page_url); + $signmsgval = $this->append_param($signmsgval, "bgUrl", $bg_url); + $signmsgval = $this->append_param($signmsgval, "version", $version); + $signmsgval = $this->append_param($signmsgval, "language", $language); + $signmsgval = $this->append_param($signmsgval, "signType", $sign_type); + $signmsgval = $this->append_param($signmsgval, "merchantAcctId", $merchant_acctid); + $signmsgval = $this->append_param($signmsgval, "payerName", $payer_name); + $signmsgval = $this->append_param($signmsgval, "payerContactType", $payer_contact_type); + $signmsgval = $this->append_param($signmsgval, "payerContact", $payer_contact); + $signmsgval = $this->append_param($signmsgval, "orderId", $order_id); + $signmsgval = $this->append_param($signmsgval, "orderAmount", $order_amount); + $signmsgval = $this->append_param($signmsgval, "orderTime", $order_time); + $signmsgval = $this->append_param($signmsgval, "productName", $product_name); + $signmsgval = $this->append_param($signmsgval, "productNum", $product_num); + $signmsgval = $this->append_param($signmsgval, "productId", $product_id); + $signmsgval = $this->append_param($signmsgval, "productDesc", $product_desc); + $signmsgval = $this->append_param($signmsgval, "ext1", $ext1); + $signmsgval = $this->append_param($signmsgval, "ext2", $ext2); + $signmsgval = $this->append_param($signmsgval, "payType", $pay_type); + $signmsgval = $this->append_param($signmsgval, "bankId", $bank_id); + $signmsgval = $this->append_param($signmsgval, "redoFlag", $redo_flag); + $signmsgval = $this->append_param($signmsgval, "pid", $pid); + $signmsgval = $this->append_param($signmsgval, "key", $key); + $signmsg = strtoupper(md5($signmsgval)); //签名字符串 不可空 + + + $def_url = '
    '; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= "

    "; + + return $def_url; + } + + /** + * 响应操作 + */ + function respond() + { + $payment = get_payment($_GET['code']); + $merchant_acctid = $payment['kq_account']; //人民币账号 不可空 + $key = $payment['kq_key']; + $get_merchant_acctid = trim($_REQUEST['merchantAcctId']); + $pay_result = trim($_REQUEST['payResult']); + $version = trim($_REQUEST['version']); + $language = trim($_REQUEST['language']); + $sign_type = trim($_REQUEST['signType']); + $pay_type = trim($_REQUEST['payType']); + $bank_id = trim($_REQUEST['bankId']); + $order_id = trim($_REQUEST['orderId']); + $order_time = trim($_REQUEST['orderTime']); + $order_amount = trim($_REQUEST['orderAmount']); + $deal_id = trim($_REQUEST['dealId']); + $bank_deal_id = trim($_REQUEST['bankDealId']); + $deal_time = trim($_REQUEST['dealTime']); + $pay_amount = trim($_REQUEST['payAmount']); + $fee = trim($_REQUEST['fee']); + $ext1 = trim($_REQUEST['ext1']); + $ext2 = trim($_REQUEST['ext2']); + $err_code = trim($_REQUEST['errCode']); + $sign_msg = trim($_REQUEST['signMsg']); + + //生成加密串。必须保持如下顺序。 + $merchant_signmsgval = ''; + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"merchantAcctId",$merchant_acctid); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"version",$version); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"language",$language); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"signType",$sign_type); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"payType",$pay_type); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"bankId",$bank_id); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"orderId",$order_id); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"orderTime",$order_time); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"orderAmount",$order_amount); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"dealId",$deal_id); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"bankDealId",$bank_deal_id); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"dealTime",$deal_time); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"payAmount",$pay_amount); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"fee",$fee); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"ext1",$ext1); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"ext2",$ext2); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"payResult",$pay_result); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"errCode",$err_code); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"key",$key); + $merchant_signmsg = md5($merchant_signmsgval); + + //首先对获得的商户号进行比对 + if ($get_merchant_acctid != $merchant_acctid) + { + //商户号错误 + return false; + } + + if (strtoupper($sign_msg) == strtoupper($merchant_signmsg)) + { + if ($pay_result == 10 || $pay_result == 00) + { + order_paid($ext1); + + return true; + } + else + { + //'支付结果失败'; + return false; + } + + } + else + { + //'密钥校对错误'; + return false; + } + } + + /** + * 将变量值不为空的参数组成字符串 + * @param string $strs 参数字符串 + * @param string $key 参数键名 + * @param string $val 参数键对应值 + */ + function append_param($strs,$key,$val) + { + if($strs != "") + { + if($key != '' && $val != '') + { + $strs .= '&' . $key . '=' . $val; + } + } + else + { + if($val != '') + { + $strs = $key . '=' . $val; + } + } + return $strs; + } + +} + +?> \ No newline at end of file diff --git a/includes/modules/payment/kuaiqian_icbc.php b/includes/modules/payment/kuaiqian_icbc.php new file mode 100644 index 0000000..4bff929 --- /dev/null +++ b/includes/modules/payment/kuaiqian_icbc.php @@ -0,0 +1,287 @@ + 'kq_account', 'type' => 'text', 'value' => ''), + array('name' => 'kq_key', 'type' => 'text', 'value' => ''), + ); + + return; + +} + +class kuaiqian_icbc +{ + /** + * 构造函数 + * + * @access public + * @param + * + * @return void + */ + + function kuaiqian_icbc() + { + } + + function __construct() + { + $this->kuaiqian_icbc(); + } + + /** + * 生成支付代码 + * @param array $order 订单信息 + * @param array $payment 支付方式信息 + */ + function get_code($order, $payment) + { + $merchant_acctid = trim($payment['kq_account']); //人民币账号 不可空 + $key = trim($payment['kq_key']); + $input_charset = 1; //字符集 默认1=utf-8 + $page_url = return_url(basename(__FILE__, '.php')); + $bg_url = ''; + $version = 'v2.0'; + $language = 1; + $sign_type = 1; //签名类型 不可空 固定值 1:md5 + $payer_name = ''; + $payer_contact_type = ''; + $payer_contact = ''; + $order_id = $order['order_sn']; //商户订单号 不可空 + $order_amount = $order['order_amount'] * 100; //商户订单金额 不可空 + $order_time = local_date('YmdHis', $order['add_time']); //商户订单提交时间 不可空 14位 + $product_name = ''; + $product_num = ''; + $product_id = ''; + $product_desc = ''; + $ext1 = $order['log_id']; + $ext2 = ''; + $pay_type = '10'; //支付方式 不可空 + $bank_id = 'ICBC'; + $redo_flag = '0'; + $pid = ''; + + /* 生成加密签名串 请务必按照如下顺序和规则组成加密串!*/ + $signmsgval = ''; + $signmsgval = $this->append_param($signmsgval, "inputCharset", $input_charset); + $signmsgval = $this->append_param($signmsgval, "pageUrl", $page_url); + $signmsgval = $this->append_param($signmsgval, "bgUrl", $bg_url); + $signmsgval = $this->append_param($signmsgval, "version", $version); + $signmsgval = $this->append_param($signmsgval, "language", $language); + $signmsgval = $this->append_param($signmsgval, "signType", $sign_type); + $signmsgval = $this->append_param($signmsgval, "merchantAcctId", $merchant_acctid); + $signmsgval = $this->append_param($signmsgval, "payerName", $payer_name); + $signmsgval = $this->append_param($signmsgval, "payerContactType", $payer_contact_type); + $signmsgval = $this->append_param($signmsgval, "payerContact", $payer_contact); + $signmsgval = $this->append_param($signmsgval, "orderId", $order_id); + $signmsgval = $this->append_param($signmsgval, "orderAmount", $order_amount); + $signmsgval = $this->append_param($signmsgval, "orderTime", $order_time); + $signmsgval = $this->append_param($signmsgval, "productName", $product_name); + $signmsgval = $this->append_param($signmsgval, "productNum", $product_num); + $signmsgval = $this->append_param($signmsgval, "productId", $product_id); + $signmsgval = $this->append_param($signmsgval, "productDesc", $product_desc); + $signmsgval = $this->append_param($signmsgval, "ext1", $ext1); + $signmsgval = $this->append_param($signmsgval, "ext2", $ext2); + $signmsgval = $this->append_param($signmsgval, "payType", $pay_type); + $signmsgval = $this->append_param($signmsgval, "bankId", $bank_id); + $signmsgval = $this->append_param($signmsgval, "redoFlag", $redo_flag); + $signmsgval = $this->append_param($signmsgval, "pid", $pid); + $signmsgval = $this->append_param($signmsgval, "key", $key); + $signmsg = strtoupper(md5($signmsgval)); //签名字符串 不可空 + + + $def_url = '
    '; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= "

    "; + + return $def_url; + } + + /** + * 响应操作 + */ + function respond() + { + $payment = get_payment($_GET['code']); + $merchant_acctid = $payment['kq_account']; //人民币账号 不可空 + $key = $payment['kq_key']; + $get_merchant_acctid = trim($_REQUEST['merchantAcctId']); + $pay_result = trim($_REQUEST['payResult']); + $version = trim($_REQUEST['version']); + $language = trim($_REQUEST['language']); + $sign_type = trim($_REQUEST['signType']); + $pay_type = trim($_REQUEST['payType']); + $bank_id = trim($_REQUEST['bankId']); + $order_id = trim($_REQUEST['orderId']); + $order_time = trim($_REQUEST['orderTime']); + $order_amount = trim($_REQUEST['orderAmount']); + $deal_id = trim($_REQUEST['dealId']); + $bank_deal_id = trim($_REQUEST['bankDealId']); + $deal_time = trim($_REQUEST['dealTime']); + $pay_amount = trim($_REQUEST['payAmount']); + $fee = trim($_REQUEST['fee']); + $ext1 = trim($_REQUEST['ext1']); + $ext2 = trim($_REQUEST['ext2']); + $err_code = trim($_REQUEST['errCode']); + $sign_msg = trim($_REQUEST['signMsg']); + + //生成加密串。必须保持如下顺序。 + $merchant_signmsgval = ''; + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"merchantAcctId",$merchant_acctid); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"version",$version); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"language",$language); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"signType",$sign_type); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"payType",$pay_type); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"bankId",$bank_id); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"orderId",$order_id); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"orderTime",$order_time); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"orderAmount",$order_amount); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"dealId",$deal_id); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"bankDealId",$bank_deal_id); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"dealTime",$deal_time); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"payAmount",$pay_amount); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"fee",$fee); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"ext1",$ext1); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"ext2",$ext2); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"payResult",$pay_result); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"errCode",$err_code); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"key",$key); + $merchant_signmsg = md5($merchant_signmsgval); + + //首先对获得的商户号进行比对 + if ($get_merchant_acctid != $merchant_acctid) + { + //商户号错误 + return false; + } + + if (strtoupper($sign_msg) == strtoupper($merchant_signmsg)) + { + if ($pay_result == 10 || $pay_result == 00) + { + order_paid($ext1); + + return true; + } + else + { + //'支付结果失败'; + return false; + } + + } + else + { + //'密钥校对错误'; + return false; + } + } + + /** + * 将变量值不为空的参数组成字符串 + * @param string $strs 参数字符串 + * @param string $key 参数键名 + * @param string $val 参数键对应值 + */ + function append_param($strs,$key,$val) + { + if($strs != "") + { + if($key != '' && $val != '') + { + $strs .= '&' . $key . '=' . $val; + } + } + else + { + if($val != '') + { + $strs = $key . '=' . $val; + } + } + return $strs; + } + +} + +?> \ No newline at end of file diff --git a/includes/modules/payment/kuaiqian_sdb.php b/includes/modules/payment/kuaiqian_sdb.php new file mode 100644 index 0000000..341b698 --- /dev/null +++ b/includes/modules/payment/kuaiqian_sdb.php @@ -0,0 +1,287 @@ + 'kq_account', 'type' => 'text', 'value' => ''), + array('name' => 'kq_key', 'type' => 'text', 'value' => ''), + ); + + return; + +} + +class kuaiqian_sdb +{ + /** + * 构造函数 + * + * @access public + * @param + * + * @return void + */ + + function kuaiqian_sdb() + { + } + + function __construct() + { + $this->kuaiqian_sdb(); + } + + /** + * 生成支付代码 + * @param array $order 订单信息 + * @param array $payment 支付方式信息 + */ + function get_code($order, $payment) + { + $merchant_acctid = trim($payment['kq_account']); //人民币账号 不可空 + $key = trim($payment['kq_key']); + $input_charset = 1; //字符集 默认1=utf-8 + $page_url = return_url(basename(__FILE__, '.php')); + $bg_url = ''; + $version = 'v2.0'; + $language = 1; + $sign_type = 1; //签名类型 不可空 固定值 1:md5 + $payer_name = ''; + $payer_contact_type = ''; + $payer_contact = ''; + $order_id = $order['order_sn']; //商户订单号 不可空 + $order_amount = $order['order_amount'] * 100; //商户订单金额 不可空 + $order_time = local_date('YmdHis', $order['add_time']); //商户订单提交时间 不可空 14位 + $product_name = ''; + $product_num = ''; + $product_id = ''; + $product_desc = ''; + $ext1 = $order['log_id']; + $ext2 = ''; + $pay_type = '10'; //支付方式 不可空 + $bank_id = 'SDB'; + $redo_flag = '0'; + $pid = ''; + + /* 生成加密签名串 请务必按照如下顺序和规则组成加密串!*/ + $signmsgval = ''; + $signmsgval = $this->append_param($signmsgval, "inputCharset", $input_charset); + $signmsgval = $this->append_param($signmsgval, "pageUrl", $page_url); + $signmsgval = $this->append_param($signmsgval, "bgUrl", $bg_url); + $signmsgval = $this->append_param($signmsgval, "version", $version); + $signmsgval = $this->append_param($signmsgval, "language", $language); + $signmsgval = $this->append_param($signmsgval, "signType", $sign_type); + $signmsgval = $this->append_param($signmsgval, "merchantAcctId", $merchant_acctid); + $signmsgval = $this->append_param($signmsgval, "payerName", $payer_name); + $signmsgval = $this->append_param($signmsgval, "payerContactType", $payer_contact_type); + $signmsgval = $this->append_param($signmsgval, "payerContact", $payer_contact); + $signmsgval = $this->append_param($signmsgval, "orderId", $order_id); + $signmsgval = $this->append_param($signmsgval, "orderAmount", $order_amount); + $signmsgval = $this->append_param($signmsgval, "orderTime", $order_time); + $signmsgval = $this->append_param($signmsgval, "productName", $product_name); + $signmsgval = $this->append_param($signmsgval, "productNum", $product_num); + $signmsgval = $this->append_param($signmsgval, "productId", $product_id); + $signmsgval = $this->append_param($signmsgval, "productDesc", $product_desc); + $signmsgval = $this->append_param($signmsgval, "ext1", $ext1); + $signmsgval = $this->append_param($signmsgval, "ext2", $ext2); + $signmsgval = $this->append_param($signmsgval, "payType", $pay_type); + $signmsgval = $this->append_param($signmsgval, "bankId", $bank_id); + $signmsgval = $this->append_param($signmsgval, "redoFlag", $redo_flag); + $signmsgval = $this->append_param($signmsgval, "pid", $pid); + $signmsgval = $this->append_param($signmsgval, "key", $key); + $signmsg = strtoupper(md5($signmsgval)); //签名字符串 不可空 + + + $def_url = '
    '; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= "

    "; + + return $def_url; + } + + /** + * 响应操作 + */ + function respond() + { + $payment = get_payment($_GET['code']); + $merchant_acctid = $payment['kq_account']; //人民币账号 不可空 + $key = $payment['kq_key']; + $get_merchant_acctid = trim($_REQUEST['merchantAcctId']); + $pay_result = trim($_REQUEST['payResult']); + $version = trim($_REQUEST['version']); + $language = trim($_REQUEST['language']); + $sign_type = trim($_REQUEST['signType']); + $pay_type = trim($_REQUEST['payType']); + $bank_id = trim($_REQUEST['bankId']); + $order_id = trim($_REQUEST['orderId']); + $order_time = trim($_REQUEST['orderTime']); + $order_amount = trim($_REQUEST['orderAmount']); + $deal_id = trim($_REQUEST['dealId']); + $bank_deal_id = trim($_REQUEST['bankDealId']); + $deal_time = trim($_REQUEST['dealTime']); + $pay_amount = trim($_REQUEST['payAmount']); + $fee = trim($_REQUEST['fee']); + $ext1 = trim($_REQUEST['ext1']); + $ext2 = trim($_REQUEST['ext2']); + $err_code = trim($_REQUEST['errCode']); + $sign_msg = trim($_REQUEST['signMsg']); + + //生成加密串。必须保持如下顺序。 + $merchant_signmsgval = ''; + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"merchantAcctId",$merchant_acctid); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"version",$version); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"language",$language); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"signType",$sign_type); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"payType",$pay_type); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"bankId",$bank_id); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"orderId",$order_id); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"orderTime",$order_time); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"orderAmount",$order_amount); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"dealId",$deal_id); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"bankDealId",$bank_deal_id); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"dealTime",$deal_time); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"payAmount",$pay_amount); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"fee",$fee); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"ext1",$ext1); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"ext2",$ext2); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"payResult",$pay_result); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"errCode",$err_code); + $merchant_signmsgval = $this->append_param($merchant_signmsgval,"key",$key); + $merchant_signmsg = md5($merchant_signmsgval); + + //首先对获得的商户号进行比对 + if ($get_merchant_acctid != $merchant_acctid) + { + //商户号错误 + return false; + } + + if (strtoupper($sign_msg) == strtoupper($merchant_signmsg)) + { + if ($pay_result == 10 || $pay_result == 00) + { + order_paid($ext1); + + return true; + } + else + { + //'支付结果失败'; + return false; + } + + } + else + { + //'密钥校对错误'; + return false; + } + } + + /** + * 将变量值不为空的参数组成字符串 + * @param string $strs 参数字符串 + * @param string $key 参数键名 + * @param string $val 参数键对应值 + */ + function append_param($strs,$key,$val) + { + if($strs != "") + { + if($key != '' && $val != '') + { + $strs .= '&' . $key . '=' . $val; + } + } + else + { + if($val != '') + { + $strs = $key . '=' . $val; + } + } + return $strs; + } + +} + +?> \ No newline at end of file diff --git a/includes/modules/payment/nps.php b/includes/modules/payment/nps.php new file mode 100644 index 0000000..e903c31 --- /dev/null +++ b/includes/modules/payment/nps.php @@ -0,0 +1,247 @@ + 'nps_account', 'type' => 'text', 'value' => ''), + array('name' => 'nps_key', 'type' => 'text', 'value' => ''), + ); + + return; +} + +class nps +{ + /** + * 构造函数 + * + * @access public + * @param + * + * @return void + */ + function nps() + { + } + + function __construct() + { + $this->nps(); + } + + /** + * 生成支付代码 + * @param array $order 订单信息 + * @param array $payment 支付方式信息 + */ + function get_code($order, $payment) + { + $m_id = trim($payment['nps_account']); + $m_orderid = $order['log_id']; + $m_oamount = $order['order_amount']; + $m_ocurrency = '1'; + $m_url = return_url(basename(__FILE__, '.php')); + $m_language = '1'; + $s_name = 'null'; + $s_addr = 'null'; + $s_postcode = 'null'; + $s_tel = 'null'; + $s_eml = 'null'; + $r_name = 'null'; + $r_addr = 'null'; + $r_postcode = 'null'; + $r_tel = 'null'; + $r_eml = 'null'; + $m_ocomment = '欢迎使用NPS在线支付'; + $modate = date('y-m-d H:i:s',time()); + $m_status = 0; + + //组织订单信息 + $m_info = $m_id . '|' . $m_orderid . '|' . $m_oamount . '|' . $m_ocurrency . '|' . $m_url . '|' . $m_language; + $s_info = $s_name . '|' . $s_addr . '|' . $s_postcode . '|' . $s_tel . '|' . $s_eml; + $r_info = $r_name . '|' . $r_addr . '|' . $r_postcode . '|' . $r_tel . '|' . $r_eml . '|' . $m_ocomment . '|' . $m_status . '|' . $modate; + + $OrderInfo = $m_info . '|' . $s_info . '|' . $r_info; + + //订单信息先转换成HEX,然后再加密 + $key = $payment['nps_key']; //<--支付密钥--> 注:此处密钥必须与商家后台里的密钥一致 + + $OrderInfo = $this->StrToHex($OrderInfo); + $digest = strtoupper(md5($OrderInfo . $key)); + + $def_url = "
    "; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + + $def_url .= '
    '; + + return $def_url; + } + + /** + * 响应操作 + */ + + function respond() + { + $payment = get_payment(basename(__FILE__, '.php')); + + $m_id = $_POST['m_id']; // 商家号 + $m_orderid = $_POST['m_orderid']; // 商家订单号 + $m_oamount = $_POST['m_oamount']; // 支付金额 + $m_ocurrency = $_POST['m_ocurrency']; // 币种 + $m_language = $_POST['m_language']; // 语言选择 + $s_name = $_POST['s_name']; // 消费者姓名 + $s_addr = $_POST['s_addr']; // 消费者住址 + $s_postcode = $_POST['s_postcode']; // 邮政编码 + $s_tel = $_POST['s_tel']; // 消费者联系电话 + $s_eml = $_POST['s_eml']; // 消费者邮件地址 + $r_name = $_POST['r_name']; // 消费者姓名 + $r_addr = $_POST['r_addr']; // 收货人住址 + $r_postcode = $_POST['r_postcode']; // 收货人邮政编码 + $r_tel = $_POST['r_tel']; // 收货人联系电话 + $r_eml = $_POST['r_eml']; // 收货人电子地址 + $m_ocomment = $_POST['m_ocomment']; // 备注 + $State = $_POST['m_status']; // 支付状态2成功,3失败 + $modate = $_POST['modate']; // 返回日期 + $order_sn = $_POST['m_orderid']; + + //接收组件的加密 + $OrderInfo = $_POST['OrderMessage'];// 订单加密信息 + $signMsg = $_POST['Digest']; // 密匙 + + //接收新的md5加密认证 + $newmd5info = $_POST['newmd5info']; + + //检查签名 + $key = $payment['nps_key']; //<--支付密钥--> 注:此处密钥必须与商家后台里的密钥一致 + $digest = strtoupper(md5($OrderInfo . $key)); + + //新的整合md5加密 + $newtext = $m_id . $m_orderid . $m_oamount . $key . $State; + $newMd5digest = strtoupper(md5($newtext)); + + if ($digest == $signMsg) + { + //解密 + //$decode = $DES->Descrypt($OrderInfo, $key); + $OrderInfo = $this->HexToStr($OrderInfo); + //md5密匙认证 + if ($newmd5info == $newMd5digest) + { + if ($State == 2) + { + //改变订单状态 + order_paid($m_orderid); + + return true; + } + else + { + return false; + } + } + else + { + return false; + } + } + else + { + return false; + } + } + + function StrToHex($string) + { + $hex = ''; + + for ($i = 0, $count = strlen($string); $i < $count; $i++) + { + $hex .= dechex(ord($string[$i])); + } + + return strtoupper($hex); + } + + function HexToStr($hex) + { + $string = ''; + + for ($i = 0, $count = strlen($hex) - 1; $i < $count; $i += 2) + { + $string .= chr(hexdec($hex[$i] . $hex[$i + 1])); + } + + return $string; + } +} + +?> \ No newline at end of file diff --git a/includes/modules/payment/pay800.php b/includes/modules/payment/pay800.php new file mode 100644 index 0000000..15bc860 --- /dev/null +++ b/includes/modules/payment/pay800.php @@ -0,0 +1,308 @@ + 'pay800_account', 'type' => 'text', 'value' => ''), + array('name' => 'pay800_key', 'type' => 'text', 'value' => ''), + array('name' => 'pay800_currency', 'type' => 'select', 'value' => ''), + array('name' => 'pay800_language', 'type' => 'select', 'value' => ''), + ); + + return; +} + + +class pay800 +{ + /** + * 生成支付代码 + * @param array $order 订单信息 + * @param array $payment 支付方式信息 + */ + function get_code($order, $payment) + { + $data_M_ID = $payment['pay800_account']; //商 家 号: + $data_M_OrderID = $order['log_id']; //订 单 号: + $data_M_OAmount = $order['order_amount']; //订单金额: + $data_M_OCurrency = $payment['pay800_currency']; //币 种: + $data_M_URL = return_url(basename(__FILE__, '.php')); //返回地址: + $data_M_Language = $payment['pay800_language']; //语言选择: + + $data_T_TradeName = ''; //$order['order_sn']; //商品名称: + $data_T_Unit = ''; //$order['order_sn']; //商品单位: + $data_T_UnitPrice = ''; //$order['order_sn']; //商品单价: + $data_T_quantity = ''; //$order['order_sn']; //商品数量: + $data_T_carriage = ''; //$order['shipping_fee']; //商品运费: + + $data_S_Name = ''; //$order['order_sn']; //消费者姓名: + $data_S_Address = ''; //$order['order_sn']; //消费者住址: + $data_S_PostCode = ''; //$order['order_sn']; //消费者邮码: + $data_S_Telephone = ''; //$order['order_sn']; //消费者电话: + $data_S_Email = ''; //$order['order_sn']; //消费者邮件: + + $data_R_Name = ''; //$order['consignee']; //收货人姓名: + $data_R_Address = ''; //$order['address']; //收货人住址: + $data_R_PostCode = ''; //$order['zipcode']; //收货人邮码: + $data_R_Telephone = ''; //$order['tel']; //收货人电话: + $data_R_Email = ''; //$order['email']; //收货人邮件: + + $data_M_OComment = ''; //$order['inv_content']; //备 注 + $data_M_OState = '0'; //交易状态: + $data_M_ODate = date('Y-m-d H:i:s'); //时间字段: + + $data_PrivateKey = $payment['pay800_key']; + + //$data_R_Telephone2 = $order['mobile']; //收货人手机: + + if (empty($data_M_OComment)) + { + $data_M_OComment = 'From ECShop order ' . $payment['pay800_account']; + } + + + $data_m_info = '' . + $data_M_ID . '|' . + $data_M_OrderID . '|' . + $data_M_OAmount . '|' . + $data_M_OCurrency . '|' . + $data_M_URL . '|' . + $data_M_Language . '' ; + + $data_t_info = ''. + $data_T_TradeName . '|' . + $data_T_Unit . '|' . + $data_T_UnitPrice . '|' . + $data_T_quantity . '|' . + $data_T_carriage . '' ; + + $data_s_info = ''. + $data_S_Name . '|' . + $data_S_Address . '|' . + $data_S_PostCode . '|' . + $data_S_Telephone . '|' . + $data_S_Email . '|' . + $data_R_Name . '' ; + + $data_r_info = ''. + $data_R_Address . '|' . + $data_R_PostCode . '|' . + $data_R_Telephone . '|' . + $data_R_Email . '|' . + $data_M_OComment . '|' . + $data_M_OState . '|' . + $data_M_ODate . '' ; + + + $data_OrderInfo = $data_m_info .'|'. $data_t_info .'|'. $data_s_info .'|'. $data_r_info ; + $data_OrderMessage = $data_OrderInfo . $data_PrivateKey ; + $data_Digest = strtoupper(trim(md5($data_OrderMessage))); + + $def_url = "
    ". + " ". + " ". + " ". + " ". + "
    " ; + + return $def_url; + } + + /** + * 响应操作 + */ + function respond() + { + $payment = get_payment('pay800'); + + $data_PrivateKey = $payment['pay800_key']; + $get_PayResult = false; + + $rec_M_id = $_REQUEST['M_ID']; + $rec_OrderMessage = $_REQUEST['OrderMessage']; + $rec_Digest = $_REQUEST['digest']; + + + + $data_OrderMessage = $rec_OrderMessage . $data_PrivateKey; + $data_Digest = strtoupper(trim(md5($data_OrderMessage))); + + if ($rec_OrderMessage == '') + { + //echo '订单加密信息为空值'; + return $get_PayResult; + } + + if ($rec_Digest == '') + { + //echo '认证签名为空值'; + return $get_PayResult; + } + + if ($data_Digest == $rec_Digest) + { + $tempStr = $rec_OrderMessage; + $V = explode('|',$tempStr); + $num = count($V); + if ($num !== 25) //返回时,多加了一个数据 m_serial,这里应该是25 + { + //echo 'error message = '. $tempStr .'

    '; + return $get_PayResult; + } + + $data_m_id = $V[0]; + $data_m_orderid = $V[1]; + $data_m_oamount = $V[2]; + $data_m_ocurrency = $V[3]; + $data_m_url = $V[4]; + $data_m_language = $V[5]; + + $data_T_TradeName = $V[6]; + $data_T_Unit = $V[7]; + $data_T_UnitPrice = $V[8]; + $data_T_quantity = $V[9]; + $data_T_carriage = $V[10]; + + $data_s_name = $V[11]; + $data_s_addr = $V[12]; + $data_s_postcode = $V[13]; + $data_s_tel = $V[14]; + $data_s_eml = $V[15]; + + $data_r_name = $V[16]; + $data_r_addr = $V[17]; + $data_r_postcode = $V[18]; + $data_r_tel = $V[19]; + $data_r_eml = $V[20]; + + $data_m_ocomment = $V[21]; + $data_m_status = $V[22]; + $data_m_odate = $V[23]; + + $data_m_serial = $V[24]; + + /* + if ($data_m_status == 2) + { + echo '验证成功!' . '

    '; + echo '商 家 号 =' . $data_m_id . '
    '; + echo '支付订单 =' . $data_m_orderid . '
    '; + echo '支付金额 =' . $data_m_oamount . '
    '; + echo '币 种   =' . $data_m_ocurrency . '
    '; + echo '结果地址 =' . $data_m_url . '
    '; + echo '语言选择 =' . $data_m_language . '
    '; + + echo '商品名称 =' . $data_T_TradeName . '
    '; + echo '商品单位 =' . $data_T_Unit . '
    '; + echo '商品单价 =' . $data_T_UnitPrice . '
    '; + echo '商品数量 =' . $data_T_quantity . '
    '; + echo '商品运费 =' . $data_T_carriage . '
    '; + + echo '消费者姓名 =' . $data_s_name . '
    '; + echo '消费者住址 =' . $data_s_addr . '
    '; + echo '消费者邮码 =' . $data_s_postcode . '
    '; + echo '消费者电话 =' . $data_s_tel . '
    '; + echo '消费者邮件 =' . $data_s_eml . '
    '; + + echo '收货姓名 =' . $data_r_name . '
    '; + echo '收货住址 =' . $data_r_addr . '
    '; + echo '收货编码 =' . $data_r_postcode . '
    '; + echo '收货电话 =' . $data_r_tel . '
    '; + echo '收货邮件 =' . $data_r_eml . '
    '; + + echo '备 注 =' . $data_m_ocomment . '
    '; + echo '支付状态 =' . $data_m_status . '
    '; + echo '支付日期 =' . $data_m_odate . '
    '; + + echo '系统参考号 =' . $data_m_serial . '
    '; + + echo '
    返回的认证结果: '; + } + else + { + echo '支付失败!
    '; + } + */ + + switch ($data_m_status) + { + case '0': + //echo '0.未支付'; + break; + case '2': + //echo '2.支付成功'; + $get_PayResult = true; + order_paid($data_m_orderid, PS_PAYED); //修改订单状态 + break; + case '3': + //echo '3.支付失败'; + break; + default: + //echo '支付状态 错误'; + break; + } + } + else + { + //echo '失败,信息可能被篡改'; + } + + return $get_PayResult; + } +} + +?> \ No newline at end of file diff --git a/includes/modules/payment/paypal.php b/includes/modules/payment/paypal.php new file mode 100644 index 0000000..5ddea96 --- /dev/null +++ b/includes/modules/payment/paypal.php @@ -0,0 +1,229 @@ + 'paypal_account', 'type' => 'text', 'value' => ''), + array('name' => 'paypal_currency', 'type' => 'select', 'value' => 'USD') + ); + + return; +} + +/** + * 类 + */ +class paypal +{ + /** + * 构造函数 + * + * @access public + * @param + * + * @return void + */ + function paypal() + { + } + + function __construct() + { + $this->paypal(); + } + + /** + * 生成支付代码 + * @param array $order 订单信息 + * @param array $payment 支付方式信息 + */ + function get_code($order, $payment) + { + $data_order_id = $order['log_id']; + $data_amount = $order['order_amount']; + $data_return_url = return_url(basename(__FILE__, '.php')); + $data_pay_account = $payment['paypal_account']; + $currency_code = $payment['paypal_currency']; + $data_notify_url = return_url(basename(__FILE__, '.php')); + $cancel_return = $GLOBALS['ecs']->url(); + + $def_url = '
    ' . // 不能省略 + "" . // 不能省略 + "" . // 贝宝帐号 + "" . // payment for + "" . // 订单金额 + "" . // 货币 + "" . // 付款后页面 + "" . // 订单号 + "" . // 字符集 + "" . // 不要求客户提供收货地址 + "" . // 付款说明 + "" . + "" . + "" . + "" . // 按钮 + "

    "; + + return $def_url; + } + + /** + * 响应操作 + */ + function respond() + { + $payment = get_payment('paypal'); + $merchant_id = $payment['paypal_account']; ///获取商户编号 + + // read the post from PayPal system and add 'cmd' + $req = 'cmd=_notify-validate'; + foreach ($_POST as $key => $value) + { + $value = urlencode(stripslashes($value)); + $req .= "&$key=$value"; + } + + // post back to PayPal system to validate + $header = "POST /cgi-bin/webscr HTTP/1.0\r\n"; + $header .= "Content-Type: application/x-www-form-urlencoded\r\n"; + $header .= "Content-Length: " . strlen($req) ."\r\n\r\n"; + $fp = fsockopen ('www.paypal.com', 80, $errno, $errstr, 30); + + // assign posted variables to local variables + $item_name = $_POST['item_name']; + $item_number = $_POST['item_number']; + $payment_status = $_POST['payment_status']; + $payment_amount = $_POST['mc_gross']; + $payment_currency = $_POST['mc_currency']; + $txn_id = $_POST['txn_id']; + $receiver_email = $_POST['receiver_email']; + $payer_email = $_POST['payer_email']; + $order_sn = $_POST['invoice']; + $memo = !empty($_POST['memo']) ? $_POST['memo'] : ''; + $action_note = $txn_id . '(' . $GLOBALS['_LANG']['paypal_txn_id'] . ')' . $memo; + + if (!$fp) + { + fclose($fp); + + return false; + } + else + { + fputs($fp, $header . $req); + while (!feof($fp)) + { + $res = fgets($fp, 1024); + if (strcmp($res, 'VERIFIED') == 0) + { + // check the payment_status is Completed + if ($payment_status != 'Completed' && $payment_status != 'Pending') + { + fclose($fp); + + return false; + } + + // check that txn_id has not been previously processed + /*$sql = "SELECT COUNT(*) FROM " . $GLOBALS['ecs']->table('order_action') . " WHERE action_note LIKE '" . mysql_like_quote($txn_id) . "%'"; + if ($GLOBALS['db']->getOne($sql) > 0) + { + fclose($fp); + + return false; + }*/ + + // check that receiver_email is your Primary PayPal email + if ($receiver_email != $merchant_id) + { + fclose($fp); + + return false; + } + + // check that payment_amount/payment_currency are correct + $sql = "SELECT order_amount FROM " . $GLOBALS['ecs']->table('pay_log') . " WHERE log_id = '$order_sn'"; + if ($GLOBALS['db']->getOne($sql) != $payment_amount) + { + fclose($fp); + + return false; + } + if ($payment['paypal_currency'] != $payment_currency) + { + fclose($fp); + + return false; + } + + // process payment + order_paid($order_sn, PS_PAYED, $action_note); + fclose($fp); + + return true; + } + elseif (strcmp($res, 'INVALID') == 0) + { + // log for manual investigation + fclose($fp); + + return false; + } + } + } + } +} + +?> \ No newline at end of file diff --git a/includes/modules/payment/paypal_ec.php b/includes/modules/payment/paypal_ec.php new file mode 100644 index 0000000..4de82d7 --- /dev/null +++ b/includes/modules/payment/paypal_ec.php @@ -0,0 +1,268 @@ + 'paypal_ec_username', 'type' => 'text', 'value' => ''), + array('name' => 'paypal_ec_password', 'type' => 'text', 'value' => ''), + array('name' => 'paypal_ec_signature', 'type' => 'text', 'value' => ''), + array('name' => 'paypal_ec_currency', 'type' => 'select', 'value' => 'USD') + ); + + return; +} + +/** + * 类 + */ +class paypal_ec +{ + + + /** + * 构造函数 + * + * @access public + * @param + * + * @return void + */ + function paypal_ec() + { + + } + + function __construct() + { + $this->paypal_ec(); + } + + + + /** + * 生成支付代码 + * @param array $order 订单信息 + * @param array $payment 支付方式信息 + */ + function get_code($order, $payment) + { + + $token = ''; + $serverName = $_SERVER['SERVER_NAME']; + $serverPort = $_SERVER['SERVER_PORT']; + $url=dirname('http://'.$serverName.':'.$serverPort.$_SERVER['REQUEST_URI']); + $paymentAmount=$order['order_amount']; + $currencyCodeType=$payment['paypal_ec_currency']; + $paymentType='Sale'; + $data_order_id = $order['log_id']; + + $_SESSION['paypal_username']=$payment['paypal_ec_username']; + $_SESSION['paypal_password']=$payment['paypal_ec_password']; + $_SESSION['paypal_signature']=$payment['paypal_ec_signature']; + + $returnURL =urlencode($url.'/respond.php?code=paypal_ec¤cyCodeType='.$currencyCodeType.'&paymentType='.$paymentType.'&paymentAmount='.$paymentAmount.'&invoice='.$data_order_id); + $cancelURL =urlencode("$url/SetExpressCheckout.php?paymentType=$paymentType" ); + + $nvpstr="&Amt=".$paymentAmount."&PAYMENTACTION=".$paymentType."&ReturnUrl=".$returnURL."&CANCELURL=".$cancelURL ."&CURRENCYCODE=".$currencyCodeType ."&ButtonSource=ECSHOP_cart_EC_C2"; + + $resArray=$this->hash_call("SetExpressCheckout",$nvpstr); + + $_SESSION['reshash']=$resArray; + if(isset($resArray["ACK"])) + { + $ack = strtoupper($resArray["ACK"]); + } + + if (isset($resArray["TOKEN"])) + { + $token = urldecode($resArray["TOKEN"]); + } + $payPalURL = PAYPAL_URL.$token; + $button = '
    '; + + return $button; + } + + /** + * 响应操作 + */ + function respond() + { + $order_sn = $_REQUEST['invoice']; + $token =urlencode( $_REQUEST['token']); + $nvpstr="&TOKEN=".$token; + $resArray=$this->hash_call("GetExpressCheckoutDetails",$nvpstr); + $_SESSION['reshash']=$resArray; + $ack = strtoupper($resArray["ACK"]); + if($ack=="SUCCESS") + { + $_SESSION['token']=$_REQUEST['token']; + $_SESSION['payer_id'] = $_REQUEST['PayerID']; + + $_SESSION['paymentAmount']=$_REQUEST['paymentAmount']; + $_SESSION['currCodeType']=$_REQUEST['currencyCodeType']; + $_SESSION['paymentType']=$_REQUEST['paymentType']; + + $resArray=$_SESSION['reshash']; + $token =urlencode( $_SESSION['token']); + + $paymentAmount =urlencode ($_SESSION['paymentAmount']); + $paymentType = urlencode($_SESSION['paymentType']); + $currCodeType = urlencode($_SESSION['currCodeType']); + $payerID = urlencode($_SESSION['payer_id']); + $serverName = urlencode($_SERVER['SERVER_NAME']); + + $nvpstr='&TOKEN='.$token.'&PAYERID='.$payerID.'&PAYMENTACTION='.$paymentType.'&AMT='.$paymentAmount.'&CURRENCYCODE='.$currCodeType.'&IPADDRESS='.$serverName ; + + $resArray=$this->hash_call("DoExpressCheckoutPayment",$nvpstr); + + $ack = strtoupper($resArray["ACK"]); + if($ack=="SUCCESS") + { + /* 改变订单状态 */ + order_paid($order_sn, 2); + return true; + } + else + { + return false; + } + } + else + { + return false; + } + } + + function hash_call($methodName,$nvpStr) + { + global $API_Endpoint; + $version='53.0'; + $API_UserName=$_SESSION['paypal_username']; + $API_Password=$_SESSION['paypal_password']; + $API_Signature=$_SESSION['paypal_signature']; + $nvp_Header; + + $ch = curl_init(); + + curl_setopt($ch, CURLOPT_URL,$API_Endpoint); + curl_setopt($ch, CURLOPT_VERBOSE, 1); + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); + curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); + curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); + curl_setopt($ch, CURLOPT_POST, 1); + + if(USE_PROXY) + { + curl_setopt ($ch, CURLOPT_PROXY, PROXY_HOST.":".PROXY_PORT); + } + + $nvpreq="METHOD=".urlencode($methodName)."&VERSION=".urlencode($version)."&PWD=".urlencode($API_Password)."&USER=".urlencode($API_UserName)."&SIGNATURE=".urlencode($API_Signature).$nvpStr; + + curl_setopt($ch,CURLOPT_POSTFIELDS,$nvpreq); + + $response = curl_exec($ch); + + $nvpResArray=$this->deformatNVP($response); + + $nvpReqArray=$this->deformatNVP($nvpreq); + + $_SESSION['nvpReqArray']=$nvpReqArray; + + if (curl_errno($ch)) + { + $_SESSION['curl_error_no']=curl_errno($ch) ; + $_SESSION['curl_error_msg']=curl_error($ch); + } + else + { + curl_close($ch); + } + + return $nvpResArray; + } + + + function deformatNVP($nvpstr) + { + + $intial=0; + $nvpArray = array(); + + while(strlen($nvpstr)) + { + $keypos= strpos($nvpstr,'='); + $valuepos = strpos($nvpstr,'&') ? strpos($nvpstr,'&'): strlen($nvpstr); + $keyval=substr($nvpstr,$intial,$keypos); + $valval=substr($nvpstr,$keypos+1,$valuepos-$keypos-1); + $nvpArray[urldecode($keyval)] =urldecode( $valval); + $nvpstr=substr($nvpstr,$valuepos+1,strlen($nvpstr)); + } + + return $nvpArray; + } + +} + +?> \ No newline at end of file diff --git a/includes/modules/payment/paypalcn.php b/includes/modules/payment/paypalcn.php new file mode 100644 index 0000000..3a89934 --- /dev/null +++ b/includes/modules/payment/paypalcn.php @@ -0,0 +1,226 @@ + 'paypalcn_account', 'type' => 'text', 'value' => ''), + ); + + return; +} + +/** + * 类 + */ +class paypalcn +{ + /** + * 构造函数 + * + * @access public + * @param + * + * @return void + */ + function paypalcn() + { + } + + function __construct() + { + $this->paypalcn(); + } + + /** + * 生成支付代码 + * @param array $order 订单信息 + * @param array $payment 支付方式信息 + */ + function get_code($order, $payment) + { + $data_order_id = $order['log_id']; + $data_amount = $order['order_amount']; + $data_return_url = return_url(basename(__FILE__, '.php')); + $data_pay_account = $payment['paypalcn_account']; + $data_notify_url = return_url(basename(__FILE__, '.php')); + $cancel_return = $GLOBALS['ecs']->url(); + + $def_url = '
    ' . // 不能省略 + "" . // 不能省略 + "" . // 贝宝帐号 + "" . // 付款后页面 + "" . // 订单金额 + "" . // 订单号 + "" . // 字符集 + "" . // 不要求客户提供收货地址 + "" . // 付款说明 + "" . // 货币:人民币 + "" . + "" . + "" . + "" . // 按钮 + "

    "; + + return $def_url; + } + + /** + * 响应操作 + */ + function respond() + { + $payment = get_payment('paypalcn'); + $merchant_id = $payment['paypalcn_account']; ///获取商户编号 + + // read the post from PayPal system and add 'cmd' + $req = 'cmd=_notify-validate'; + foreach ($_POST as $key => $value) + { + $value = urlencode(stripslashes($value)); + $req .= "&$key=$value"; + } + + // post back to PayPal system to validate + $header = "POST /cgi-bin/webscr HTTP/1.0\r\n"; + $header .= "Content-Type: application/x-www-form-urlencoded\r\n"; + $header .= "Content-Length: " . strlen($req) ."\r\n\r\n"; + $fp = fsockopen ('www.paypal.com', 80, $errno, $errstr, 30); + + // assign posted variables to local variables + $item_name = $_POST['item_name']; + $item_number = $_POST['item_number']; + $payment_status = $_POST['payment_status']; + $payment_amount = $_POST['mc_gross']; + $payment_currency = $_POST['mc_currency']; + $txn_id = $_POST['txn_id']; + $receiver_email = $_POST['receiver_email']; + $payer_email = $_POST['payer_email']; + $order_sn = $_POST['invoice']; + $memo = !empty($_POST['memo']) ? $_POST['memo'] : ''; + $action_note = $txn_id . '(' . $GLOBALS['_LANG']['paypal_txn_id'] . ')' . $memo; + + if (!$fp) + { + fclose($fp); + + return false; + } + else + { + fputs($fp, $header . $req); + while (!feof($fp)) + { + $res = fgets($fp, 1024); + if (strcmp($res, 'VERIFIED') == 0) + { + // check the payment_status is Completed + if ($payment_status != 'Completed' && $payment_status != 'Pending') + { + fclose($fp); + + return false; + } + + // check that txn_id has not been previously processed + /*$sql = "SELECT COUNT(*) FROM " . $GLOBALS['ecs']->table('order_action') . " WHERE action_note LIKE '" . mysql_like_quote($txn_id) . "%'"; + if ($GLOBALS['db']->getOne($sql) > 0) + { + fclose($fp); + + return false; + }*/ + + // check that receiver_email is your Primary PayPal email + if ($receiver_email != $merchant_id) + { + fclose($fp); + + return false; + } + + // check that payment_amount/payment_currency are correct + $sql = "SELECT order_amount FROM " . $GLOBALS['ecs']->table('pay_log') . " WHERE log_id = '$order_sn'"; + if ($GLOBALS['db']->getOne($sql) != $payment_amount) + { + fclose($fp); + + return false; + } + if ($payment_currency != 'CNY') + { + fclose($fp); + + return false; + } + + // process payment + order_paid($order_sn, PS_PAYED, $action_note); + fclose($fp); + + return true; + } + elseif (strcmp($res, 'INVALID') == 0) + { + // log for manual investigation + fclose($fp); + + return false; + } + } + } + } +} + +?> \ No newline at end of file diff --git a/includes/modules/payment/post.php b/includes/modules/payment/post.php new file mode 100644 index 0000000..18ff2eb --- /dev/null +++ b/includes/modules/payment/post.php @@ -0,0 +1,101 @@ +post(); + } + + /** + * 提交函数 + */ + function get_code() + { + return ''; + } + + /** + * 处理函数 + */ + function response() + { + return; + } +} + +?> \ No newline at end of file diff --git a/includes/modules/payment/shenzhou.php b/includes/modules/payment/shenzhou.php new file mode 100644 index 0000000..c94bd37 --- /dev/null +++ b/includes/modules/payment/shenzhou.php @@ -0,0 +1,309 @@ + 'shenzhou_account', 'type' => 'text', 'value' => ''), + array('name' => 'shenzhou_key', 'type' => 'text', 'value' => ''), + ); + + return; + +} + +class shenzhou +{ + /** + * 构造函数 + * + * @access public + * @param + * + * @return void + */ + + function shenzhou() + { + } + + function __construct() + { + $this->shenzhou(); + } + + /** + * 生成支付代码 + * @param array $order 订单信息 + * @param array $payment 支付方式信息 + */ + function get_code($order, $payment) + { + $merchant_acctid = trim($payment['shenzhou_account']); //快钱神州行账号 不可空 + $key = trim($payment['shenzhou_key']); //密钥 不可空 + $input_charset = 1; //字符集 默认1=utf-8 + $bg_url = ''; + $page_url = $GLOBALS['ecs']->url() . 'respond.php'; + $version = 'v2.0'; + $language = 1; + $sign_type = 1; //签名类型 不可空 固定值 1:md5 + $payer_name = ''; + $payer_contact_type = ''; + $payer_contact = ''; + $order_id = $order['order_sn']; //商户订单号 不可空 + $order_amount = $order['order_amount'] * 100; //商户订单金额 不可空 + $pay_type = '00'; //支付方式 不可空 + $card_number = ''; + $card_pwd = ''; + $full_amount_flag = '0'; + $order_time = local_date('YmdHis', $order['add_time']); //商户订单提交时间 不可空 14位 + $product_name = ''; + $product_num = ''; + $product_id = ''; + $product_desc = ''; + $ext1 = $order['log_id']; + $ext2 = 'ecshop'; + + /* 生成加密签名串 请务必按照如下顺序和规则组成加密串!*/ + $signmsgval = ''; + $signmsgval = $this->append_param($signmsgval, "inputCharset", $input_charset); + $signmsgval = $this->append_param($signmsgval, "bgUrl", $bg_url); + $signmsgval = $this->append_param($signmsgval, "pageUrl", $page_url); + $signmsgval = $this->append_param($signmsgval, "version", $version); + $signmsgval = $this->append_param($signmsgval, "language", $language); + $signmsgval = $this->append_param($signmsgval, "signType", $sign_type); + $signmsgval = $this->append_param($signmsgval, "merchantAcctId", $merchant_acctid); + $signmsgval = $this->append_param($signmsgval, "payerName", urlencode($payer_name)); + $signmsgval = $this->append_param($signmsgval, "payerContactType", $payer_contact_type); + $signmsgval = $this->append_param($signmsgval, "payerContact", $payer_contact); + $signmsgval = $this->append_param($signmsgval, "orderId", $order_id); + $signmsgval = $this->append_param($signmsgval, "orderAmount", $order_amount); + $signmsgval = $this->append_param($signmsgval, "payType", $pay_type); + $signmsgval = $this->append_param($signmsgval, "cardNumber", $card_number); + $signmsgval = $this->append_param($signmsgval, "cardPwd", $card_pwd); + $signmsgval = $this->append_param($signmsgval, "fullAmountFlag", $full_amount_flag); + $signmsgval = $this->append_param($signmsgval, "orderTime", $order_time); + $signmsgval = $this->append_param($signmsgval, "productName", urlencode($product_name)); + $signmsgval = $this->append_param($signmsgval, "productNum", $product_num); + $signmsgval = $this->append_param($signmsgval, "productId", $product_id); + $signmsgval = $this->append_param($signmsgval, "productDesc", urlencode($product_desc)); + $signmsgval = $this->append_param($signmsgval, "ext1", urlencode($ext1)); + $signmsgval = $this->append_param($signmsgval, "ext2", urlencode($ext2)); + $signmsgval = $this->append_param($signmsgval, "key", $key); + $sign_msg = strtoupper(md5($signmsgval)); //安全校验域 不可空 + + $def_url = '
    '; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= ""; + $def_url .= "

    "; + + return $def_url; + } + + /** + * 响应操作 + */ + function respond() + { + $payment = get_payment(basename(__FILE__, '.php')); + $merchant_acctid = $payment['shenzhou_account']; //收款帐号 不可空 + $key = $payment['shenzhou_key']; + $get_merchant_acctid = trim($_REQUEST['merchantAcctId']); //接收的收款帐号 + $pay_result = trim($_REQUEST['payResult']); + $version = trim($_REQUEST['version']); + $language = trim($_REQUEST['language']); + $sign_type = trim($_REQUEST['signType']); + $pay_type = trim($_REQUEST['payType']); //20代表神州行卡密直接支付;22代表快钱账户神州行余额支付 + $card_umber = trim($_REQUEST['cardNumber']); + $card_pwd = trim($_REQUEST['cardPwd']); + $order_id = trim($_REQUEST['orderId']); //订单号 + $order_time = trim($_REQUEST['orderTime']); + $order_amount = trim($_REQUEST['orderAmount']); + $deal_id = trim($_REQUEST['dealId']); //获取该交易在快钱的交易号 + $ext1 = trim($_REQUEST['ext1']); + $ext2 = trim($_REQUEST['ext2']); + $pay_amount = trim($_REQUEST['payAmount']); //获取实际支付金额 + $bill_order_time = trim($_REQUEST['billOrderTime']); + $pay_result = trim($_REQUEST['payResult']); //10代表支付成功; 11代表支付失败 + $sign_type = trim($_REQUEST['signType']); + $sign_msg = trim($_REQUEST['signMsg']); + + //生成加密串。必须保持如下顺序。 + $merchant_signmsgval = $this->append_param($merchant_signmsgval, "merchantAcctId", $merchant_acctid); + $merchant_signmsgval = $this->append_param($merchant_signmsgval, "version", $version); + $merchant_signmsgval = $this->append_param($merchant_signmsgval, "language", $language); + $merchant_signmsgval = $this->append_param($merchant_signmsgval, "payType", $pay_type); + $merchant_signmsgval = $this->append_param($merchant_signmsgval, "cardNumber", $card_number); + $merchant_signmsgval = $this->append_param($merchant_signmsgval, "cardPwd", $card_pwd); + $merchant_signmsgval = $this->append_param($merchant_signmsgval, "orderId", $order_id); + $merchant_signmsgval = $this->append_param($merchant_signmsgval, "orderAmount", $order_amount); + $merchant_signmsgval = $this->append_param($merchant_signmsgval, "dealId", $deal_id); + $merchant_signmsgval = $this->append_param($merchant_signmsgval, "orderTime", $order_time); + $merchant_signmsgval = $this->append_param($merchant_signmsgval, "ext1", $ext1); + $merchant_signmsgval = $this->append_param($merchant_signmsgval, "ext2", $ext2); + $merchant_signmsgval = $this->append_param($merchant_signmsgval, "payAmount", $pay_amount); + $merchant_signmsgval = $this->append_param($merchant_signmsgval, "billOrderTime", $bill_order_time); + $merchant_signmsgval = $this->append_param($merchant_signmsgval, "payResult", $pay_result); + $merchant_signmsgval = $this->append_param($merchant_signmsgval, "signType", $sign_type); + $merchant_signmsgval = $this->append_param($merchant_signmsgval, "key", $key); + $merchant_signmsg = md5($merchant_signmsgval); + + //首先对获得的商户号进行比对 + if ($get_merchant_acctid != $merchant_acctid) + { + //'商户号错误'; + return false; + } + + if (strtoupper($sign_msg) == strtoupper($merchant_signmsg)) + { + if ($pay_result == 10) //有成功支付的结果返回10 + { + order_paid($ext1); + + return true; + } + elseif ($pay_result == 11 && $pay_amount > 0) + { + $sql = "SELECT order_amount FROM " . $GLOBALS['ecs']->table('order_info') ."WHERE order_id = '$order_id'"; + $get_order_amount = $GLOBALS['db']->getOne($sql); + if ($get_order_amount == $pay_amount && $get_order_amount == $order_amount) //检查订单金额、实际支付金额和订单是否相等 + { + order_paid($ext1); + + return true; + } + elseif ($get_order_amount == $order_amount && $pay_amount > 0) //订单金额相等 实际支付金额 > 0的情况 + { + $surplus_amount = $get_order_amount - $pay_amount; //计算订单剩余金额 + $sql = 'UPDATE' . $GLOBALS['ecs']->table('order_info') . "SET `money_paid` = (money_paid + '$pay_amount')," . + " order_amount = (order_amount - '$pay_amount') WHERE order_id = '$order_id'"; + $result = $GLOBALS['db']->query($sql); + $sql = 'UPDATE' . $GLOBALS['ecs']->table('order_info') . "SET `order_status` ='" . OS_CONFIRMED . "' WHERE order_id = '$orderId'"; + $result = $GLOBALS['db']->query($sql); + //order_paid($orderId, PS_UNPAYED); + //'订单金额小于0'; + return false; + } + else + { + //'订单金额不相等'; + return false; + } + } + else + { + //'实际支付金额不能小于0'; + return false; + } + } + else + { + //'签名校对错误'; + return false; + } + } + + /** + * 将变量值不为空的参数组成字符串 + * @param string $strs 参数字符串 + * @param string $key 参数键名 + * @param string $val 参数键对应值 + */ + function append_param($strs,$key,$val) + { + if($strs != "") + { + if($val != "") + { + $strs .= '&' . $key . '=' . $val; + } + } + else + { + if($val != "") + { + $strs = $key . '=' . $val; + } + } + + return $strs; + } +} + +?> \ No newline at end of file diff --git a/includes/modules/payment/tenpay.php b/includes/modules/payment/tenpay.php new file mode 100644 index 0000000..e586a49 --- /dev/null +++ b/includes/modules/payment/tenpay.php @@ -0,0 +1,242 @@ + 'tenpay_account', 'type' => 'text', 'value' => ''), + array('name' => 'tenpay_key', 'type' => 'text', 'value' => ''), + array('name' => 'magic_string', 'type' => 'text', 'value' => '') + ); + + return; +} + +/** + * 类 + */ +class tenpay +{ + /** + * 构造函数 + * + * @access public + * @param + * + * @return void + */ + function tenpay() + { + } + + function __construct() + { + $this->tenpay(); + } + + /** + * 生成支付代码 + * @param array $order 订单信息 + * @param array $payment 支付方式信息 + */ + function get_code($order, $payment) + { + $cmd_no = '1'; + + /* 获得订单的流水号,补零到10位 */ + $sp_billno = $order['order_sn']; + + /* 交易日期 */ + $today = date('Ymd'); + + /* 将商户号+年月日+流水号 */ + $bill_no = str_pad($order['log_id'], 10, 0, STR_PAD_LEFT); + $transaction_id = $payment['tenpay_account'].$today.$bill_no; + + /* 银行类型:支持纯网关和财付通 */ + $bank_type = '0'; + + /* 订单描述,用订单号替代 */ + if (!empty($order['order_id'])) + { + //$desc = get_goods_name_by_id($order['order_id']); + $desc = $order['order_sn']; + $attach = ''; + } + else + { + $desc = $GLOBALS['_LANG']['account_voucher']; + $attach = 'voucher'; + } + /* 编码标准 */ + if (!defined('EC_CHARSET') || EC_CHARSET == 'utf-8') + { + $desc = ecs_iconv('utf-8', 'gbk', $desc); + } + + /* 返回的路径 */ + $return_url = return_url('tenpay'); + + /* 总金额 */ + $total_fee = floatval($order['order_amount']) * 100; + + /* 货币类型 */ + $fee_type = '1'; + + /* 财付通风险防范参数 */ + $spbill_create_ip = $_SERVER['REMOTE_ADDR']; + + /* 数字签名 */ + $sign_text = "cmdno=" . $cmd_no . "&date=" . $today . "&bargainor_id=" . $payment['tenpay_account'] . + "&transaction_id=" . $transaction_id . "&sp_billno=" . $sp_billno . + "&total_fee=" . $total_fee . "&fee_type=" . $fee_type . "&return_url=" . $return_url . + "&attach=" . $attach . "&spbill_create_ip=" . $spbill_create_ip . "&key=" . $payment['tenpay_key']; + $sign = strtoupper(md5($sign_text)); + + /* 交易参数 */ + $parameter = array( + 'cmdno' => $cmd_no, // 业务代码, 财付通支付支付接口填 1 + 'date' => $today, // 商户日期:如20051212 + 'bank_type' => $bank_type, // 银行类型:支持纯网关和财付通 + 'desc' => $desc, // 交易的商品名称 + 'purchaser_id' => '', // 用户(买方)的财付通帐户,可以为空 + 'bargainor_id' => $payment['tenpay_account'], // 商家的财付通商户号 + 'transaction_id' => $transaction_id, // 交易号(订单号),由商户网站产生(建议顺序累加) + 'sp_billno' => $sp_billno, // 商户系统内部的定单号,最多10位 + 'total_fee' => $total_fee, // 订单金额 + 'fee_type' => $fee_type, // 现金支付币种 + 'return_url' => $return_url, // 接收财付通返回结果的URL + 'attach' => $attach, // 用户自定义签名 + 'sign' => $sign, // MD5签名 + 'spbill_create_ip' => $spbill_create_ip, //财付通风险防范参数 + 'sys_id' => '542554970', //ecshop C账号 不参与签名 + 'sp_suggestuser' => '1202822001' //财付通分配的商户号 + + ); + + $button = '
    '; + + foreach ($parameter AS $key=>$val) + { + $button .= ""; + } + + $button .= '

    '; + + return $button; + } + + /** + * 响应操作 + */ + function respond() + { + /*取返回参数*/ + $cmd_no = $_GET['cmdno']; + $pay_result = $_GET['pay_result']; + $pay_info = $_GET['pay_info']; + $bill_date = $_GET['date']; + $bargainor_id = $_GET['bargainor_id']; + $transaction_id = $_GET['transaction_id']; + $sp_billno = $_GET['sp_billno']; + $total_fee = $_GET['total_fee']; + $fee_type = $_GET['fee_type']; + $attach = $_GET['attach']; + $sign = $_GET['sign']; + + $payment = get_payment('tenpay'); + //$order_sn = $bill_date . str_pad(intval($sp_billno), 5, '0', STR_PAD_LEFT); + //$log_id = preg_replace('/0*([0-9]*)/', '\1', $sp_billno); //取得支付的log_id + if ($attach == 'voucher') + { + $log_id = get_order_id_by_sn($sp_billno, "true"); + } + else + { + $log_id = get_order_id_by_sn($sp_billno); + } + + /* 如果pay_result大于0则表示支付失败 */ + if ($pay_result > 0) + { + return false; + } + + /* 检查支付的金额是否相符 */ + if (!check_money($log_id, $total_fee / 100)) + { + return false; + } + + /* 检查数字签名是否正确 */ + $sign_text = "cmdno=" . $cmd_no . "&pay_result=" . $pay_result . + "&date=" . $bill_date . "&transaction_id=" . $transaction_id . + "&sp_billno=" . $sp_billno . "&total_fee=" . $total_fee . + "&fee_type=" . $fee_type . "&attach=" . $attach . + "&key=" . $payment['tenpay_key']; + $sign_md5 = strtoupper(md5($sign_text)); + if ($sign_md5 != $sign) + { + return false; + } + else + { + /* 改变订单状态 */ + order_paid($log_id); + return true; + } + } +} + +?> \ No newline at end of file diff --git a/includes/modules/payment/tenpayc2c.php b/includes/modules/payment/tenpayc2c.php new file mode 100644 index 0000000..bd98a55 --- /dev/null +++ b/includes/modules/payment/tenpayc2c.php @@ -0,0 +1,257 @@ + 'tenpay_account', 'type' => 'text', 'value' => ''), + array('name' => 'tenpay_key', 'type' => 'text', 'value' => ''), + array('name' => 'tenpay_type', 'type' => 'select', 'value'=>'1'), + ); + + return; +} + +/** + * 类 + */ +class tenpayc2c +{ + /** + * 构造函数 + * + * @access public + * @param + * + * @return void + */ + function tenpayc2c() + { + } + + function __construct() + { + $this->tenpayc2c(); + } + + /** + * 生成支付代码 + * @param array $order 订单信息 + * @param array $payment 支付方式信息 + */ + function get_code($order, $payment) + { + /* 版本号 */ + $version = '2'; + + /* 任务代码,定值:12 */ + $cmdno = '12'; + + /* 编码标准 */ + if (!defined('EC_CHARSET')) + { + $encode_type = 2; + } + else + { + if (EC_CHARSET == 'utf-8') + { + $encode_type = 2; + } + else + { + $encode_type = 1; + } + } + + /* 平台提供者,代理商的财付通账号 */ + $chnid = $payment['tenpay_account']; + + /* 收款方财付通账号 */ + $seller = $payment['tenpay_account']; + + /* 商品名称 */ + if (!empty($order['order_id'])) + { + //$mch_name = get_goods_name_by_id($order['order_id']); + $mch_name = $order['order_sn']; + } + else + { + $mch_name = $GLOBALS['_LANG']['account_voucher']; + } + + /* 总金额 */ + $mch_price = floatval($order['order_amount']) * 100; + + /* 物流配送说明 */ + $transport_desc = ''; + $transport_fee = ''; + + /* 交易说明 */ + $mch_desc = $GLOBALS['_LANG']['shop_order_sn'] . $order['order_sn']; + $need_buyerinfo = '2' ; + + /* 交易类型:2、虚拟交易,1、实物交易 */ + $mch_type = $payment['tenpay_type']; + + /* 获得订单的流水号,补零到10位 */ + $mch_vno = $order['order_sn']; + + /* 返回的路径 */ + $mch_returl = return_url('tenpayc2c'); + $show_url = return_url('tenpayc2c'); + $attach = ''; + + /* 数字签名 */ + $sign_text = "chnid=" . $chnid . "&cmdno=" . $cmdno . "&encode_type=" . $encode_type . "&mch_desc=" . $mch_desc . "&mch_name=" . $mch_name . "&mch_price=" . $mch_price ."&mch_returl=" . $mch_returl . "&mch_type=" . $mch_type . "&mch_vno=" . $mch_vno . "&need_buyerinfo=" . $need_buyerinfo ."&seller=" . $seller . "&show_url=" . $show_url . "&version=" . $version . "&key=" . $payment['tenpay_key']; + + $sign =md5($sign_text); + + /* 交易参数 */ + $parameter = array( + 'attach' => $attach, + 'chnid' => $chnid, + 'cmdno' => $cmdno, // 业务代码, 财付通支付支付接口填 1 + 'encode_type' => $encode_type, //编码标准 + 'mch_desc' => $mch_desc, + 'mch_name' => $mch_name, + 'mch_price' => $mch_price, // 订单金额 + 'mch_returl' => $mch_returl, // 接收财付通返回结果的URL + 'mch_type' => $mch_type, //交易类型 + 'mch_vno' => $mch_vno, // 交易号(订单号),由商户网站产生(建议顺序累加) + 'need_buyerinfo' => $need_buyerinfo, //是否需要在财付通填定物流信息 + 'seller' => $seller, // 商家的财付通商户号 + 'show_url' => $show_url, + 'transport_desc' => $transport_desc, + 'transport_fee' => $transport_fee, + 'version' => $version, //版本号 2 + 'sign' => $sign, // MD5签名 + 'sys_id' => '542554970' //ecshop C账号 不参与签名 + ); + + $button = '
    '; + + foreach ($parameter AS $key=>$val) + { + $button .= ""; + } + + $button .= '

    '; + + return $button; + } + + /** + * 响应操作 + */ + function respond() + { + /*取返回参数*/ + $cmd_no = $_GET['cmdno']; + $retcode = $_GET['retcode']; + $status = $_GET['status']; + $seller = $_GET['seller']; + $total_fee = $_GET['total_fee']; + $trade_price = $_GET['trade_price']; + $transport_fee = $_GET['transport_fee']; + $buyer_id = $_GET['buyer_id']; + $chnid = $_GET['chnid']; + $cft_tid = $_GET['cft_tid']; + $mch_vno = $_GET['mch_vno']; + $attach = !empty($_GET['attach']) ? $_GET['attach'] : ''; + $version = $_GET['version']; + $sign = $_GET['sign']; + + $payment = get_payment('tenpayc2c'); + $log_id = get_order_id_by_sn($mch_vno); + //$log_id = str_replace($attach, '', $mch_vno); //取得支付的log_id + + /* 如果$retcode大于0则表示支付失败 */ + if ($retcode > 0) + { + //echo '操作失败'; + return false; + } + + /* 检查支付的金额是否相符 */ + if (!check_money($log_id, $total_fee / 100)) + { + //echo '金额不相等'; + return false; + } + + /* 检查数字签名是否正确 */ + $sign_text = "buyer_id=" . $buyer_id . "&cft_tid=" . $cft_tid . "&chnid=" . $chnid . "&cmdno=" . $cmd_no . "&mch_vno=" . $mch_vno . "&retcode=" . $retcode . "&seller=" .$seller . "&status=" . $status . "&total_fee=" . $total_fee . "&trade_price=" . $trade_price . "&transport_fee=" . $transport_fee . "&version=" . $version . "&key=" . $payment['tenpay_key']; + $sign_md5 = strtoupper(md5($sign_text)); + if ($sign_md5 != $sign) + { + //echo '签名错误'; + return false; + } + elseif ($status = 3) + { + /* 改变订单状态为已付款 */ + order_paid($log_id, PS_PAYING); + return true; + } + else + { + //为止error + return false; + } + } +} + +?> \ No newline at end of file diff --git a/includes/modules/payment/xpay.php b/includes/modules/payment/xpay.php new file mode 100644 index 0000000..cfe5df7 --- /dev/null +++ b/includes/modules/payment/xpay.php @@ -0,0 +1,165 @@ + + * @version: v2.1 + * --------------------------------------------- + */ + +if (!defined('IN_ECS')) +{ + die('Hacking attempt'); +} + +$payment_lang = ROOT_PATH . 'languages/' .$GLOBALS['_CFG']['lang']. '/payment/xpay.php'; +if (file_exists($payment_lang)) +{ + global $_LANG; + + include_once($payment_lang); +} + +/* 模块的基本信息 */ +if (isset($set_modules) && $set_modules == TRUE) +{ + $i = isset($modules) ? count($modules) : 0; + + /* 代码 */ + $modules[$i]['code'] = basename(__FILE__, '.php'); + + /* 描述对应的语言项 */ + $modules[$i]['desc'] = 'xpay_desc'; + + /* 是否支持货到付款 */ + $modules[$i]['is_cod'] = '0'; + + /* 是否支持在线支付 */ + $modules[$i]['is_online'] = '1'; + + /* 作者 */ + $modules[$i]['author'] = 'ECSHOP TEAM'; + + /* 网址 */ + $modules[$i]['website'] = 'http://www.xpay.cn'; + + /* 版本号 */ + $modules[$i]['version'] = '2.0.0'; + + /* 配置信息 */ + $modules[$i]['config'] = array( + array('name' => 'xpay_tid', 'type' => 'text', 'value' => ''), + array('name' => 'xpay_key', 'type' => 'text', 'value' => ''), + ); + + return; +} + +/** + * 类 + */ +class xpay +{ + /** + * 构造函数 + * + * @access public + * @param + * + * @return void + */ + function xpay() + { + } + + function __construct() + { + $this->xpay(); + } + + /** + * 生成支付代码 + * @param array $order 订单信息 + * @param array $payment 支付方式信息 + */ + function get_code($order, $payment) + { + $data_order_id = $order['log_id']; + $data_amount = $order['order_amount']; + $data_return_url = return_url('xpay');; + $data_tid = $payment['xpay_tid']; + $data_key = md5("$payment[xpay_key]:$data_amount,$data_order_id,$data_tid,bank,,sell,,2.0"); + + $def_url = '
    '; + $def_url .= ""; // 商户交易号 + $def_url .= ""; // 订单号 + $def_url .= ""; // 订单总金额 + $def_url .= ""; // 默认支付方式 + $def_url .= ""; // 支持支付种类 + $def_url .= ""; // 交易码 + $def_url .= ""; // 业务代码参数 + $def_url .= ""; // 版本号 + $def_url .= ""; // 订单MD5校验码 + $def_url .= ""; // 支付交易完成后返回到该url,支付结果以get方式发送 + $def_url .= ""; // 产品名称或交易说明 + $def_url .= ""; // 产品类型或交易分类 + $def_url .= ""; // 消费购买用户名 + $def_url .= ""; // 语言 + $def_url .= ""; // 备注字段 + $def_url .= ""; // 隐藏交易邮箱 + $def_url .= ""; // 隐藏弹窗提示 + $def_url .= ""; // 商户网站名称 + $def_url .= ""; // 商户网站域名 + $def_url .= ""; + $def_url .= "
    "; + + return $def_url; + } + + /** + * 响应操作 + */ + function respond() + { + /*取返回参数*/ + $tid = $_REQUEST["tid"]; // 商户唯一交易号 + $bid = $_REQUEST["bid"]; // 商户网站订单号 + $sid = $_REQUEST["sid"]; // 易付通交易成功 流水号 + $prc = $_REQUEST["prc"]; // 支付的金额 + $actionCode = $_REQUEST["actioncode"]; // 交易码 + $actionParameter = $_REQUEST["actionparameter"]; // 业务代码 + $card = $_REQUEST["card"]; // 支付方式 + $success = $_REQUEST["success"]; // 成功标志, + $bankcode = $_REQUEST["bankcode"]; // 支付银行 + $remark1 = $_REQUEST["remark1"]; // 备注信息 + $username = $_REQUEST["username"]; // 商户网站支付用户 + $md = $_REQUEST["md"]; // 32位md5加密数据 + + $payment = get_payment('xpay'); + if ($success == 'false') + { + return false; + } + // 验证数据是否正确 + $ymd = md5($payment['xpay_key'] . ":" . $bid . "," . $sid . "," . $prc . "," . $actionCode ."," . $actionParameter . "," . $tid . "," . $card . "," . $success); // 本地进行数据加密 + if($md != $ymd) + { + return false; + } + else + { + order_paid($bid, PS_PAYED); + + return true; + } + } +} + +?> \ No newline at end of file diff --git a/includes/modules/payment/yeepay.php b/includes/modules/payment/yeepay.php new file mode 100644 index 0000000..5bccb4e --- /dev/null +++ b/includes/modules/payment/yeepay.php @@ -0,0 +1,205 @@ + 'yp_account', 'type' => 'text', 'value' => ''), + array('name' => 'yp_key', 'type' => 'text', 'value' => ''), + ); + + return; +} + +/** + * 类 + */ +class yeepay +{ + /** + * 构造函数 + * + * @access public + * @param + * + * @return void + */ + function yeepay() + { + } + + function __construct() + { + $this->yeepay(); + } + + /** + * 生成支付代码 + * @param array $order 订单信息 + * @param array $payment 支付方式信息 + */ + function get_code($order, $payment) + { + $data_merchant_id = $payment['yp_account']; + $data_order_id = $order['order_sn']; + $data_amount = $order['order_amount']; + $message_type = 'Buy'; + $data_cur = 'CNY'; + $product_id = ''; + $product_cat = ''; + $product_desc = ''; + $address_flag = '0'; + + $data_return_url = return_url(basename(__FILE__, '.php')); + + $data_pay_key = $payment['yp_key']; + $data_pay_account = $payment['yp_account']; + $mct_properties = $order['log_id']; + $def_url = $message_type . $data_merchant_id . $data_order_id . $data_amount . $data_cur . $product_id . $product_cat + . $product_desc . $data_return_url . $address_flag . $mct_properties; + $MD5KEY = hmac($def_url, $data_pay_key); + + $def_url = "\n
    \n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= ""; + $def_url .= "
    \n"; + + return $def_url; + } + + /** + * 响应操作 + */ + function respond() + { + $payment = get_payment('yeepay'); + + $merchant_id = $payment['yp_account']; // 获取商户编号 + $merchant_key = $payment['yp_key']; // 获取秘钥 + + $message_type = trim($_REQUEST['r0_Cmd']); + $succeed = trim($_REQUEST['r1_Code']); // 获取交易结果,1成功,-1失败 + $trxId = trim($_REQUEST['r2_TrxId']); + $amount = trim($_REQUEST['r3_Amt']); // 获取订单金额 + $cur = trim($_REQUEST['r4_Cur']); // 获取订单货币单位 + $product_id = trim($_REQUEST['r5_Pid']); // 获取产品ID + $orderid = trim($_REQUEST['r6_Order']); // 获取订单ID + $userId = trim($_REQUEST['r7_Uid']); // 获取产品ID + $merchant_param = trim($_REQUEST['r8_MP']); // 获取商户私有参数 + $bType = trim($_REQUEST['r9_BType']); // 获取订单ID + + $mac = trim($_REQUEST['hmac']); // 获取安全加密串 + + ///生成加密串,注意顺序 + $ScrtStr = $merchant_id . $message_type . $succeed . $trxId . $amount . $cur . $product_id . + $orderid . $userId . $merchant_param . $bType; + $mymac = hmac($ScrtStr, $merchant_key); + + $v_result = false; + + if (strtoupper($mac) == strtoupper($mymac)) + { + if ($succeed == '1') + { + ///支付成功 + $v_result = true; + + order_paid($merchant_param); + } + } + + return $v_result; + } +} + +if (!function_exists("hmac")) +{ + function hmac($data, $key) + { + // RFC 2104 HMAC implementation for php. + // Creates an md5 HMAC. + // Eliminates the need to install mhash to compute a HMAC + // Hacked by Lance Rushing(NOTE: Hacked means written) + + $key = ecs_iconv('GB2312', 'UTF8', $key); + $data = ecs_iconv('GB2312', 'UTF8', $data); + + $b = 64; // byte length for md5 + if (strlen($key) > $b) + { + $key = pack('H*', md5($key)); + } + + $key = str_pad($key, $b, chr(0x00)); + $ipad = str_pad('', $b, chr(0x36)); + $opad = str_pad('', $b, chr(0x5c)); + $k_ipad = $key ^ $ipad ; + $k_opad = $key ^ $opad; + + return md5($k_opad . pack('H*', md5($k_ipad . $data))); + } +} + +?> \ No newline at end of file diff --git a/includes/modules/payment/yeepay_abchina.php b/includes/modules/payment/yeepay_abchina.php new file mode 100644 index 0000000..373ec07 --- /dev/null +++ b/includes/modules/payment/yeepay_abchina.php @@ -0,0 +1,208 @@ + 'yp_account', 'type' => 'text', 'value' => ''), + array('name' => 'yp_key', 'type' => 'text', 'value' => ''), + ); + + return; +} + +/** + * 类 + */ +class yeepay_abchina +{ + /** + * 构造函数 + * + * @access public + * @param + * + * @return void + */ + function yeepay_abchina() + { + $this->frpid = 'ABC-NET'; + } + + function __construct() + { + $this->yeepay_abchina(); + } + + /** + * 生成支付代码 + * @param array $order 订单信息 + * @param array $payment 支付方式信息 + */ + function get_code($order, $payment) + { + $data_merchant_id = $payment['yp_account']; + $data_order_id = $order['order_sn']; + $data_amount = $order['order_amount']; + $message_type = 'Buy'; + $data_cur = 'CNY'; + $product_id = ''; + $product_cat = ''; + $product_desc = ''; + $address_flag = '0'; + + $data_return_url = return_url(basename(__FILE__, '.php')); + + $data_pay_key = $payment['yp_key']; + $data_pay_account = $payment['yp_account']; + $mct_properties = $order['log_id']; + $def_url = $message_type . $data_merchant_id . $data_order_id . $data_amount . $data_cur . $product_id . $product_cat + . $product_desc . $data_return_url . $address_flag . $mct_properties . $this->frpid; + $MD5KEY = hmac($def_url, $data_pay_key); + + $def_url = "\n
    \n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= ""; + $def_url .= "
    \n"; + + return $def_url; + } + + /** + * 响应操作 + */ + function respond() + { + $payment = get_payment('yeepay_abchina'); + + $merchant_id = $payment['yp_account']; // 获取商户编号 + $merchant_key = $payment['yp_key']; // 获取秘钥 + + $message_type = trim($_REQUEST['r0_Cmd']); + $succeed = trim($_REQUEST['r1_Code']); // 获取交易结果,1成功,-1失败 + $trxId = trim($_REQUEST['r2_TrxId']); + $amount = trim($_REQUEST['r3_Amt']); // 获取订单金额 + $cur = trim($_REQUEST['r4_Cur']); // 获取订单货币单位 + $product_id = trim($_REQUEST['r5_Pid']); // 获取产品ID + $orderid = trim($_REQUEST['r6_Order']); // 获取订单ID + $userId = trim($_REQUEST['r7_Uid']); // 获取产品ID + $merchant_param = trim($_REQUEST['r8_MP']); // 获取商户私有参数 + $bType = trim($_REQUEST['r9_BType']); // 获取订单ID + + $mac = trim($_REQUEST['hmac']); // 获取安全加密串 + + ///生成加密串,注意顺序 + $ScrtStr = $merchant_id . $message_type . $succeed . $trxId . $amount . $cur . $product_id . + $orderid . $userId . $merchant_param . $bType; + $mymac = hmac($ScrtStr, $merchant_key); + + $v_result = false; + + if (strtoupper($mac) == strtoupper($mymac)) + { + if ($succeed == '1') + { + ///支付成功 + $v_result = true; + + order_paid($merchant_param); + } + } + + return $v_result; + } +} + +if (!function_exists("hmac")) +{ + function hmac($data, $key) + { + // RFC 2104 HMAC implementation for php. + // Creates an md5 HMAC. + // Eliminates the need to install mhash to compute a HMAC + // Hacked by Lance Rushing(NOTE: Hacked means written) + + $key = ecs_iconv('GB2312', 'UTF8', $key); + $data = ecs_iconv('GB2312', 'UTF8', $data); + + $b = 64; // byte length for md5 + if (strlen($key) > $b) + { + $key = pack('H*', md5($key)); + } + + $key = str_pad($key, $b, chr(0x00)); + $ipad = str_pad('', $b, chr(0x36)); + $opad = str_pad('', $b, chr(0x5c)); + $k_ipad = $key ^ $ipad ; + $k_opad = $key ^ $opad; + + return md5($k_opad . pack('H*', md5($k_ipad . $data))); + } +} + +?> \ No newline at end of file diff --git a/includes/modules/payment/yeepay_ccb.php b/includes/modules/payment/yeepay_ccb.php new file mode 100644 index 0000000..acb3a55 --- /dev/null +++ b/includes/modules/payment/yeepay_ccb.php @@ -0,0 +1,209 @@ + 'yp_account', 'type' => 'text', 'value' => ''), + array('name' => 'yp_key', 'type' => 'text', 'value' => ''), + ); + + return; +} + +/** + * 类 + */ +class yeepay_ccb +{ + /** + * 构造函数 + * + * @access public + * @param + * + * @return void + */ + function yeepay_ccb() + { + $this->frpid = 'CCB-NET'; + } + + function __construct() + { + $this->yeepay_ccb(); + } + + /** + * 生成支付代码 + * @param array $order 订单信息 + * @param array $payment 支付方式信息 + */ + function get_code($order, $payment) + { + $data_merchant_id = $payment['yp_account']; + $data_order_id = $order['order_sn']; + $data_amount = $order['order_amount']; + $message_type = 'Buy'; + $data_cur = 'CNY'; + $product_id = ''; + $product_cat = ''; + $product_desc = ''; + $address_flag = '0'; + + $data_return_url = return_url(basename(__FILE__, '.php')); + + $data_pay_key = $payment['yp_key']; + $data_pay_account = $payment['yp_account']; + $mct_properties = $order['log_id']; + $def_url = $message_type . $data_merchant_id . $data_order_id . $data_amount . $data_cur . $product_id . $product_cat + . $product_desc . $data_return_url . $address_flag . $mct_properties . $this->frpid; + $MD5KEY = hmac($def_url, $data_pay_key); + + $def_url = "\n
    \n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= ""; + $def_url .= "
    \n"; + + return $def_url; + } + + /** + * 响应操作 + */ + function respond() + { + $payment = get_payment('yeepay_ccb'); + + $merchant_id = $payment['yp_account']; // 获取商户编号 + $merchant_key = $payment['yp_key']; // 获取秘钥 + + $message_type = trim($_REQUEST['r0_Cmd']); + $succeed = trim($_REQUEST['r1_Code']); // 获取交易结果,1成功,-1失败 + $trxId = trim($_REQUEST['r2_TrxId']); + $amount = trim($_REQUEST['r3_Amt']); // 获取订单金额 + $cur = trim($_REQUEST['r4_Cur']); // 获取订单货币单位 + $product_id = trim($_REQUEST['r5_Pid']); // 获取产品ID + $orderid = trim($_REQUEST['r6_Order']); // 获取订单ID + $userId = trim($_REQUEST['r7_Uid']); // 获取产品ID + $merchant_param = trim($_REQUEST['r8_MP']); // 获取商户私有参数 + $bType = trim($_REQUEST['r9_BType']); // 获取订单ID + + $mac = trim($_REQUEST['hmac']); // 获取安全加密串 + + ///生成加密串,注意顺序 + $ScrtStr = $merchant_id . $message_type . $succeed . $trxId . $amount . $cur . $product_id . + $orderid . $userId . $merchant_param . $bType; + $mymac = hmac($ScrtStr, $merchant_key); + + $v_result = false; + + if (strtoupper($mac) == strtoupper($mymac)) + { + if ($succeed == '1') + { + ///支付成功 + $v_result = true; + + $order_id = str_replace($orderid, '', $product_id); + order_paid($merchant_param); + } + } + + return $v_result; + } +} + +if (!function_exists("hmac")) +{ + function hmac($data, $key) + { + // RFC 2104 HMAC implementation for php. + // Creates an md5 HMAC. + // Eliminates the need to install mhash to compute a HMAC + // Hacked by Lance Rushing(NOTE: Hacked means written) + + $key = ecs_iconv('GB2312', 'UTF8', $key); + $data = ecs_iconv('GB2312', 'UTF8', $data); + + $b = 64; // byte length for md5 + if (strlen($key) > $b) + { + $key = pack('H*', md5($key)); + } + + $key = str_pad($key, $b, chr(0x00)); + $ipad = str_pad('', $b, chr(0x36)); + $opad = str_pad('', $b, chr(0x5c)); + $k_ipad = $key ^ $ipad ; + $k_opad = $key ^ $opad; + + return md5($k_opad . pack('H*', md5($k_ipad . $data))); + } +} + +?> \ No newline at end of file diff --git a/includes/modules/payment/yeepay_cmbchina.php b/includes/modules/payment/yeepay_cmbchina.php new file mode 100644 index 0000000..de754e3 --- /dev/null +++ b/includes/modules/payment/yeepay_cmbchina.php @@ -0,0 +1,209 @@ + 'yp_account', 'type' => 'text', 'value' => ''), + array('name' => 'yp_key', 'type' => 'text', 'value' => ''), + ); + + return; +} + +/** + * 类 + */ +class yeepay_cmbchina +{ + /** + * 构造函数 + * + * @access public + * @param + * + * @return void + */ + function yeepay_cmbchina() + { + $this->frpid = 'CMBCHINA-NET'; + } + + function __construct() + { + $this->yeepay_cmbchina(); + } + + /** + * 生成支付代码 + * @param array $order 订单信息 + * @param array $payment 支付方式信息 + */ + function get_code($order, $payment) + { + $data_merchant_id = $payment['yp_account']; + $data_order_id = $order['order_sn']; + $data_amount = $order['order_amount']; + $message_type = 'Buy'; + $data_cur = 'CNY'; + $product_id = ''; + $product_cat = ''; + $product_desc = ''; + $address_flag = '0'; + + $data_return_url = return_url(basename(__FILE__, '.php')); + + $data_pay_key = $payment['yp_key']; + $data_pay_account = $payment['yp_account']; + $mct_properties = $order['log_id']; + $def_url = $message_type . $data_merchant_id . $data_order_id . $data_amount . $data_cur . $product_id . $product_cat + . $product_desc . $data_return_url . $address_flag . $mct_properties . $this->frpid; + $MD5KEY = hmac($def_url, $data_pay_key); + + $def_url = "\n
    \n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= ""; + $def_url .= "
    \n"; + + return $def_url; + } + + /** + * 响应操作 + */ + function respond() + { + $payment = get_payment('yeepay_cmbchina'); + + $merchant_id = $payment['yp_account']; // 获取商户编号 + $merchant_key = $payment['yp_key']; // 获取秘钥 + + $message_type = trim($_REQUEST['r0_Cmd']); + $succeed = trim($_REQUEST['r1_Code']); // 获取交易结果,1成功,-1失败 + $trxId = trim($_REQUEST['r2_TrxId']); + $amount = trim($_REQUEST['r3_Amt']); // 获取订单金额 + $cur = trim($_REQUEST['r4_Cur']); // 获取订单货币单位 + $product_id = trim($_REQUEST['r5_Pid']); // 获取产品ID + $orderid = trim($_REQUEST['r6_Order']); // 获取订单ID + $userId = trim($_REQUEST['r7_Uid']); // 获取产品ID + $merchant_param = trim($_REQUEST['r8_MP']); // 获取商户私有参数 + $bType = trim($_REQUEST['r9_BType']); // 获取订单ID + + $mac = trim($_REQUEST['hmac']); // 获取安全加密串 + + ///生成加密串,注意顺序 + $ScrtStr = $merchant_id . $message_type . $succeed . $trxId . $amount . $cur . $product_id . + $orderid . $userId . $merchant_param . $bType; + $mymac = hmac($ScrtStr, $merchant_key); + + $v_result = false; + + if (strtoupper($mac) == strtoupper($mymac)) + { + if ($succeed == '1') + { + ///支付成功 + $v_result = true; + + $order_id = str_replace($orderid, '', $product_id); + order_paid($merchant_param); + } + } + + return $v_result; + } +} + +if (!function_exists("hmac")) +{ + function hmac($data, $key) + { + // RFC 2104 HMAC implementation for php. + // Creates an md5 HMAC. + // Eliminates the need to install mhash to compute a HMAC + // Hacked by Lance Rushing(NOTE: Hacked means written) + + $key = ecs_iconv('GB2312', 'UTF8', $key); + $data = ecs_iconv('GB2312', 'UTF8', $data); + + $b = 64; // byte length for md5 + if (strlen($key) > $b) + { + $key = pack('H*', md5($key)); + } + + $key = str_pad($key, $b, chr(0x00)); + $ipad = str_pad('', $b, chr(0x36)); + $opad = str_pad('', $b, chr(0x5c)); + $k_ipad = $key ^ $ipad ; + $k_opad = $key ^ $opad; + + return md5($k_opad . pack('H*', md5($k_ipad . $data))); + } +} + +?> \ No newline at end of file diff --git a/includes/modules/payment/yeepay_icbc.php b/includes/modules/payment/yeepay_icbc.php new file mode 100644 index 0000000..0c2b234 --- /dev/null +++ b/includes/modules/payment/yeepay_icbc.php @@ -0,0 +1,209 @@ + 'yp_account', 'type' => 'text', 'value' => ''), + array('name' => 'yp_key', 'type' => 'text', 'value' => ''), + ); + + return; +} + +/** + * 类 + */ +class yeepay_icbc +{ + /** + * 构造函数 + * + * @access public + * @param + * + * @return void + */ + function yeepay_icbc() + { + $this->frpid = 'ICBC-NET'; + } + + function __construct() + { + $this->yeepay_icbc(); + } + + /** + * 生成支付代码 + * @param array $order 订单信息 + * @param array $payment 支付方式信息 + */ + function get_code($order, $payment) + { + $data_merchant_id = $payment['yp_account']; + $data_order_id = $order['order_sn']; + $data_amount = $order['order_amount']; + $message_type = 'Buy'; + $data_cur = 'CNY'; + $product_id = ''; + $product_cat = ''; + $product_desc = ''; + $address_flag = '0'; + + $data_return_url = return_url(basename(__FILE__, '.php')); + + $data_pay_key = $payment['yp_key']; + $data_pay_account = $payment['yp_account']; + $mct_properties = $order['log_id']; + $def_url = $message_type . $data_merchant_id . $data_order_id . $data_amount . $data_cur . $product_id . $product_cat + . $product_desc . $data_return_url . $address_flag . $mct_properties . $this->frpid; + $MD5KEY = hmac($def_url, $data_pay_key); + + $def_url = "\n
    \n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= ""; + $def_url .= "
    \n"; + + return $def_url; + } + + /** + * 响应操作 + */ + function respond() + { + $payment = get_payment('yeepay_icbc'); + + $merchant_id = $payment['yp_account']; // 获取商户编号 + $merchant_key = $payment['yp_key']; // 获取秘钥 + + $message_type = trim($_REQUEST['r0_Cmd']); + $succeed = trim($_REQUEST['r1_Code']); // 获取交易结果,1成功,-1失败 + $trxId = trim($_REQUEST['r2_TrxId']); + $amount = trim($_REQUEST['r3_Amt']); // 获取订单金额 + $cur = trim($_REQUEST['r4_Cur']); // 获取订单货币单位 + $product_id = trim($_REQUEST['r5_Pid']); // 获取产品ID + $orderid = trim($_REQUEST['r6_Order']); // 获取订单ID + $userId = trim($_REQUEST['r7_Uid']); // 获取产品ID + $merchant_param = trim($_REQUEST['r8_MP']); // 获取商户私有参数 + $bType = trim($_REQUEST['r9_BType']); // 获取订单ID + + $mac = trim($_REQUEST['hmac']); // 获取安全加密串 + + ///生成加密串,注意顺序 + $ScrtStr = $merchant_id . $message_type . $succeed . $trxId . $amount . $cur . $product_id . + $orderid . $userId . $merchant_param . $bType; + $mymac = hmac($ScrtStr, $merchant_key); + + $v_result = false; + + if (strtoupper($mac) == strtoupper($mymac)) + { + if ($succeed == '1') + { + ///支付成功 + $v_result = true; + + $order_id = str_replace($orderid, '', $product_id); + order_paid($merchant_param); + } + } + + return $v_result; + } +} + +if (!function_exists("hmac")) +{ + function hmac($data, $key) + { + // RFC 2104 HMAC implementation for php. + // Creates an md5 HMAC. + // Eliminates the need to install mhash to compute a HMAC + // Hacked by Lance Rushing(NOTE: Hacked means written) + + $key = ecs_iconv('GB2312', 'UTF8', $key); + $data = ecs_iconv('GB2312', 'UTF8', $data); + + $b = 64; // byte length for md5 + if (strlen($key) > $b) + { + $key = pack('H*', md5($key)); + } + + $key = str_pad($key, $b, chr(0x00)); + $ipad = str_pad('', $b, chr(0x36)); + $opad = str_pad('', $b, chr(0x5c)); + $k_ipad = $key ^ $ipad ; + $k_opad = $key ^ $opad; + + return md5($k_opad . pack('H*', md5($k_ipad . $data))); + } +} + +?> \ No newline at end of file diff --git a/includes/modules/payment/yeepay_jcard.php b/includes/modules/payment/yeepay_jcard.php new file mode 100644 index 0000000..bdeea04 --- /dev/null +++ b/includes/modules/payment/yeepay_jcard.php @@ -0,0 +1,209 @@ + 'yp_account', 'type' => 'text', 'value' => ''), + array('name' => 'yp_key', 'type' => 'text', 'value' => ''), + ); + + return; +} + +/** + * 类 + */ +class yeepay_jcard +{ + /** + * 构造函数 + * + * @access public + * @param + * + * @return void + */ + function yeepay_jcard() + { + $this->frpid = 'JUNNET-NET'; + } + + function __construct() + { + $this->yeepay_jcard(); + } + + /** + * 生成支付代码 + * @param array $order 订单信息 + * @param array $payment 支付方式信息 + */ + function get_code($order, $payment) + { + $data_merchant_id = $payment['yp_account']; + $data_order_id = $order['order_sn']; + $data_amount = $order['order_amount']; + $message_type = 'Buy'; + $data_cur = 'CNY'; + $product_id = ''; + $product_cat = ''; + $product_desc = ''; + $address_flag = '0'; + + $data_return_url = return_url(basename(__FILE__, '.php')); + + $data_pay_key = $payment['yp_key']; + $data_pay_account = $payment['yp_account']; + $mct_properties = $order['log_id']; + $def_url = $message_type . $data_merchant_id . $data_order_id . $data_amount . $data_cur . $product_id . $product_cat + . $product_desc . $data_return_url . $address_flag . $mct_properties . $this->frpid; + $MD5KEY = hmac($def_url, $data_pay_key); + + $def_url = "\n
    \n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= ""; + $def_url .= "
    \n"; + + return $def_url; + } + + /** + * 响应操作 + */ + function respond() + { + $payment = get_payment('yeepay_jcard'); + + $merchant_id = $payment['yp_account']; // 获取商户编号 + $merchant_key = $payment['yp_key']; // 获取秘钥 + + $message_type = trim($_REQUEST['r0_Cmd']); + $succeed = trim($_REQUEST['r1_Code']); // 获取交易结果,1成功,-1失败 + $trxId = trim($_REQUEST['r2_TrxId']); + $amount = trim($_REQUEST['r3_Amt']); // 获取订单金额 + $cur = trim($_REQUEST['r4_Cur']); // 获取订单货币单位 + $product_id = trim($_REQUEST['r5_Pid']); // 获取产品ID + $orderid = trim($_REQUEST['r6_Order']); // 获取订单ID + $userId = trim($_REQUEST['r7_Uid']); // 获取产品ID + $merchant_param = trim($_REQUEST['r8_MP']); // 获取商户私有参数 + $bType = trim($_REQUEST['r9_BType']); // 获取订单ID + + $mac = trim($_REQUEST['hmac']); // 获取安全加密串 + + ///生成加密串,注意顺序 + $ScrtStr = $merchant_id . $message_type . $succeed . $trxId . $amount . $cur . $product_id . + $orderid . $userId . $merchant_param . $bType; + $mymac = hmac($ScrtStr, $merchant_key); + + $v_result = false; + + if (strtoupper($mac) == strtoupper($mymac)) + { + if ($succeed == '1') + { + ///支付成功 + $v_result = true; + + $order_id = str_replace($orderid, '', $product_id); + order_paid($merchant_param); + } + } + + return $v_result; + } +} + +if (!function_exists("hmac")) +{ + function hmac($data, $key) + { + // RFC 2104 HMAC implementation for php. + // Creates an md5 HMAC. + // Eliminates the need to install mhash to compute a HMAC + // Hacked by Lance Rushing(NOTE: Hacked means written) + + $key = ecs_iconv('GB2312', 'UTF8', $key); + $data = ecs_iconv('GB2312', 'UTF8', $data); + + $b = 64; // byte length for md5 + if (strlen($key) > $b) + { + $key = pack('H*', md5($key)); + } + + $key = str_pad($key, $b, chr(0x00)); + $ipad = str_pad('', $b, chr(0x36)); + $opad = str_pad('', $b, chr(0x5c)); + $k_ipad = $key ^ $ipad ; + $k_opad = $key ^ $opad; + + return md5($k_opad . pack('H*', md5($k_ipad . $data))); + } +} + +?> \ No newline at end of file diff --git a/includes/modules/payment/yeepayszx.php b/includes/modules/payment/yeepayszx.php new file mode 100644 index 0000000..efdfc0b --- /dev/null +++ b/includes/modules/payment/yeepayszx.php @@ -0,0 +1,206 @@ + 'yp_account', 'type' => 'text', 'value' => ''), + array('name' => 'yp_key', 'type' => 'text', 'value' => ''), + ); + + return; +} + +/** + * 类 + */ +class yeepayszx +{ + /** + * 构造函数 + * + * @access public + * @param + * + * @return void + */ + function yeepayszx() + { + } + + function __construct() + { + $this->yeepayszx(); + } + + /** + * 生成支付代码 + * @param array $order 订单信息 + * @param array $payment 支付方式信息 + */ + function get_code($order, $payment) + { + $data_merchant_id = $payment['yp_account']; + $data_order_id = $order['order_sn']; + $data_amount = $order['order_amount']; + $message_type = 'Buy'; + $data_cur = 'CNY'; + $product_id = ''; + $product_cat = ''; + $product_desc = ''; + $address_flag = '0'; + + $data_return_url = return_url(basename(__FILE__, '.php')); + + $data_pay_key = $payment['yp_key']; + $data_pay_account = $payment['yp_account']; + $mct_properties = $order['log_id']; + $frp_id = 'SZX'; + $need_response = ''; + $def_url = $message_type . $data_merchant_id . $data_order_id . $data_amount . $data_cur . $product_id . $data_return_url . $address_flag . $mct_properties . $frp_id . $need_response; + $MD5KEY = $this->hmac($def_url, $data_pay_key); + + $def_url = "\n
    \n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + //$def_url .= "\n"; + //$def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= "\n"; + $def_url .= ""; + $def_url .= "
    \n"; + + return $def_url; + } + + /** + * 响应操作 + */ + function respond() + { + $payment = get_payment('yeepay'); + + $merchant_id = $payment['yp_account']; // 获取商户编号 + $merchant_key = $payment['yp_key']; // 获取秘钥 + + $message_type = trim($_REQUEST['r0_Cmd']); + $succeed = trim($_REQUEST['r1_Code']); // 获取交易结果,1成功,-1失败 + $trxId = trim($_REQUEST['r2_TrxId']); + $amount = trim($_REQUEST['r3_Amt']); // 获取订单金额 + $cur = trim($_REQUEST['r4_Cur']); // 获取订单货币单位 + $product_id = trim($_REQUEST['r5_Pid']); // 获取产品ID + $orderid = trim($_REQUEST['r6_Order']); // 获取订单ID + $userId = trim($_REQUEST['r7_Uid']); // 获取产品ID + $merchant_param = trim($_REQUEST['r8_MP']); // 获取商户私有参数 + $bType = trim($_REQUEST['r9_BType']); // 获取订单ID + + $mac = trim($_REQUEST['hmac']); // 获取安全加密串 + + ///生成加密串,注意顺序 + $ScrtStr = $merchant_id . $message_type . $succeed . $trxId . $amount . $cur . $product_id . + $orderid . $userId . $merchant_param . $bType; + + $mymac = $this->hmac($ScrtStr, $merchant_key); + + $v_result = false; + + if (strtoupper($mac) == strtoupper($mymac)) + { + if ($succeed == '1') + { + ///支付成功 + $v_result = true; + + $order_id = str_replace($orderid, '', $product_id); + order_paid($merchant_param); + } + } + + return $v_result; + } + function hmac($data, $key) + { + // RFC 2104 HMAC implementation for php. + // Creates an md5 HMAC. + // Eliminates the need to install mhash to compute a HMAC + // Hacked by Lance Rushing(NOTE: Hacked means written) + + $key = ecs_iconv(EC_CHARSET, 'UTF8', $key); + $data = ecs_iconv(EC_CHARSET, 'UTF8', $data); + + $b = 64; // byte length for md5 + if (strlen($key) > $b) + { + $key = pack('H*', md5($key)); + } + + $key = str_pad($key, $b, chr(0x00)); + $ipad = str_pad('', $b, chr(0x36)); + $opad = str_pad('', $b, chr(0x5c)); + $k_ipad = $key ^ $ipad ; + $k_opad = $key ^ $opad; + + return md5($k_opad . pack('H*', md5($k_ipad . $data))); + } +} + +?> \ No newline at end of file diff --git a/includes/modules/shipping/cac.php b/includes/modules/shipping/cac.php new file mode 100644 index 0000000..51ff37a --- /dev/null +++ b/includes/modules/shipping/cac.php @@ -0,0 +1,120 @@ + \ No newline at end of file diff --git a/includes/modules/shipping/city_express.php b/includes/modules/shipping/city_express.php new file mode 100644 index 0000000..2037a4f --- /dev/null +++ b/includes/modules/shipping/city_express.php @@ -0,0 +1,130 @@ + 'base_fee', 'value'=>10), + ); + + /* 模式编辑器 */ + $modules[$i]['print_model'] = 2; + + /* 打印单背景 */ + $modules[$i]['print_bg'] = ''; + + /* 打印快递单标签位置信息 */ + $modules[$i]['config_lable'] = ''; + + return; +} + +class city_express +{ + /*------------------------------------------------------ */ + //-- PUBLIC ATTRIBUTEs + /*------------------------------------------------------ */ + + /** + * 配置信息 + */ + var $configure; + + /*------------------------------------------------------ */ + //-- PUBLIC METHODs + /*------------------------------------------------------ */ + + /** + * 构造函数 + * + * @param: $configure[array] 配送方式的参数的数组 + * + * @return null + */ + function city_express($cfg=array()) + { + foreach ($cfg AS $key=>$val) + { + $this->configure[$val['name']] = $val['value']; + } + } + + /** + * 计算订单的配送费用的函数 + * + * @param float $goods_weight 商品重量 + * @param float $goods_amount 商品金额 + * @return decimal + */ + function calculate($goods_weight, $goods_amount) + { + if ($this->configure['free_money'] > 0 && $goods_amount >= $this->configure['free_money']) + { + return 0; + } + else + { + return $this->configure['base_fee']; + } + } + + /** + * 查询发货状态 + * 该配送方式不支持查询发货状态 + * + * @access public + * @param string $invoice_sn 发货单号 + * @return string + */ + function query($invoice_sn) + { + return $invoice_sn; + } +} + +?> diff --git a/includes/modules/shipping/ems.php b/includes/modules/shipping/ems.php new file mode 100644 index 0000000..f75fd82 --- /dev/null +++ b/includes/modules/shipping/ems.php @@ -0,0 +1,165 @@ + 'item_fee', 'value'=>20), + array('name' => 'base_fee', 'value'=>20), + array('name' => 'step_fee', 'value'=>15), + ); + + /* 模式编辑器 */ + $modules[$i]['print_model'] = 2; + + /* 打印单背景 */ + $modules[$i]['print_bg'] = '/images/receipt/dly_ems.jpg'; + + /* 打印快递单标签位置信息 */ + $modules[$i]['config_lable'] = 't_shop_name,' . $_LANG['lable_box']['shop_name'] . ',236,32,182,161,b_shop_name||,||t_shop_tel,' . $_LANG['lable_box']['shop_tel'] . ',127,21,295,135,b_shop_tel||,||t_shop_address,' . $_LANG['lable_box']['shop_address'] . ',296,68,124,190,b_shop_address||,||t_pigeon,' . $_LANG['lable_box']['pigeon'] . ',21,21,192,278,b_pigeon||,||t_customer_name,' . $_LANG['lable_box']['customer_name'] . ',107,23,494,136,b_customer_name||,||t_customer_tel,' . $_LANG['lable_box']['customer_tel'] . ',155,21,639,124,b_customer_tel||,||t_customer_mobel,' . $_LANG['lable_box']['customer_mobel'] . ',159,21,639,147,b_customer_mobel||,||t_customer_post,' . $_LANG['lable_box']['customer_post'] . ',88,21,680,258,b_customer_post||,||t_year,' . $_LANG['lable_box']['year'] . ',37,21,534,379,b_year||,||t_months,' . $_LANG['lable_box']['months'] . ',29,21,592,379,b_months||,||t_day,' . $_LANG['lable_box']['day'] . ',27,21,642,380,b_day||,||t_order_best_time,' . $_LANG['lable_box']['order_best_time'] . ',104,39,688,359,b_order_best_time||,||t_order_postscript,' . $_LANG['lable_box']['order_postscript'] . ',305,34,485,402,b_order_postscript||,||t_customer_address,' . $_LANG['lable_box']['customer_address'] . ',289,48,503,190,b_customer_address||,||'; + + return; +} + +/** + * 邮政快递包裹费用计算方式 + * ==================================================================================== + * 500g及500g以内 20元 + * ------------------------------------------------------------------------------------- + * 续重每500克或其零数 6元/9元/15元(按分区不同收费不同,具体分区方式,请寄件人拨打电话或到当地邮局营业窗口咨询,客服电话11185。) + * ------------------------------------------------------------------------------------- + * + */ +class ems +{ + /*------------------------------------------------------ */ + //-- PUBLIC ATTRIBUTEs + /*------------------------------------------------------ */ + + /** + * 配置信息 + */ + var $configure; + + /*------------------------------------------------------ */ + //-- PUBLIC METHODs + /*------------------------------------------------------ */ + + /** + * 构造函数 + * + * @param: $configure[array] 配送方式的参数的数组 + * + * @return null + */ + function ems($cfg=array()) + { + foreach ($cfg AS $key=>$val) + { + $this->configure[$val['name']] = $val['value']; + } + } + + /** + * 计算订单的配送费用的函数 + * + * @param float $goods_weight 商品重量 + * @param float $goods_amount 商品金额 + * @param float $goods_number 商品件数 + * @return decimal + */ + function calculate($goods_weight, $goods_amount, $goods_number) + { + if ($this->configure['free_money'] > 0 && $goods_amount >= $this->configure['free_money']) + { + return 0; + } + else + { + $fee = $this->configure['base_fee']; + $this->configure['fee_compute_mode'] = !empty($this->configure['fee_compute_mode']) ? $this->configure['fee_compute_mode'] : 'by_weight'; + + if ($this->configure['fee_compute_mode'] == 'by_number') + { + $fee = $goods_number * $this->configure['item_fee']; + } + else + { + if ($goods_weight > 0.5) + { + $fee += (ceil(($goods_weight - 0.5) / 0.5)) * $this->configure['step_fee']; + } + } + return $fee; + } + } + + /** + * 查询发货状态 + * + * @access public + * @param string $invoice_sn 发货单号 + * @return string + */ + function query($invoice_sn) + { + $str = '
    '. + ''. + '' .$invoice_sn. ''. + ''. + ''. + '
    '; + + return $str; + } +} + +?> \ No newline at end of file diff --git a/includes/modules/shipping/flat.php b/includes/modules/shipping/flat.php new file mode 100644 index 0000000..36c8171 --- /dev/null +++ b/includes/modules/shipping/flat.php @@ -0,0 +1,130 @@ + 'base_fee', 'value' => 10), + ); + + /* 模式编辑器 */ + $modules[$i]['print_model'] = 2; + + /* 打印单背景 */ + $modules[$i]['print_bg'] = ''; + + /* 打印快递单标签位置信息 */ + $modules[$i]['config_lable'] = ''; + + return; +} + +class flat +{ + /*------------------------------------------------------ */ + //-- PUBLIC ATTRIBUTEs + /*------------------------------------------------------ */ + + /** + * 配置信息 + */ + var $configure; + + /*------------------------------------------------------ */ + //-- PUBLIC METHODs + /*------------------------------------------------------ */ + + /** + * 构造函数 + * + * @param: $configure[array] 配送方式的参数的数组 + * + * @return null + */ + function flat($cfg = array()) + { + foreach ($cfg AS $key => $val) + { + $this->configure[$val['name']] = $val['value']; + } + } + + /** + * 计算订单的配送费用的函数 + * + * @param float $goods_weight 商品重量 + * @param float $goods_amount 商品金额 + * @return decimal + */ + function calculate($goods_weight, $goods_amount) + { + if ($this->configure['free_money'] > 0 && $goods_amount >= $this->configure['free_money']) + { + return 0; + } + else + { + return isset($this->configure['base_fee']) ? $this->configure['base_fee'] : 0; + } + } + + /** + * 查询发货状态 + * 该配送方式不支持查询发货状态 + * + * @access public + * @param string $invoice_sn 发货单号 + * @return string + */ + function query($invoice_sn) + { + return $invoice_sn; + } +} + +?> \ No newline at end of file diff --git a/includes/modules/shipping/fpd.php b/includes/modules/shipping/fpd.php new file mode 100644 index 0000000..4b25e58 --- /dev/null +++ b/includes/modules/shipping/fpd.php @@ -0,0 +1,117 @@ + \ No newline at end of file diff --git a/includes/modules/shipping/post_express.php b/includes/modules/shipping/post_express.php new file mode 100644 index 0000000..2d86d7f --- /dev/null +++ b/includes/modules/shipping/post_express.php @@ -0,0 +1,199 @@ + 'item_fee', 'value'=>5), + array('name' => 'base_fee', 'value'=>5), + array('name' => 'step_fee', 'value'=>2), + array('name' => 'step_fee1', 'value'=>1), + ); + + /* 模式编辑器 */ + $modules[$i]['print_model'] = 2; + + /* 打印单背景 */ + $modules[$i]['print_bg'] = ''; + + /* 打印快递单标签位置信息 */ + $modules[$i]['config_lable'] = ''; + + return; +} + +/** + * 邮政快递包裹费用计算方式 + * ==================================================================================== + * 运距 首重1000克 5000克以内续重每500克 5001克以上续重500克 + * ------------------------------------------------------------------------------------- + * 500公里及500公里以内 5.00 2.00 1.00 + * 500公里以上至1000公里 6.00 2.50 1.30 + * 1000公里以上至1500公里 7.00 3.00 1.60 + * 1500公里以上至2000公里 8.00 3.50 1.90 + * 2000公里以上至2500公里 9.00 4.00 2.20 + * 2500公里以上至3000公里 10.00 4.50 2.50 + * 3000公里以上至4000公里 12.00 5.50 3.10 + * 4000公里以上至5000公里 14.00 6.50 3.70 + * 5000公里以上至6000公里 16.00 7.50 4.30 + * 6000公里以上 20.00 9.00 6.00 + * ------------------------------------------------------------------------------------- + * 每件挂号费 3.00 + */ +class post_express +{ + /*------------------------------------------------------ */ + //-- PUBLIC ATTRIBUTEs + /*------------------------------------------------------ */ + + /** + * 配置信息 + */ + var $configure; + + /*------------------------------------------------------ */ + //-- PUBLIC METHODs + /*------------------------------------------------------ */ + + /** + * 构造函数 + * + * @param: $configure[array] 配送方式的参数的数组 + * + * @return null + */ + function post_express($cfg=array()) + { + foreach ($cfg AS $key=>$val) + { + $this->configure[$val['name']] = $val['value']; + } + } + + /** + * 计算订单的配送费用的函数 + * + * @param float $goods_weight 商品重量 + * @param float $goods_amount 商品金额 + * @param float $goods_number 商品数量 + * @return decimal + */ + function calculate($goods_weight, $goods_amount, $goods_number) + { + if ($this->configure['free_money'] > 0 && $goods_amount >= $this->configure['free_money']) + { + return 0; + } + else + { + $fee = $this->configure['base_fee']; + $this->configure['fee_compute_mode'] = !empty($this->configure['fee_compute_mode']) ? $this->configure['fee_compute_mode'] : 'by_weight'; + + if ($this->configure['fee_compute_mode'] == 'by_number') + { + $fee = $goods_number * $this->configure['item_fee']; + } + else + { + if ($goods_weight > 5) + { + $fee += 8 * $this->configure['step_fee']; + $fee += (ceil(($goods_weight - 5) / 0.5)) * $this->configure['step_fee1']; + } + else + { + if ($goods_weight > 1) + { + $fee += (ceil(($goods_weight - 1) / 0.5)) * $this->configure['step_fee']; + } + } + } + + + return $fee; + } + } + + /** + * 查询发货状态 + * 该配送方式不支持查询发货状态 + * + * @access public + * @param string $invoice_sn 发货单号 + * @return string + */ + function query($invoice_sn) + { + return $invoice_sn; + } + + /** + * 当保价比例以%出现时,计算保价费用 + * + * @access public + * @param decimal $tatal_price 需要保价的商品总价 + * @param decimal $insure_rate 保价计算比例 + * + * @return decimal $price 保价费用 + */ + function calculate_insure($total_price, $insure_rate) + { + $total_price = ceil($total_price); + $price = $total_price * $insure_rate; + if ($price < 1) + { + $price = 1; + } + return ceil($price); + } +} + +?> \ No newline at end of file diff --git a/includes/modules/shipping/post_mail.php b/includes/modules/shipping/post_mail.php new file mode 100644 index 0000000..cbd76a1 --- /dev/null +++ b/includes/modules/shipping/post_mail.php @@ -0,0 +1,166 @@ + 'item_fee', 'value'=>4), + array('name' => 'base_fee', 'value'=>3.5), + array('name' => 'step_fee', 'value'=>2), + array('name' => 'step_fee1', 'value'=>2.5), + array('name' => 'pack_fee', 'value'=>0), + ); + + /* 模式编辑器 */ + $modules[$i]['print_model'] = 2; + + /* 打印单背景 */ + $modules[$i]['print_bg'] = ''; + + /* 打印快递单标签位置信息 */ + $modules[$i]['config_lable'] = ''; + + return; +} + +/** + * 邮局平邮费用计算方式: 每公斤资费 × 包裹重量 + 挂号费3.00 + 邮单费0.5 + 包装费(按实际收取) + 保价费 + * + * 保价费 由客户自愿选择,保价费为订单产品价值的1%。客户选择不保价,则保价费=0 + * + */ +class post_mail +{ + /*------------------------------------------------------ */ + //-- PUBLIC ATTRIBUTEs + /*------------------------------------------------------ */ + + /** + * 配置信息 + */ + var $configure; + + /*------------------------------------------------------ */ + //-- PUBLIC METHODs + /*------------------------------------------------------ */ + + /** + * 构造函数 + * + * @param: $configure[array] 配送方式的参数的数组 + * + * @return null + */ + function post_mail($cfg=array()) + { + foreach ($cfg AS $key=>$val) + { + $this->configure[$val['name']] = $val['value']; + } + } + + /** + * 计算订单的配送费用的函数 + * + * @param float $goods_weight 商品重量 + * @param float $goods_amount 商品金额 + * @param float $goods_number 商品件数 + * @return decimal + */ + function calculate($goods_weight, $goods_amount, $goods_number) + { + if ($this->configure['free_money'] > 0 && $goods_amount >= $this->configure['free_money']) + { + return 0; + } + else + { + /* 基本费用 */ + $fee = $this->configure['base_fee'] + $this->configure['pack_fee']; + $this->configure['fee_compute_mode'] = !empty($this->configure['fee_compute_mode']) ? $this->configure['fee_compute_mode'] : 'by_weight'; + + if ($this->configure['fee_compute_mode'] == 'by_number') + { + $fee = $goods_number * ($this->configure['item_fee'] + $this->configure['pack_fee']); + } + else + { + if ($goods_weight > 5) + { + $fee += 4 * $this->configure['step_fee']; + $fee += (ceil(($goods_weight - 5))) * $this->configure['step_fee1']; + } + else + { + if ($goods_weight > 1) + { + $fee += (ceil(($goods_weight - 1))) * $this->configure['step_fee']; + } + } + } + + + return $fee; + } + } + + /** + * 查询发货状态 + * 该配送方式不支持查询发货状态 + * + * @access public + * @param string $invoice_sn 发货单号 + * @return string + */ + function query($invoice_sn) + { + return $invoice_sn; + } +} + +?> \ No newline at end of file diff --git a/includes/modules/shipping/presswork.php b/includes/modules/shipping/presswork.php new file mode 100644 index 0000000..ac917f1 --- /dev/null +++ b/includes/modules/shipping/presswork.php @@ -0,0 +1,158 @@ +$val) + { + $this->configure[$val['name']] = $val['value']; + } + } + + /** + * 计算订单的配送费用的函数 + * + * @param float $goods_weight 商品重量 + * @param float $goods_amount 商品金额 + * @return decimal + */ + function calculate($goods_weight, $goods_amount) + { + if ($this->configure['free_money'] > 0 && $goods_amount >= $this->configure['free_money']) + { + return 0; + } + else + { + $fee = $goods_weight * 4 + 3.4; + + if ($goods_weight > 0.1) + { + $fee += (ceil(($goods_weight - 0.1) / 0.1)) * 0.4; + } + + return $fee; + } + } + + /** + * 查询发货状态 + * 该配送方式不支持查询发货状态 + * + * @access public + * @param string $invoice_sn 发货单号 + * @return string + */ + function query($invoice_sn) + { + return $invoice_sn; + } + + /** + * 当保价比例以%出现时,计算保价费用 + * + * @access public + * @param decimal $tatal_price 需要保价的商品总价 + * @param decimal $insure_rate 保价计算比例 + * + * @return decimal $price 保价费用 + */ + function calculate_insure($total_price, $insure_rate) + { + $total_price = ceil($total_price); + $price = $total_price * $insure_rate; + if ($price < 1) + { + $price = 1; + } + return ceil($price); + } +} + +?> \ No newline at end of file diff --git a/includes/modules/shipping/sf_express.php b/includes/modules/shipping/sf_express.php new file mode 100644 index 0000000..61ae5a0 --- /dev/null +++ b/includes/modules/shipping/sf_express.php @@ -0,0 +1,161 @@ + 'item_fee', 'value'=>20),/* 单件商品的配送费用 */ + array('name' => 'base_fee', 'value'=>15), /* 1000克以内的价格 */ + array('name' => 'step_fee', 'value'=>2), /* 续重每1000克增加的价格 */ + ); + + /* 模式编辑器 */ + $modules[$i]['print_model'] = 2; + + /* 打印单背景 */ + $modules[$i]['print_bg'] = '/images/receipt/dly_sf_express.jpg'; + + /* 打印快递单标签位置信息 */ + $modules[$i]['config_lable'] = 't_shop_name,' . $_LANG['lable_box']['shop_name'] . ',150,29,112,137,b_shop_name||,||t_shop_address,' . $_LANG['lable_box']['shop_address'] . ',268,55,105,168,b_shop_address||,||t_shop_tel,' . $_LANG['lable_box']['shop_tel'] . ',55,25,177,224,b_shop_tel||,||t_customer_name,' . $_LANG['lable_box']['customer_name'] . ',78,23,299,265,b_customer_name||,||t_customer_address,' . $_LANG['lable_box']['customer_address'] . ',271,94,104,293,b_customer_address||,||'; + + return; +} + +/** + * 顺丰速运费用计算方式: 起点到终点 * 重量(kg) + * ==================================================================================== + * -浙江,上海,江苏地区为15元/公斤,续重(2元/公斤) + * -续重每500克或其零数 (具体请上顺丰速运网站查询:http://www.sf-express.com/sfwebapp/price.jsp 客服电话 4008111111) + * + * ------------------------------------------------------------------------------------- + */ + +class sf_express +{ + /*------------------------------------------------------ */ + //-- PUBLIC ATTRIBUTEs + /*------------------------------------------------------ */ + + /** + * 配置信息参数 + */ + var $configure; + + /*------------------------------------------------------ */ + //-- PUBLIC METHODs + /*------------------------------------------------------ */ + + /** + * 构造函数 + * + * @param: $configure[array] 配送方式的参数的数组 + * + * @return null + */ + function sf_express($cfg=array()) + { + foreach ($cfg AS $key=>$val) + { + $this->configure[$val['name']] = $val['value']; + } + + } + + /** + * 计算订单的配送费用的函数 + * + * @param float $goods_weight 商品重量 + * @param float $goods_amount 商品金额 + * @param float $goods_number 商品数量 + * @return decimal + */ + function calculate($goods_weight, $goods_amount, $goods_number) + { + if ($this->configure['free_money'] > 0 && $goods_amount >= $this->configure['free_money']) + { + return 0; + } + else + { + @$fee = $this->configure['base_fee']; + $this->configure['fee_compute_mode'] = !empty($this->configure['fee_compute_mode']) ? $this->configure['fee_compute_mode'] : 'by_weight'; + + if ($this->configure['fee_compute_mode'] == 'by_number') + { + $fee = $goods_number * $this->configure['item_fee']; + } + else + { + if ($goods_weight > 1) + { + $fee += (ceil(($goods_weight - 1))) * $this->configure['step_fee']; + } + } + // $_SESSION['cart_weight'] = $goods_weight; + return $fee; + } + } + + /** + * 查询快递状态 + * + * @access public + * @return string 查询窗口的链接地址 + */ + function query($invoice_sn) + { + $form_str = '' .$invoice_sn. ''; + return $form_str; + } +} + +?> \ No newline at end of file diff --git a/includes/modules/shipping/sto_express.php b/includes/modules/shipping/sto_express.php new file mode 100644 index 0000000..7bd5201 --- /dev/null +++ b/includes/modules/shipping/sto_express.php @@ -0,0 +1,166 @@ + 'item_fee', 'value'=>15), /* 单件商品的配送费用 */ + array('name' => 'base_fee', 'value'=>15), /* 1000克以内的价格 */ + array('name' => 'step_fee', 'value'=>5), /* 续重每1000克增加的价格 */ + ); + + /* 模式编辑器 */ + $modules[$i]['print_model'] = 2; + + /* 打印单背景 */ + $modules[$i]['print_bg'] = '/images/receipt/dly_sto_express.jpg'; + + /* 打印快递单标签位置信息 */ + $modules[$i]['config_lable'] = 't_shop_address,' . $_LANG['lable_box']['shop_address'] . ',235,48,131,152,b_shop_address||,||t_shop_name,' . $_LANG['lable_box']['shop_name'] . ',237,26,131,200,b_shop_name||,||t_shop_tel,' . $_LANG['lable_box']['shop_tel'] . ',96,36,144,257,b_shop_tel||,||t_customer_post,' . $_LANG['lable_box']['customer_post'] . ',86,23,578,268,b_customer_post||,||t_customer_address,' . $_LANG['lable_box']['customer_address'] . ',232,49,434,149,b_customer_address||,||t_customer_name,' . $_LANG['lable_box']['customer_name'] . ',151,27,449,231,b_customer_name||,||t_customer_tel,' . $_LANG['lable_box']['customer_tel'] . ',90,32,452,261,b_customer_tel||,||'; + + return; +} + +/** + * 申通快递费用计算方式: + * ==================================================================================== + * - 江浙沪地区统一资费: 1公斤以内15元, 每增加1公斤加5-6元, 云南为8元 + * - 其他地区统一资费: 1公斤以内18元, 每增加1公斤加5-6元, 云南为8元 + * - 对于体大质轻的包裹,我们将按照航空运输协会的规定,根据体积和实际重量中较重的一种收费,需将包的长、宽、高、相乘,再除以6000 + * - (具体资费请上此网站查询:http://www.car365.cn/fee.asp 客服电话:021-52238886) + * ------------------------------------------------------------------------------------- + * + */ +class sto_express +{ + /*------------------------------------------------------ */ + //-- PUBLIC ATTRIBUTEs + /*------------------------------------------------------ */ + + /** + * 配置信息参数 + */ + var $configure; + + /*------------------------------------------------------ */ + //-- PUBLIC METHODs + /*------------------------------------------------------ */ + + /** + * 构造函数 + * + * @param: $configure[array] 配送方式的参数的数组 + * + * @return null + */ + function sto_express($cfg=array()) + { + foreach ($cfg AS $key=>$val) + { + $this->configure[$val['name']] = $val['value']; + } + } + + /** + * 计算订单的配送费用的函数 + * + * @param float $goods_weight 商品重量 + * @param float $goods_amount 商品金额 + * @param float $goods_amount 商品件数 + * @return decimal + */ + function calculate($goods_weight, $goods_amount, $goods_number) + { + if ($this->configure['free_money'] > 0 && $goods_amount >= $this->configure['free_money']) + { + return 0; + } + else + { + @$fee = $this->configure['base_fee']; + $this->configure['fee_compute_mode'] = !empty($this->configure['fee_compute_mode']) ? $this->configure['fee_compute_mode'] : 'by_weight'; + + if ($this->configure['fee_compute_mode'] == 'by_number') + { + $fee = $goods_number * $this->configure['item_fee']; + } + else + { + if ($goods_weight > 1) + { + $fee += (ceil(($goods_weight - 1))) * $this->configure['step_fee']; + } + } + + return $fee; + } + } + + /** + * 查询快递状态 + * + * @access public + * @param string $invoice_sn 发货单号 + * @return string 查询窗口的链接地址 + */ + function query($invoice_sn) + { + $str = '
    '. + '","\n",$invoice_sn). '" />'. + '' .$invoice_sn. ''. + '
    '; + + return $str; + } +} + +?> \ No newline at end of file diff --git a/includes/modules/shipping/yto.php b/includes/modules/shipping/yto.php new file mode 100644 index 0000000..679ff01 --- /dev/null +++ b/includes/modules/shipping/yto.php @@ -0,0 +1,162 @@ + 'item_fee', 'value'=>10), /* 单件商品的配送价格 */ + array('name' => 'base_fee', 'value'=>5), /* 1000克以内的价格 */ + array('name' => 'step_fee', 'value'=>5), /* 续重每1000克增加的价格 */ + ); + + /* 模式编辑器 */ + $modules[$i]['print_model'] = 2; + + /* 打印单背景 */ + $modules[$i]['print_bg'] = '/images/receipt/dly_yto.jpg'; + + /* 打印快递单标签位置信息 */ + $modules[$i]['config_lable'] = 't_shop_province,' . $_LANG['lable_box']['shop_province'] . ',132,24,279.6,105.7,b_shop_province||,||t_shop_name,' . $_LANG['lable_box']['shop_name'] . ',268,29,142.95,133.85,b_shop_name||,||t_shop_address,' . $_LANG['lable_box']['shop_address'] . ',346,40,67.3,199.95,b_shop_address||,||t_shop_city,' . $_LANG['lable_box']['shop_city'] . ',64,35,223.8,163.95,b_shop_city||,||t_shop_district,' . $_LANG['lable_box']['shop_district'] . ',56,35,314.9,164.25,b_shop_district||,||t_pigeon,' . $_LANG['lable_box']['pigeon'] . ',21,21,143.1,263.2,b_pigeon||,||t_customer_name,' . $_LANG['lable_box']['customer_name'] . ',89,25,488.65,121.05,b_customer_name||,||t_customer_tel,' . $_LANG['lable_box']['customer_tel'] . ',136,21,656,110.6,b_customer_tel||,||t_customer_mobel,' . $_LANG['lable_box']['customer_mobel'] . ',137,21,655.6,132.8,b_customer_mobel||,||t_customer_province,' . $_LANG['lable_box']['customer_province'] . ',115,24,480.2,173.5,b_customer_province||,||t_customer_city,' . $_LANG['lable_box']['customer_city'] . ',60,27,609.3,172.5,b_customer_city||,||t_customer_district,' . $_LANG['lable_box']['customer_district'] . ',58,28,696.8,173.25,b_customer_district||,||t_customer_post,' . $_LANG['lable_box']['customer_post'] . ',93,21,701.1,240.25,b_customer_post||,||'; + + return; +} + +class yto +{ + /*------------------------------------------------------ */ + //-- PUBLIC ATTRIBUTEs + /*------------------------------------------------------ */ + + /** + * 配置信息 + */ + var $configure; + + /*------------------------------------------------------ */ + //-- PUBLIC METHODs + /*------------------------------------------------------ */ + + /** + * 构造函数 + * + * @param: $configure[array] 配送方式的参数的数组 + * + * @return null + */ + function yto($cfg = array()) + { + foreach ($cfg AS $key=>$val) + { + $this->configure[$val['name']] = $val['value']; + } + } + + /** + * 计算订单的配送费用的函数 + * + * @param float $goods_weight 商品重量 + * @param float $goods_amount 商品金额 + * @param float $goods_number 商品件数 + * @return decimal + */ + function calculate($goods_weight, $goods_amount, $goods_number) + { + if ($this->configure['free_money'] > 0 && $goods_amount >= $this->configure['free_money']) + { + return 0; + } + else + { + @$fee = $this->configure['base_fee']; + $this->configure['fee_compute_mode'] = !empty($this->configure['fee_compute_mode']) ? $this->configure['fee_compute_mode'] : 'by_weight'; + + if ($this->configure['fee_compute_mode'] == 'by_number') + { + $fee = $goods_number * $this->configure['item_fee']; + } + else + { + if ($goods_weight > 1) + { + $fee += (ceil(($goods_weight - 1))) * $this->configure['step_fee']; + } + } + + return $fee; + } + } + + + /** + * 查询发货状态 + * + * @access public + * @param string $invoice_sn 发货单号 + * @return string + */ + function query($invoice_sn) + { + //圆通快递查询会判断链接来源,目前的查询无法生效。 + $str = '
    '. + ''. + '' .$invoice_sn. ''. + '
    '; + + return $str; + + } +} + +?> \ No newline at end of file diff --git a/includes/modules/shipping/zto.php b/includes/modules/shipping/zto.php new file mode 100644 index 0000000..aa25be6 --- /dev/null +++ b/includes/modules/shipping/zto.php @@ -0,0 +1,183 @@ + 'item_fee', 'value'=>15), /* 单件商品配送的价格 */ + array('name' => 'base_fee', 'value'=>10), /* 1000克以内的价格 */ + array('name' => 'step_fee', 'value'=>5), /* 续重每1000克增加的价格 */ + ); + + /* 模式编辑器 */ + $modules[$i]['print_model'] = 2; + + /* 打印单背景 */ + $modules[$i]['print_bg'] = '/images/receipt/dly_zto.jpg'; + + /* 打印快递单标签位置信息 */ + $modules[$i]['config_lable'] = 't_shop_province,' . $_LANG['lable_box']['shop_province'] . ',116,30,296.55,117.2,b_shop_province||,||t_customer_province,' . $_LANG['lable_box']['customer_province'] . ',114,32,649.95,114.3,b_customer_province||,||t_shop_address,' . $_LANG['lable_box']['shop_address'] . ',260,57,151.75,152.05,b_shop_address||,||t_shop_name,' . $_LANG['lable_box']['shop_name'] . ',259,28,152.65,212.4,b_shop_name||,||t_shop_tel,' . $_LANG['lable_box']['shop_tel'] . ',131,37,138.65,246.5,b_shop_tel||,||t_customer_post,' . $_LANG['lable_box']['customer_post'] . ',104,39,659.2,242.2,b_customer_post||,||t_customer_tel,' . $_LANG['lable_box']['customer_tel'] . ',158,22,461.9,241.9,b_customer_tel||,||t_customer_mobel,' . $_LANG['lable_box']['customer_mobel'] . ',159,21,463.25,265.4,b_customer_mobel||,||t_customer_name,' . $_LANG['lable_box']['customer_name'] . ',109,32,498.9,115.8,b_customer_name||,||t_customer_address,' . $_LANG['lable_box']['customer_address'] . ',264,58,499.6,150.1,b_customer_address||,||t_months,' . $_LANG['lable_box']['months'] . ',35,23,135.85,392.8,b_months||,||t_day,' . $_LANG['lable_box']['day'] . ',24,23,180.1,392.8,b_day||,||'; + + return; +} + +class zto +{ + /*------------------------------------------------------ */ + //-- PUBLIC ATTRIBUTEs + /*------------------------------------------------------ */ + + /** + * 配置信息 + */ + var $configure; + + /*------------------------------------------------------ */ + //-- PUBLIC METHODs + /*------------------------------------------------------ */ + + /** + * 构造函数 + * + * @param: $configure[array] 配送方式的参数的数组 + * + * @return null + */ + function zto($cfg = array()) + { + foreach ($cfg AS $key=>$val) + { + $this->configure[$val['name']] = $val['value']; + } + } + + /** + * 计算订单的配送费用的函数 + * + * @param float $goods_weight 商品重量 + * @param float $goods_amount 商品金额 + * @param float $goods_number 商品件数 + * @return decimal + */ + function calculate($goods_weight, $goods_amount, $goods_number) + { + if ($this->configure['free_money'] > 0 && $goods_amount >= $this->configure['free_money']) + { + return 0; + } + else + { + @$fee = $this->configure['base_fee']; + $this->configure['fee_compute_mode'] = !empty($this->configure['fee_compute_mode']) ? $this->configure['fee_compute_mode'] : 'by_weight'; + + if ($this->configure['fee_compute_mode'] == 'by_number') + { + $fee = $goods_number * $this->configure['item_fee']; + } + else + { + if ($goods_weight > 1) + { + $fee += (ceil(($goods_weight - 1))) * $this->configure['step_fee']; + } + } + + return $fee; + } + } + + /** + * 查询发货状态 + * + * @access public + * @param string $invoice_sn 发货单号 + * @return string + */ + function query($invoice_sn) + { + $str = '
    '. + '","\n",$invoice_sn). '" />'. + '' .$invoice_sn. ''. + ''. + ''. + '
    '; + + return $str; + } + + /** + * 计算保价费用 + * 保价费不低于100元,保价金额不得高于10000元,保价金额超过10000元的,超过的部分无效 + * @access public + * @param int $goods_amount 保价费用 + * @param int $insure 保价比例 + * + * @return void + */ + function calculate_insure ($goods_amount, $insure) + { + if ($goods_amount > 10000) + { + $goods_amount = 10000; + } + + $fee = $goods_amount * $insure; + + if ($fee < 100) + { + $fee = 100; + } + + return $fee; + } + +} + +?> \ No newline at end of file diff --git "a/includes/modules/\346\234\200\346\250\241\346\235\277 - \344\270\223\346\263\250\347\275\221\345\272\227\345\225\206\345\237\216\346\250\241\346\235\277\345\210\266\344\275\234\344\270\216\345\256\232\345\210\266\345\274\200\345\217\221.url" "b/includes/modules/\346\234\200\346\250\241\346\235\277 - \344\270\223\346\263\250\347\275\221\345\272\227\345\225\206\345\237\216\346\250\241\346\235\277\345\210\266\344\275\234\344\270\216\345\256\232\345\210\266\345\274\200\345\217\221.url" new file mode 100644 index 0000000..f60bd51 --- /dev/null +++ "b/includes/modules/\346\234\200\346\250\241\346\235\277 - \344\270\223\346\263\250\347\275\221\345\272\227\345\225\206\345\237\216\346\250\241\346\235\277\345\210\266\344\275\234\344\270\216\345\256\232\345\210\266\345\274\200\345\217\221.url" @@ -0,0 +1,9 @@ +[DEFAULT] +BASEURL=http://www.zuimoban.com/ +[{000214A0-0000-0000-C000-000000000046}] +Prop3=19,2 +[InternetShortcut] +URL=http://www.zuimoban.com/ +IDList= +IconFile=http://www.zuimoban.com/favicon.ico +IconIndex=1 diff --git a/includes/shopex_json.php b/includes/shopex_json.php new file mode 100644 index 0000000..473f41b --- /dev/null +++ b/includes/shopex_json.php @@ -0,0 +1,845 @@ + + * @author Matt Knapp + * @author Brett Stimmerman + * @copyright 2005 Michal Migurski + * @version CVS: $Id: json.php 2997 2007-06-04 07:31:16Z flaboy $ + * @license http://www.opensource.org/licenses/bsd-license.php + * @link http://pear.php.net/pepr/pepr-proposal-show.php?id=198 + */ + +if(!function_exists('json_encode')){ + function json_encode($value){ + $json = new Services_JSON(); + return $json->encode($value); + } +} +if(!function_exists('json_decode')){ + function json_decode($json_value,$bool = false){ + $json = new Services_JSON(); + return $json->decode($json_value,$bool); + } +} + +/** + * Marker constant for Services_JSON::decode(), used to flag stack state + */ +define('SERVICES_JSON_SLICE', 1); + +/** + * Marker constant for Services_JSON::decode(), used to flag stack state + */ +define('SERVICES_JSON_IN_STR', 2); + +/** + * Marker constant for Services_JSON::decode(), used to flag stack state + */ +define('SERVICES_JSON_IN_ARR', 3); + +/** + * Marker constant for Services_JSON::decode(), used to flag stack state + */ +define('SERVICES_JSON_IN_OBJ', 4); + +/** + * Marker constant for Services_JSON::decode(), used to flag stack state + */ +define('SERVICES_JSON_IN_CMT', 5); + +/** + * Behavior switch for Services_JSON::decode() + */ +define('SERVICES_JSON_LOOSE_TYPE', 16); + +/** + * Behavior switch for Services_JSON::decode() + */ +define('SERVICES_JSON_SUPPRESS_ERRORS', 32); + +/** + * Converts to and from JSON format. + * + * Brief example of use: + * + * + * // create a new instance of Services_JSON + * $json = new Services_JSON(); + * + * // convert a complexe value to JSON notation, and send it to the browser + * $value = array('foo', 'bar', array(1, 2, 'baz'), array(3, array(4))); + * $output = $json->encode($value); + * + * print($output); + * // prints: ["foo","bar",[1,2,"baz"],[3,[4]]] + * + * // accept incoming POST data, assumed to be in JSON notation + * $input = file_get_contents('php://input', 1000000); + * $value = $json->decode($input); + * + */ +class Services_JSON +{ + /** + * constructs a new JSON instance + * + * @param int $use object behavior flags; combine with boolean-OR + * + * possible values: + * - SERVICES_JSON_LOOSE_TYPE: loose typing. + * "{...}" syntax creates associative arrays + * instead of objects in decode(). + * - SERVICES_JSON_SUPPRESS_ERRORS: error suppression. + * Values which can't be encoded (e.g. resources) + * appear as NULL instead of throwing errors. + * By default, a deeply-nested resource will + * bubble up with an error, so all return values + * from encode() should be checked with isError() + */ + function Services_JSON($use = 0) + { + $this->use = $use; + } + + /** + * convert a string from one UTF-16 char to one UTF-8 char + * + * Normally should be handled by mb_convert_encoding, but + * provides a slower PHP-only method for installations + * that lack the multibye string extension. + * + * @param string $utf16 UTF-16 character + * @return string UTF-8 character + * @access private + */ + function utf162utf8($utf16) + { + // oh please oh please oh please oh please oh please + if(function_exists('mb_convert_encoding')) { + return mb_convert_encoding($utf16, 'UTF-8', 'UTF-16'); + } + + $bytes = (ord($utf16{0}) << 8) | ord($utf16{1}); + + switch(true) { + case ((0x7F & $bytes) == $bytes): + // this case should never be reached, because we are in ASCII range + // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 + return chr(0x7F & $bytes); + + case (0x07FF & $bytes) == $bytes: + // return a 2-byte UTF-8 character + // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 + return chr(0xC0 | (($bytes >> 6) & 0x1F)) + . chr(0x80 | ($bytes & 0x3F)); + + case (0xFFFF & $bytes) == $bytes: + // return a 3-byte UTF-8 character + // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 + return chr(0xE0 | (($bytes >> 12) & 0x0F)) + . chr(0x80 | (($bytes >> 6) & 0x3F)) + . chr(0x80 | ($bytes & 0x3F)); + } + + // ignoring UTF-32 for now, sorry + return ''; + } + + /** + * convert a string from one UTF-8 char to one UTF-16 char + * + * Normally should be handled by mb_convert_encoding, but + * provides a slower PHP-only method for installations + * that lack the multibye string extension. + * + * @param string $utf8 UTF-8 character + * @return string UTF-16 character + * @access private + */ + function utf82utf16($utf8) + { + // oh please oh please oh please oh please oh please + if(function_exists('mb_convert_encoding')) { + return mb_convert_encoding($utf8, 'UTF-16', 'UTF-8'); + } + + switch(strlen($utf8)) { + case 1: + // this case should never be reached, because we are in ASCII range + // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 + return $utf8; + + case 2: + // return a UTF-16 character from a 2-byte UTF-8 char + // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 + return chr(0x07 & (ord($utf8{0}) >> 2)) + . chr((0xC0 & (ord($utf8{0}) << 6)) + | (0x3F & ord($utf8{1}))); + + case 3: + // return a UTF-16 character from a 3-byte UTF-8 char + // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 + return chr((0xF0 & (ord($utf8{0}) << 4)) + | (0x0F & (ord($utf8{1}) >> 2))) + . chr((0xC0 & (ord($utf8{1}) << 6)) + | (0x7F & ord($utf8{2}))); + } + + // ignoring UTF-32 for now, sorry + return ''; + } + + /** + * encodes an arbitrary variable into JSON format + * + * @param mixed $var any number, boolean, string, array, or object to be encoded. + * see argument 1 to Services_JSON() above for array-parsing behavior. + * if var is a strng, note that encode() always expects it + * to be in ASCII or UTF-8 format! + * + * @return mixed JSON string representation of input var or an error if a problem occurs + * @access public + */ + function encode($var) + { + switch (gettype($var)) { + case 'boolean': + return $var ? 'true' : 'false'; + + case 'NULL': + return 'null'; + + case 'integer': + return (int) $var; + + case 'double': + case 'float': + return (float) $var; + + case 'string': + // STRINGS ARE EXPECTED TO BE IN ASCII OR UTF-8 FORMAT + $ascii = ''; + $strlen_var = strlen($var); + + /* + * Iterate over every character in the string, + * escaping with a slash or encoding to UTF-8 where necessary + */ + for ($c = 0; $c < $strlen_var; ++$c) { + + $ord_var_c = ord($var{$c}); + + switch (true) { + case $ord_var_c == 0x08: + $ascii .= '\b'; + break; + case $ord_var_c == 0x09: + $ascii .= '\t'; + break; + case $ord_var_c == 0x0A: + $ascii .= '\n'; + break; + case $ord_var_c == 0x0C: + $ascii .= '\f'; + break; + case $ord_var_c == 0x0D: + $ascii .= '\r'; + break; + + case $ord_var_c == 0x22: + case $ord_var_c == 0x2F: + case $ord_var_c == 0x5C: + // double quote, slash, slosh + $ascii .= '\\'.$var{$c}; + break; + + case (($ord_var_c >= 0x20) && ($ord_var_c <= 0x7F)): + // characters U-00000000 - U-0000007F (same as ASCII) + $ascii .= $var{$c}; + break; + + case (($ord_var_c & 0xE0) == 0xC0): + // characters U-00000080 - U-000007FF, mask 110XXXXX + // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 + $char = pack('C*', $ord_var_c, ord($var{$c + 1})); + $c += 1; + $utf16 = $this->utf82utf16($char); + $ascii .= sprintf('\u%04s', bin2hex($utf16)); + break; + + case (($ord_var_c & 0xF0) == 0xE0): + // characters U-00000800 - U-0000FFFF, mask 1110XXXX + // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 + $char = pack('C*', $ord_var_c, + ord($var{$c + 1}), + ord($var{$c + 2})); + $c += 2; + $utf16 = $this->utf82utf16($char); + $ascii .= sprintf('\u%04s', bin2hex($utf16)); + break; + + case (($ord_var_c & 0xF8) == 0xF0): + // characters U-00010000 - U-001FFFFF, mask 11110XXX + // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 + $char = pack('C*', $ord_var_c, + ord($var{$c + 1}), + ord($var{$c + 2}), + ord($var{$c + 3})); + $c += 3; + $utf16 = $this->utf82utf16($char); + $ascii .= sprintf('\u%04s', bin2hex($utf16)); + break; + + case (($ord_var_c & 0xFC) == 0xF8): + // characters U-00200000 - U-03FFFFFF, mask 111110XX + // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 + $char = pack('C*', $ord_var_c, + ord($var{$c + 1}), + ord($var{$c + 2}), + ord($var{$c + 3}), + ord($var{$c + 4})); + $c += 4; + $utf16 = $this->utf82utf16($char); + $ascii .= sprintf('\u%04s', bin2hex($utf16)); + break; + + case (($ord_var_c & 0xFE) == 0xFC): + // characters U-04000000 - U-7FFFFFFF, mask 1111110X + // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 + $char = pack('C*', $ord_var_c, + ord($var{$c + 1}), + ord($var{$c + 2}), + ord($var{$c + 3}), + ord($var{$c + 4}), + ord($var{$c + 5})); + $c += 5; + $utf16 = $this->utf82utf16($char); + $ascii .= sprintf('\u%04s', bin2hex($utf16)); + break; + } + } + + return '"'.$ascii.'"'; + + case 'array': + /* + * As per JSON spec if any array key is not an integer + * we must treat the the whole array as an object. We + * also try to catch a sparsely populated associative + * array with numeric keys here because some JS engines + * will create an array with empty indexes up to + * max_index which can cause memory issues and because + * the keys, which may be relevant, will be remapped + * otherwise. + * + * As per the ECMA and JSON specification an object may + * have any string as a property. Unfortunately due to + * a hole in the ECMA specification if the key is a + * ECMA reserved word or starts with a digit the + * parameter is only accessible using ECMAScript's + * bracket notation. + */ + + // treat as a JSON object + if (is_array($var) && count($var) && (array_keys($var) !== range(0, sizeof($var) - 1))) { + $properties = array_map(array($this, 'name_value'), + array_keys($var), + array_values($var)); + + foreach($properties as $property) { + if(Services_JSON::isError($property)) { + return $property; + } + } + + return '{' . join(',', $properties) . '}'; + } + + // treat it like a regular array + $elements = array_map(array($this, 'encode'), $var); + + foreach($elements as $element) { + if(Services_JSON::isError($element)) { + return $element; + } + } + + return '[' . join(',', $elements) . ']'; + + case 'object': + $vars = get_object_vars($var); + + $properties = array_map(array($this, 'name_value'), + array_keys($vars), + array_values($vars)); + + foreach($properties as $property) { + if(Services_JSON::isError($property)) { + return $property; + } + } + + return '{' . join(',', $properties) . '}'; + + default: + return ($this->use & SERVICES_JSON_SUPPRESS_ERRORS) + ? 'null' + : new Services_JSON_Error(gettype($var)." can not be encoded as JSON string"); + } + } + + /** + * array-walking function for use in generating JSON-formatted name-value pairs + * + * @param string $name name of key to use + * @param mixed $value reference to an array element to be encoded + * + * @return string JSON-formatted name-value pair, like '"name":value' + * @access private + */ + function name_value($name, $value) + { + $encoded_value = $this->encode($value); + + if(Services_JSON::isError($encoded_value)) { + return $encoded_value; + } + + return $this->encode(strval($name)) . ':' . $encoded_value; + } + + /** + * reduce a string by removing leading and trailing comments and whitespace + * + * @param $str string string value to strip of comments and whitespace + * + * @return string string value stripped of comments and whitespace + * @access private + */ + function reduce_string($str) + { + $str = preg_replace(array( + + // eliminate single line comments in '// ...' form + '#^\s*//(.+)$#m', + + // eliminate multi-line comments in '/* ... */' form, at start of string + '#^\s*/\*(.+)\*/#Us', + + // eliminate multi-line comments in '/* ... */' form, at end of string + '#/\*(.+)\*/\s*$#Us' + + ), '', $str); + + // eliminate extraneous space + return trim($str); + } + + /** + * decodes a JSON string into appropriate variable + * + * @param string $str JSON-formatted string + * boolean $bool True: return Array false:return Obj ::::Add by Alex 2007.01.30 + * + * @return mixed number, boolean, string, array, or object + * corresponding to given JSON input string. + * See argument 1 to Services_JSON() above for object-output behavior. + * Note that decode() always returns strings + * in ASCII or UTF-8 format! + * @access public + * Revision History + * + * + */ + function decode($str,$bool) + { + $str = $this->reduce_string($str); + $s_brackets = false; //Add by Alex + switch (strtolower($str)) { + case 'true': + return true; + + case 'false': + return false; + + case 'null': + return null; + + default: + $m = array(); + + if (is_numeric($str)) { + // Lookie-loo, it's a number + + // This would work on its own, but I'm trying to be + // good about returning integers where appropriate: + // return (float)$str; + + // Return float or int, as appropriate + return ((float)$str == (integer)$str) + ? (integer)$str + : (float)$str; + + } elseif (preg_match('/^("|\').*(\1)$/s', $str, $m) && $m[1] == $m[2]) { + // STRINGS RETURNED IN UTF-8 FORMAT + $delim = substr($str, 0, 1); + $chrs = substr($str, 1, -1); + $utf8 = ''; + $strlen_chrs = strlen($chrs); + + for ($c = 0; $c < $strlen_chrs; ++$c) { + + $substr_chrs_c_2 = substr($chrs, $c, 2); + $ord_chrs_c = ord($chrs{$c}); + + switch (true) { + case $substr_chrs_c_2 == '\b': + $utf8 .= chr(0x08); + ++$c; + break; + case $substr_chrs_c_2 == '\t': + $utf8 .= chr(0x09); + ++$c; + break; + case $substr_chrs_c_2 == '\n': + $utf8 .= chr(0x0A); + ++$c; + break; + case $substr_chrs_c_2 == '\f': + $utf8 .= chr(0x0C); + ++$c; + break; + case $substr_chrs_c_2 == '\r': + $utf8 .= chr(0x0D); + ++$c; + break; + + case $substr_chrs_c_2 == '\\"': + case $substr_chrs_c_2 == '\\\'': + case $substr_chrs_c_2 == '\\\\': + case $substr_chrs_c_2 == '\\/': + if (($delim == '"' && $substr_chrs_c_2 != '\\\'') || + ($delim == "'" && $substr_chrs_c_2 != '\\"')) { + $utf8 .= $chrs{++$c}; + } + break; + + case preg_match('/\\\u[0-9A-F]{4}/i', substr($chrs, $c, 6)): + // single, escaped unicode character + $utf16 = chr(hexdec(substr($chrs, ($c + 2), 2))) + . chr(hexdec(substr($chrs, ($c + 4), 2))); + $utf8 .= $this->utf162utf8($utf16); + $c += 5; + break; + + case ($ord_chrs_c >= 0x20) && ($ord_chrs_c <= 0x7F): + $utf8 .= $chrs{$c}; + break; + + case ($ord_chrs_c & 0xE0) == 0xC0: + // characters U-00000080 - U-000007FF, mask 110XXXXX + //see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 + $utf8 .= substr($chrs, $c, 2); + ++$c; + break; + + case ($ord_chrs_c & 0xF0) == 0xE0: + // characters U-00000800 - U-0000FFFF, mask 1110XXXX + // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 + $utf8 .= substr($chrs, $c, 3); + $c += 2; + break; + + case ($ord_chrs_c & 0xF8) == 0xF0: + // characters U-00010000 - U-001FFFFF, mask 11110XXX + // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 + $utf8 .= substr($chrs, $c, 4); + $c += 3; + break; + + case ($ord_chrs_c & 0xFC) == 0xF8: + // characters U-00200000 - U-03FFFFFF, mask 111110XX + // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 + $utf8 .= substr($chrs, $c, 5); + $c += 4; + break; + + case ($ord_chrs_c & 0xFE) == 0xFC: + // characters U-04000000 - U-7FFFFFFF, mask 1111110X + // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 + $utf8 .= substr($chrs, $c, 6); + $c += 5; + break; + + } + + } + + return $utf8; + + } elseif (preg_match('/^\[.*\]$/s', $str) || preg_match('/^\{.*\}$/s', $str)) { + // array, or object notation + + if ($str{0} == '['||$bool) { //Modified by Alex + if ($str{0} == '[') $s_brackets = true; //Add by Alex + $stk = array(SERVICES_JSON_IN_ARR); + $arr = array(); + } else { + if ($this->use & SERVICES_JSON_LOOSE_TYPE) { + $stk = array(SERVICES_JSON_IN_OBJ); + $obj = array(); + } else { + $stk = array(SERVICES_JSON_IN_OBJ); + $obj = new stdClass(); + } + } + + array_push($stk, array('what' => SERVICES_JSON_SLICE, + 'where' => 0, + 'delim' => false)); + + $chrs = substr($str, 1, -1); + $chrs = $this->reduce_string($chrs); + + if ($chrs == '') { + if (reset($stk) == SERVICES_JSON_IN_ARR) { + return $arr; + + } else { + return $obj; + + } + } + + //print("\nparsing {$chrs}\n"); + + $strlen_chrs = strlen($chrs); + + for ($c = 0; $c <= $strlen_chrs; ++$c) { + + $top = end($stk); + $substr_chrs_c_2 = substr($chrs, $c, 2); + + if (($c == $strlen_chrs) || (($chrs{$c} == ',') && ($top['what'] == SERVICES_JSON_SLICE))) { + // found a comma that is not inside a string, array, etc., + // OR we've reached the end of the character list + $slice = substr($chrs, $top['where'], ($c - $top['where'])); + array_push($stk, array('what' => SERVICES_JSON_SLICE, 'where' => ($c + 1), 'delim' => false)); + //print("Found split at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n"); + + if (reset($stk) == SERVICES_JSON_IN_ARR) { + // we are in an array, so just push an element onto the stack + //Modified by Alex ---Begin + if($s_brackets){ + array_push($arr, $this->decode($slice,$bool)); + } + else{ + $parts = array(); + + if (preg_match('/^\s*(["\'].*[^\\\]["\'])\s*:\s*(\S.*),?$/Uis', $slice, $parts)) { + // "name":value pair + $key = $this->decode($parts[1],$bool); + $val = $this->decode($parts[2],$bool); + + $arr[$key] = $val; + } elseif (preg_match('/^\s*(\w+)\s*:\s*(\S.*),?$/Uis', $slice, $parts)) { + // name:value pair, where name is unquoted + $key = $parts[1]; + $val = $this->decode($parts[2],$bool); + + $arr[$key] = $val; + } + } + //Modified by Alex --- End + + } elseif (reset($stk) == SERVICES_JSON_IN_OBJ) { + // we are in an object, so figure + // out the property name and set an + // element in an associative array, + // for now + $parts = array(); + + if (preg_match('/^\s*(["\'].*[^\\\]["\'])\s*:\s*(\S.*),?$/Uis', $slice, $parts)) { + // "name":value pair + $key = $this->decode($parts[1],$bool); + $val = $this->decode($parts[2],$bool); + + if ($this->use & SERVICES_JSON_LOOSE_TYPE) { + $obj[$key] = $val; + } else { + $obj->$key = $val; + } + } elseif (preg_match('/^\s*(\w+)\s*:\s*(\S.*),?$/Uis', $slice, $parts)) { + // name:value pair, where name is unquoted + $key = $parts[1]; + $val = $this->decode($parts[2],$bool); + + if ($this->use & SERVICES_JSON_LOOSE_TYPE) { + $obj[$key] = $val; + } else { + $obj->$key = $val; + } + } + + } + + } elseif ((($chrs{$c} == '"') || ($chrs{$c} == "'")) && ($top['what'] != SERVICES_JSON_IN_STR)) { + // found a quote, and we are not inside a string + array_push($stk, array('what' => SERVICES_JSON_IN_STR, 'where' => $c, 'delim' => $chrs{$c})); + //print("Found start of string at {$c}\n"); + + } elseif (($chrs{$c} == $top['delim']) && + ($top['what'] == SERVICES_JSON_IN_STR) && + ((strlen(substr($chrs, 0, $c)) - strlen(rtrim(substr($chrs, 0, $c), '\\'))) % 2 != 1)) { + // found a quote, we're in a string, and it's not escaped + // we know that it's not escaped becase there is _not_ an + // odd number of backslashes at the end of the string so far + array_pop($stk); + //print("Found end of string at {$c}: ".substr($chrs, $top['where'], (1 + 1 + $c - $top['where']))."\n"); + + } elseif (($chrs{$c} == '[') && + in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) { + // found a left-bracket, and we are in an array, object, or slice + array_push($stk, array('what' => SERVICES_JSON_IN_ARR, 'where' => $c, 'delim' => false)); + //print("Found start of array at {$c}\n"); + + } elseif (($chrs{$c} == ']') && ($top['what'] == SERVICES_JSON_IN_ARR)) { + // found a right-bracket, and we're in an array + array_pop($stk); + //print("Found end of array at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n"); + + } elseif (($chrs{$c} == '{') && + in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) { + // found a left-brace, and we are in an array, object, or slice + array_push($stk, array('what' => SERVICES_JSON_IN_OBJ, 'where' => $c, 'delim' => false)); + //print("Found start of object at {$c}\n"); + + } elseif (($chrs{$c} == '}') && ($top['what'] == SERVICES_JSON_IN_OBJ)) { + // found a right-brace, and we're in an object + array_pop($stk); + //print("Found end of object at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n"); + + } elseif (($substr_chrs_c_2 == '/*') && + in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) { + // found a comment start, and we are in an array, object, or slice + array_push($stk, array('what' => SERVICES_JSON_IN_CMT, 'where' => $c, 'delim' => false)); + $c++; + //print("Found start of comment at {$c}\n"); + + } elseif (($substr_chrs_c_2 == '*/') && ($top['what'] == SERVICES_JSON_IN_CMT)) { + // found a comment end, and we're in one now + array_pop($stk); + $c++; + + for ($i = $top['where']; $i <= $c; ++$i) + $chrs = substr_replace($chrs, ' ', $i, 1); + + //print("Found end of comment at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n"); + + } + + } + + if (reset($stk) == SERVICES_JSON_IN_ARR) { + return $arr; + + } elseif (reset($stk) == SERVICES_JSON_IN_OBJ) { + return $obj; + + } + + } + } + } + + /** + * @todo Ultimately, this should just call PEAR::isError() + */ + function isError($data, $code = null) + { + if (class_exists('pear')) { + return PEAR::isError($data, $code); + } elseif (is_object($data) && (get_class($data) == 'services_json_error' || + is_subclass_of($data, 'services_json_error'))) { + return true; + } + + return false; + } +} + +if (class_exists('PEAR_Error')) { + + class Services_JSON_Error extends PEAR_Error + { + function Services_JSON_Error($message = 'unknown error', $code = null, + $mode = null, $options = null, $userinfo = null) + { + parent::PEAR_Error($message, $code, $mode, $options, $userinfo); + } + } + +} else { + + /** + * @todo Ultimately, this class shall be descended from PEAR_Error + */ + class Services_JSON_Error + { + function Services_JSON_Error($message = 'unknown error', $code = null, + $mode = null, $options = null, $userinfo = null) + { + + } + } + +} + +?> diff --git "a/includes/\346\234\200\346\250\241\346\235\277 - \344\270\223\346\263\250\347\275\221\345\272\227\345\225\206\345\237\216\346\250\241\346\235\277\345\210\266\344\275\234\344\270\216\345\256\232\345\210\266\345\274\200\345\217\221.url" "b/includes/\346\234\200\346\250\241\346\235\277 - \344\270\223\346\263\250\347\275\221\345\272\227\345\225\206\345\237\216\346\250\241\346\235\277\345\210\266\344\275\234\344\270\216\345\256\232\345\210\266\345\274\200\345\217\221.url" new file mode 100644 index 0000000..f60bd51 --- /dev/null +++ "b/includes/\346\234\200\346\250\241\346\235\277 - \344\270\223\346\263\250\347\275\221\345\272\227\345\225\206\345\237\216\346\250\241\346\235\277\345\210\266\344\275\234\344\270\216\345\256\232\345\210\266\345\274\200\345\217\221.url" @@ -0,0 +1,9 @@ +[DEFAULT] +BASEURL=http://www.zuimoban.com/ +[{000214A0-0000-0000-C000-000000000046}] +Prop3=19,2 +[InternetShortcut] +URL=http://www.zuimoban.com/ +IDList= +IconFile=http://www.zuimoban.com/favicon.ico +IconIndex=1 diff --git a/index.php b/index.php new file mode 100644 index 0000000..7f8bca5 --- /dev/null +++ b/index.php @@ -0,0 +1,410 @@ +table('goods') . ' AS g ' . + "Where g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0 AND g.is_new = 1 AND (" . $cat_id . " OR " . get_extension_goods($cat_id) .")"; +$cats = get_children($cat_id); +$where = !empty($cats) ? "AND ($cats OR " . get_extension_goods($cats) . ") " : ''; + + +$sql .=$where." ORDER BY g.sort_order, g.last_update DESC LIMIT $num "; + + $res = $GLOBALS['db']->getAll($sql); + + $goods = array(); + foreach ($res AS $idx => $row) + { + $goods[$idx]['id'] = $row['article_id']; + $goods[$idx]['id'] = $row['goods_id']; + $goods[$idx]['name'] = $row['goods_name']; + $goods[$idx]['brief'] = $row['goods_brief']; + $goods[$idx]['brand_name'] = $row['brand_name']; + $goods[$idx]['goods_style_name'] = add_style($row['goods_name'],$row['goods_name_style']); + + $goods[$idx]['short_name'] = $GLOBALS['_CFG']['goods_name_length'] > 0 ? + sub_str($row['goods_name'], $GLOBALS['_CFG']['goods_name_length']) : $row['goods_name']; + $goods[$idx]['short_style_name'] = add_style($goods[$idx]['short_name'],$row['goods_name_style']); + $goods[$idx]['market_price'] = price_format($row['market_price']); + $goods[$idx]['shop_price'] = price_format($row['shop_price']); + $goods[$idx]['thumb'] = empty($row['goods_thumb']) ? $GLOBALS['_CFG']['no_picture'] : $row['goods_thumb']; + $goods[$idx]['goods_img'] = empty($row['goods_img']) ? $GLOBALS['_CFG']['no_picture'] : $row['goods_img']; + $goods[$idx]['url'] = build_uri('goods', array('gid' => $row['goods_id']), $row['goods_name']); + } + return $goods; +} + + +/** + * ECSHOP 首页文件 + * ============================================================================ + * 版权所有 2014-2020 上海显心智能化科技发展有限公司,并保留所有权利。 + * 网站地址: http://www.shitwb.net; + * ---------------------------------------------------------------------------- + *。 + * ============================================================================ + * $Author: liuhui $ + * $Id: index.php 17063 2010-03-25 06:35:46Z liuhui $ +*/ + +define('IN_ECS', true); + +require(dirname(__FILE__) . '/includes/init.php'); + +if ((DEBUG_MODE & 2) != 2) +{ + $smarty->caching = true; +} +$ua = strtolower($_SERVER['HTTP_USER_AGENT']); + +$uachar = "/(nokia|sony|ericsson|mot|samsung|sgh|lg|philips|panasonic|alcatel|lenovo|cldc|midp|mobile)/i"; + +if(($ua == '' || preg_match($uachar, $ua))&& !strpos(strtolower($_SERVER['REQUEST_URI']),'wap')) +{ + $Loaction = 'mobile/'; + + if (!empty($Loaction)) + { + ecs_header("Location: $Loaction\n"); + + exit; + } + +} +/*------------------------------------------------------ */ +//-- Shopex系统地址转换 +/*------------------------------------------------------ */ +if (!empty($_GET['gOo'])) +{ + if (!empty($_GET['gcat'])) + { + /* 商品分类。*/ + $Loaction = 'category.php?id=' . $_GET['gcat']; + } + elseif (!empty($_GET['acat'])) + { + /* 文章分类。*/ + $Loaction = 'article_cat.php?id=' . $_GET['acat']; + } + elseif (!empty($_GET['goodsid'])) + { + /* 商品详情。*/ + $Loaction = 'goods.php?id=' . $_GET['goodsid']; + } + elseif (!empty($_GET['articleid'])) + { + /* 文章详情。*/ + $Loaction = 'article.php?id=' . $_GET['articleid']; + } + + if (!empty($Loaction)) + { + ecs_header("Location: $Loaction\n"); + + exit; + } +} + +//判断是否有ajax请求 +$act = !empty($_GET['act']) ? $_GET['act'] : ''; +if ($act == 'cat_rec') +{ + $rec_array = array(1 => 'best', 2 => 'new', 3 => 'hot'); + $rec_type = !empty($_REQUEST['rec_type']) ? intval($_REQUEST['rec_type']) : '1'; + $cat_id = !empty($_REQUEST['cid']) ? intval($_REQUEST['cid']) : '0'; + include_once('includes/cls_json.php'); + $json = new JSON; + $result = array('error' => 0, 'content' => '', 'type' => $rec_type, 'cat_id' => $cat_id); + + $children = get_children($cat_id); + $smarty->assign($rec_array[$rec_type] . '_goods', get_category_recommend_goods($rec_array[$rec_type], $children)); // 推荐商品 + $smarty->assign('cat_rec_sign', 1); + $result['content'] = $smarty->fetch('library/recommend_' . $rec_array[$rec_type] . '.lbi'); + die($json->encode($result)); +} + +/*------------------------------------------------------ */ +//-- 判断是否存在缓存,如果存在则调用缓存,反之读取相应内容 +/*------------------------------------------------------ */ +/* 缓存编号 */ +$cache_id = sprintf('%X', crc32($_SESSION['user_rank'] . '-' . $_CFG['lang'])); + +if (!$smarty->is_cached('index.dwt', $cache_id)) +{ + assign_template(); + + $position = assign_ur_here(); + $smarty->assign('page_title', $position['title']); // 页面标题 + $smarty->assign('ur_here', $position['ur_here']); // 当前位置 + + /* meta information */ + $smarty->assign('keywords', htmlspecialchars($_CFG['shop_keywords'])); + $smarty->assign('description', htmlspecialchars($_CFG['shop_desc'])); + $smarty->assign('flash_theme', $_CFG['flash_theme']); // Flash轮播图片模板 + + $smarty->assign('feed_url', ($_CFG['rewrite'] == 1) ? 'feed.xml' : 'feed.php'); // RSS URL + + $smarty->assign('categories', get_categories_tree()); // 分类树 + $smarty->assign('helps', get_shop_help()); // 网店帮助 + $smarty->assign('top_goods', get_top10()); // 销售排行 + + $smarty->assign('best_goods', get_recommend_goods('best')); // 推荐商品 + $smarty->assign('new_goods', get_recommend_goods('new')); // 最新商品 + $smarty->assign('hot_goods', get_recommend_goods('hot')); // 热点文章 + $smarty->assign('promotion_goods', get_promote_goods()); // 特价商品 + $smarty->assign('brand_list', get_brands()); + $smarty->assign('promotion_info', get_promotion_info()); // 增加一个动态显示所有促销信息的标签栏 + + $smarty->assign('invoice_list', index_get_invoice_query()); // 发货查询 + $smarty->assign('new_articles', index_get_new_articles()); // 最新文章 + $smarty->assign('group_buy_goods', index_get_group_buy()); // 团购商品 + $smarty->assign('auction_list', index_get_auction()); // 拍卖活动 + $smarty->assign('shop_notice', $_CFG['shop_notice']); // 商店公告 + + + + $smarty->assign('cat_id742_new_goods', index_get_cat_id_goods_new_list(742,4)); + $smarty->assign('cat_id745_new_goods', index_get_cat_id_goods_new_list(745,4)); + + + /* 首页主广告设置 */ + $smarty->assign('index_ad', $_CFG['index_ad']); + if ($_CFG['index_ad'] == 'cus') + { + $sql = 'SELECT ad_type, content, url FROM ' . $ecs->table("ad_custom") . ' WHERE ad_status = 1'; + $ad = $db->getRow($sql, true); + $smarty->assign('ad', $ad); + } + + /* links */ + $links = index_get_links(); + $smarty->assign('img_links', $links['img']); + $smarty->assign('txt_links', $links['txt']); + $smarty->assign('data_dir', DATA_DIR); // 数据目录 + + /* 首页推荐分类 */ + $cat_recommend_res = $db->getAll("SELECT c.cat_id, c.cat_name, cr.recommend_type FROM " . $ecs->table("cat_recommend") . " AS cr INNER JOIN " . $ecs->table("category") . " AS c ON cr.cat_id=c.cat_id"); + if (!empty($cat_recommend_res)) + { + $cat_rec_array = array(); + foreach($cat_recommend_res as $cat_recommend_data) + { + $cat_rec[$cat_recommend_data['recommend_type']][] = array('cat_id' => $cat_recommend_data['cat_id'], 'cat_name' => $cat_recommend_data['cat_name']); + } + $smarty->assign('cat_rec', $cat_rec); + } + + /* 页面中的动态内容 */ + assign_dynamic('index'); +} + +$smarty->display('index.dwt', $cache_id); + +/*------------------------------------------------------ */ +//-- PRIVATE FUNCTIONS +/*------------------------------------------------------ */ + +/** + * 调用发货单查询 + * + * @access private + * @return array + */ +function index_get_invoice_query() +{ + $sql = 'SELECT o.order_sn, o.invoice_no, s.shipping_code FROM ' . $GLOBALS['ecs']->table('order_info') . ' AS o' . + ' LEFT JOIN ' . $GLOBALS['ecs']->table('shipping') . ' AS s ON s.shipping_id = o.shipping_id' . + " WHERE invoice_no > '' AND shipping_status = " . SS_SHIPPED . + ' ORDER BY shipping_time DESC LIMIT 10'; + $all = $GLOBALS['db']->getAll($sql); + + foreach ($all AS $key => $row) + { + $plugin = ROOT_PATH . 'includes/modules/shipping/' . $row['shipping_code'] . '.php'; + + if (file_exists($plugin)) + { + include_once($plugin); + + $shipping = new $row['shipping_code']; + $all[$key]['invoice_no'] = $shipping->query((string)$row['invoice_no']); + } + } + + clearstatcache(); + + return $all; +} + +/** + * 获得最新的文章列表。 + * + * @access private + * @return array + */ +function index_get_new_articles() +{ + $sql = 'SELECT a.article_id, a.title, ac.cat_name, a.add_time, a.file_url, a.open_type, ac.cat_id, ac.cat_name ' . + ' FROM ' . $GLOBALS['ecs']->table('article') . ' AS a, ' . + $GLOBALS['ecs']->table('article_cat') . ' AS ac' . + ' WHERE a.is_open = 1 AND a.cat_id = ac.cat_id AND ac.cat_type = 1' . + ' ORDER BY a.article_type DESC, a.add_time DESC LIMIT ' . $GLOBALS['_CFG']['article_number']; + $res = $GLOBALS['db']->getAll($sql); + + $arr = array(); + foreach ($res AS $idx => $row) + { + $arr[$idx]['id'] = $row['article_id']; + $arr[$idx]['title'] = $row['title']; + $arr[$idx]['short_title'] = $GLOBALS['_CFG']['article_title_length'] > 0 ? + sub_str($row['title'], $GLOBALS['_CFG']['article_title_length']) : $row['title']; + $arr[$idx]['cat_name'] = $row['cat_name']; + $arr[$idx]['add_time'] = local_date($GLOBALS['_CFG']['date_format'], $row['add_time']); + $arr[$idx]['url'] = $row['open_type'] != 1 ? + build_uri('article', array('aid' => $row['article_id']), $row['title']) : trim($row['file_url']); + $arr[$idx]['cat_url'] = build_uri('article_cat', array('acid' => $row['cat_id']), $row['cat_name']); + } + + return $arr; +} + +/** + * 获得最新的团购活动 + * + * @access private + * @return array + */ +function index_get_group_buy() +{ + $time = gmtime(); + $limit = get_library_number('group_buy', 'index'); + + $group_buy_list = array(); + if ($limit > 0) + { + $sql = 'SELECT gb.act_id AS group_buy_id, gb.goods_id, gb.ext_info, gb.goods_name, g.goods_thumb, g.goods_img ' . + 'FROM ' . $GLOBALS['ecs']->table('goods_activity') . ' AS gb, ' . + $GLOBALS['ecs']->table('goods') . ' AS g ' . + "WHERE gb.act_type = '" . GAT_GROUP_BUY . "' " . + "AND g.goods_id = gb.goods_id " . + "AND gb.start_time <= '" . $time . "' " . + "AND gb.end_time >= '" . $time . "' " . + "AND g.is_delete = 0 " . + "ORDER BY gb.act_id DESC " . + "LIMIT $limit" ; + $res = $GLOBALS['db']->query($sql); + + while ($row = $GLOBALS['db']->fetchRow($res)) + { + /* 如果缩略图为空,使用默认图片 */ + $row['goods_img'] = get_image_path($row['goods_id'], $row['goods_img']); + $row['thumb'] = get_image_path($row['goods_id'], $row['goods_thumb'], true); + + /* 根据价格阶梯,计算最低价 */ + $ext_info = unserialize($row['ext_info']); + $price_ladder = $ext_info['price_ladder']; + if (!is_array($price_ladder) || empty($price_ladder)) + { + $row['last_price'] = price_format(0); + } + else + { + foreach ($price_ladder AS $amount_price) + { + $price_ladder[$amount_price['amount']] = $amount_price['price']; + } + } + ksort($price_ladder); + $row['last_price'] = price_format(end($price_ladder)); + $row['url'] = build_uri('group_buy', array('gbid' => $row['group_buy_id'])); + $row['short_name'] = $GLOBALS['_CFG']['goods_name_length'] > 0 ? + sub_str($row['goods_name'], $GLOBALS['_CFG']['goods_name_length']) : $row['goods_name']; + $row['short_style_name'] = add_style($row['short_name'],''); + $group_buy_list[] = $row; + } + } + + return $group_buy_list; +} + +/** + * 取得拍卖活动列表 + * @return array + */ +function index_get_auction() +{ + $now = gmtime(); + $limit = get_library_number('auction', 'index'); + $sql = "SELECT a.act_id, a.goods_id, a.goods_name, a.ext_info, g.goods_thumb ". + "FROM " . $GLOBALS['ecs']->table('goods_activity') . " AS a," . + $GLOBALS['ecs']->table('goods') . " AS g" . + " WHERE a.goods_id = g.goods_id" . + " AND a.act_type = '" . GAT_AUCTION . "'" . + " AND a.is_finished = 0" . + " AND a.start_time <= '$now'" . + " AND a.end_time >= '$now'" . + " AND g.is_delete = 0" . + " ORDER BY a.start_time DESC" . + " LIMIT $limit"; + $res = $GLOBALS['db']->query($sql); + + $list = array(); + while ($row = $GLOBALS['db']->fetchRow($res)) + { + $ext_info = unserialize($row['ext_info']); + $arr = array_merge($row, $ext_info); + $arr['formated_start_price'] = price_format($arr['start_price']); + $arr['formated_end_price'] = price_format($arr['end_price']); + $arr['thumb'] = get_image_path($row['goods_id'], $row['goods_thumb'], true); + $arr['url'] = build_uri('auction', array('auid' => $arr['act_id'])); + $arr['short_name'] = $GLOBALS['_CFG']['goods_name_length'] > 0 ? + sub_str($arr['goods_name'], $GLOBALS['_CFG']['goods_name_length']) : $arr['goods_name']; + $arr['short_style_name'] = add_style($arr['short_name'],''); + $list[] = $arr; + } + + return $list; +} + +/** + * 获得所有的友情链接 + * + * @access private + * @return array + */ +function index_get_links() +{ + $sql = 'SELECT link_logo, link_name, link_url FROM ' . $GLOBALS['ecs']->table('friend_link') . ' ORDER BY show_order'; + $res = $GLOBALS['db']->getAll($sql); + + $links['img'] = $links['txt'] = array(); + + foreach ($res AS $row) + { + if (!empty($row['link_logo'])) + { + $links['img'][] = array('name' => $row['link_name'], + 'url' => $row['link_url'], + 'logo' => $row['link_logo']); + } + else + { + $links['txt'][] = array('name' => $row['link_name'], + 'url' => $row['link_url']); + } + } + + return $links; +} + +?> \ No newline at end of file diff --git a/message.php b/message.php new file mode 100644 index 0000000..88406fc --- /dev/null +++ b/message.php @@ -0,0 +1,250 @@ + 0) + { + include_once('includes/cls_captcha.php'); + $validator = new captcha(); + if (!$validator->check_word($_POST['captcha'])) + { + show_message($_LANG['invalid_captcha']); + } + } + else + { + /* 没有验证码时,用时间来限制机器人发帖或恶意发评论 */ + if (!isset($_SESSION['send_time'])) + { + $_SESSION['send_time'] = 0; + } + + $cur_time = gmtime(); + if (($cur_time - $_SESSION['send_time']) < 30) // 小于30秒禁止发评论 + { + show_message($_LANG['cmt_spam_warning']); + } + } + $user_name = ''; + if (empty($_POST['anonymous']) && !empty($_SESSION['user_name'])) + { + $user_name = $_SESSION['user_name']; + } + elseif (!empty($_POST['anonymous']) && !isset($_POST['user_name'])) + { + $user_name = $_LANG['anonymous']; + } + elseif (empty($_POST['user_name'])) + { + $user_name = $_LANG['anonymous']; + } + else + { + $user_name = htmlspecialchars(trim($_POST['user_name'])); + } + + $user_id = !empty($_SESSION['user_id']) ? $_SESSION['user_id'] : 0; + $message = array( + 'user_id' => $user_id, + 'user_name' => $user_name, + 'user_email' => isset($_POST['user_email']) ? htmlspecialchars(trim($_POST['user_email'])) : '', + 'msg_type' => isset($_POST['msg_type']) ? intval($_POST['msg_type']) : 0, + 'msg_title' => isset($_POST['msg_title']) ? trim($_POST['msg_title']) : '', + 'msg_content' => isset($_POST['msg_content']) ? trim($_POST['msg_content']) : '', + 'order_id' => 0, + 'msg_area' => 1, + 'upload' => array() + ); + + if (add_message($message)) + { + if (intval($_CFG['captcha']) & CAPTCHA_MESSAGE) + { + unset($_SESSION[$validator->session_word]); + } + else + { + $_SESSION['send_time'] = $cur_time; + } + $msg_info = $_CFG['message_check'] ? $_LANG['message_submit_wait'] : $_LANG['message_submit_done']; + show_message($msg_info, $_LANG['message_list_lnk'], 'message.php'); + } + else + { + $err->show($_LANG['message_list_lnk'], 'message.php'); + } +} + +if ($action == 'default') +{ + assign_template(); + $position = assign_ur_here(0, $_LANG['message_board']); + $smarty->assign('page_title', $position['title']); // 页面标题 + $smarty->assign('ur_here', $position['ur_here']); // 当前位置 + $smarty->assign('helps', get_shop_help()); // 网店帮助 + + $smarty->assign('categories', get_categories_tree()); // 分类树 + $smarty->assign('top_goods', get_top10()); // 销售排行 + $smarty->assign('cat_list', cat_list(0, 0, true, 2, false)); + $smarty->assign('brand_list', get_brand_list()); + $smarty->assign('promotion_info', get_promotion_info()); + + $smarty->assign('enabled_mes_captcha', (intval($_CFG['captcha']) & CAPTCHA_MESSAGE)); + + $sql = "SELECT COUNT(*) FROM " .$GLOBALS['ecs']->table('comment')." WHERE STATUS =1 AND comment_type =0 "; + $record_count = $db->getOne($sql); + $sql = "SELECT COUNT(*) FROM " .$GLOBALS['ecs']->table('feedback')." WHERE `msg_area`='1' AND `msg_status` = '1' "; + $record_count += $db->getOne($sql); + + /* 获取留言的数量 */ + $page = isset($_REQUEST['page']) ? intval($_REQUEST['page']) : 1; + $pagesize = get_library_number('message_list', 'message_board'); + $pager = get_pager('message.php', array(), $record_count, $page, $pagesize); + $msg_lists = get_msg_list($pagesize, $pager['start']); + assign_dynamic('message_board'); + $smarty->assign('rand', mt_rand()); + $smarty->assign('msg_lists', $msg_lists); + $smarty->assign('pager', $pager); + $smarty->display('message_board.dwt'); +} + +/** + * 获取留言的详细信息 + * + * @param integer $num + * @param integer $start + * + * @return array + */ +function get_msg_list($num, $start) +{ + /* 获取留言数据 */ + $msg = array(); + + $mysql_ver = $GLOBALS['db']->version(); + + if($mysql_ver > '3.2.3') + { + $sql = "(SELECT 'comment' AS tablename, comment_id AS ID, content AS msg_content, null AS msg_title, add_time AS msg_time, id_value AS id_value, comment_rank AS comment_rank, null AS message_img, user_name AS user_name, '6' AS msg_type "; + $sql .= " FROM " .$GLOBALS['ecs']->table('comment'); + $sql .= "WHERE STATUS =1 AND comment_type =0) "; + $sql .= " UNION "; + $sql .= "(SELECT 'feedback' AS tablename, msg_id AS ID, msg_content AS msg_content, msg_title AS msg_title, msg_time AS msg_time, null AS id_value, null AS comment_rank, message_img AS message_img, user_name AS user_name, msg_type AS msg_type "; + $sql .= " FROM " .$GLOBALS['ecs']->table('feedback'); + $sql .= " WHERE `msg_area`='1' AND `msg_status` = '1') "; + $sql .= " ORDER BY msg_time DESC "; + } + else + { + $con_sql = "SELECT 'comment' AS tablename, comment_id AS ID, content AS msg_content, null AS msg_title, add_time AS msg_time, id_value AS id_value, comment_rank AS comment_rank, null AS message_img, user_name AS user_name, '6' AS msg_type "; + $con_sql .= " FROM " .$GLOBALS['ecs']->table('comment'); + $con_sql .= "WHERE STATUS =1 AND comment_type =0 "; + + $fee_sql = "SELECT 'feedback' AS tablename, msg_id AS ID, msg_content AS msg_content, msg_title AS msg_title, msg_time AS msg_time, null AS id_value, null AS comment_rank, message_img AS message_img, user_name AS user_name, msg_type AS msg_type "; + $fee_sql .= " FROM " .$GLOBALS['ecs']->table('feedback'); + $fee_sql .= " WHERE `msg_area`='1' AND `msg_status` = '1' "; + + + $cre_con = "CREATE TEMPORARY TABLE tmp_table ".$con_sql; + $GLOBALS['db']->query($cre_con); + + $cre_con = "INSERT INTO tmp_table ".$fee_sql; + $GLOBALS['db']->query($cre_con); + + $sql = "SELECT * FROM " .$GLOBALS['ecs']->table('tmp_table') . " ORDER BY msg_time DESC "; + } + + $res = $GLOBALS['db']->SelectLimit($sql, $num, $start); + + while ($rows = $GLOBALS['db']->fetchRow($res)) + { + for($i = 0; $i < count($rows); $i++) + { + $msg[$rows['msg_time']]['user_name'] = htmlspecialchars($rows['user_name']); + $msg[$rows['msg_time']]['msg_content'] = str_replace('\r\n', '
    ', htmlspecialchars($rows['msg_content'])); + $msg[$rows['msg_time']]['msg_content'] = str_replace('\n', '
    ', $msg[$rows['msg_time']]['msg_content']); + $msg[$rows['msg_time']]['msg_time'] = local_date($GLOBALS['_CFG']['time_format'], $rows['msg_time']); + $msg[$rows['msg_time']]['msg_type'] = $GLOBALS['_LANG']['message_type'][$rows['msg_type']]; + $msg[$rows['msg_time']]['msg_title'] = nl2br(htmlspecialchars($rows['msg_title'])); + $msg[$rows['msg_time']]['message_img'] = $rows['message_img']; + $msg[$rows['msg_time']]['tablename'] = $rows['tablename']; + + if(isset($rows['order_id'])) + { + $msg[$rows['msg_time']]['order_id'] = $rows['order_id']; + } + $msg[$rows['msg_time']]['comment_rank'] = $rows['comment_rank']; + $msg[$rows['msg_time']]['id_value'] = $rows['id_value']; + + /*如果id_value为true为商品评论,根据商品id取出商品名称*/ + if($rows['id_value']) + { + $sql_goods = "SELECT goods_name FROM ".$GLOBALS['ecs']->table('goods'); + $sql_goods .= "WHERE goods_id= ".$rows['id_value']; + $goods_res = $GLOBALS['db']->getRow($sql_goods); + $msg[$rows['msg_time']]['goods_name'] = $goods_res['goods_name']; + $msg[$rows['msg_time']]['goods_url'] = build_uri('goods', array('gid' => $rows['id_value']), $goods_res['goods_name']); + } + } + + $msg[$rows['msg_time']]['tablename'] = $rows['tablename']; + $id = $rows['ID']; + $reply = array(); + if(isset($msg[$rows['msg_time']]['tablename'])) + { + $table_name = $msg[$rows['msg_time']]['tablename']; + + if ($table_name == 'feedback') + { + $sql = "SELECT user_name AS re_name, user_email AS re_email, msg_time AS re_time, msg_content AS re_content ,parent_id". + " FROM " .$GLOBALS['ecs']->table('feedback') . + " WHERE parent_id = '" . $id. "'"; + } + else + { + $sql = 'SELECT user_name AS re_name, email AS re_email, add_time AS re_time, content AS re_content ,parent_id + FROM ' . $GLOBALS['ecs']->table('comment') . + " WHERE parent_id = $id "; + + } + $reply = $GLOBALS['db']->getRow($sql); + if ($reply) + { + $msg[$rows['msg_time']]['re_name'] = $reply['re_name']; + $msg[$rows['msg_time']]['re_email'] = $reply['re_email']; + $msg[$rows['msg_time']]['re_time'] = local_date($GLOBALS['_CFG']['time_format'], $reply['re_time']); + $msg[$rows['msg_time']]['re_content'] = nl2br(htmlspecialchars($reply['re_content'])); + } + } + + } + + return $msg; +} + +?> diff --git a/myship.php b/myship.php new file mode 100644 index 0000000..a112395 --- /dev/null +++ b/myship.php @@ -0,0 +1,97 @@ + 0) +{ + $consignee_list = get_consignee_list($_SESSION['user_id']); + + $choose['country'] = isset($_POST['country']) ? intval($_POST['country']) : $consignee_list[0]['country']; + $choose['province'] = isset($_POST['province']) ? intval($_POST['province']) : $consignee_list[0]['province']; + $choose['city'] = isset($_POST['city']) ? intval($_POST['city']) : $consignee_list[0]['city']; + $choose['district'] = isset($_POST['district']) ? intval($_POST['district']) : (isset($consignee_list[0]['district']) ? $consignee_list[0]['district'] : 0 ); +} +else +{ + $choose['country'] = isset($_POST['country']) ? intval($_POST['country']) : $_CFG['shop_country']; + $choose['province'] = isset($_POST['province']) ? intval($_POST['province']) : 2; + $choose['city'] = isset($_POST['city']) ? intval($_POST['city']) : 35; + $choose['district'] = isset($_POST['district']) ? intval($_POST['district']) : 417; +} + +/*------------------------------------------------------ */ +//-- PROCESSOR +/*------------------------------------------------------ */ + +assign_template(); +assign_dynamic('myship'); +$position = assign_ur_here(0, $_LANG['shopping_myship']); +$smarty->assign('page_title', $position['title']); // 页面标题 +$smarty->assign('ur_here', $position['ur_here']); // 当前位置 + +$smarty->assign('helps', get_shop_help()); // 网店帮助 +$smarty->assign('lang', $_LANG); + +$smarty->assign('choose', $choose); + +$province_list[NULL] = get_regions(1, $choose['country']); +$city_list[NULL] = get_regions(2, $choose['province']); +$district_list[NULL] = get_regions(3, $choose['city']); + +$smarty->assign('province_list', $province_list); +$smarty->assign('city_list', $city_list); +$smarty->assign('district_list', $district_list); + +/* 取得国家列表、商店所在国家、商店所在国家的省列表 */ +$smarty->assign('country_list', get_regions()); + +/* 取得配送列表 */ +$region = array($choose['country'], $choose['province'], $choose['city'], $choose['district']); +$shipping_list = available_shipping_list($region); +$cart_weight_price = 0; +$insure_disabled = true; +$cod_disabled = true; + +foreach ($shipping_list AS $key => $val) +{ + $shipping_cfg = unserialize_config($val['configure']); + $shipping_fee = shipping_fee($val['shipping_code'], unserialize($val['configure']), + $cart_weight_price['weight'], $cart_weight_price['amount']); + + $shipping_list[$key]['format_shipping_fee'] = price_format($shipping_fee, false); + $shipping_list[$key]['fee'] = $shipping_fee; + $shipping_list[$key]['free_money'] = price_format($shipping_cfg['free_money'], false); + $shipping_list[$key]['insure_formated'] = strpos($val['insure'], '%') === false ? + price_format($val['insure'], false) : $val['insure']; +} + +$smarty->assign('shipping_list', $shipping_list); + +$smarty->display('myship.dwt'); + +?> \ No newline at end of file diff --git a/package.php b/package.php new file mode 100644 index 0000000..8114ebe --- /dev/null +++ b/package.php @@ -0,0 +1,97 @@ +assign('page_title', $position['title']); // 页面标题 +$smarty->assign('ur_here', $position['ur_here']); // 当前位置 + +/* 读出所有礼包信息 */ + +$now = gmtime(); + +$sql = "SELECT * FROM " . $ecs->table('goods_activity'). " WHERE `start_time` <= '$now' AND `end_time` >= '$now' AND `act_type` = '4' ORDER BY `end_time`"; +$res = $db->query($sql); + +$list = array(); +while ($row = $db->fetchRow($res)) +{ + $row['start_time'] = local_date('Y-m-d H:i', $row['start_time']); + $row['end_time'] = local_date('Y-m-d H:i', $row['end_time']); + $ext_arr = unserialize($row['ext_info']); + unset($row['ext_info']); + if ($ext_arr) + { + foreach ($ext_arr as $key=>$val) + { + $row[$key] = $val; + } + } + + $sql = "SELECT pg.package_id, pg.goods_id, pg.goods_number, pg.admin_id, ". + " g.goods_sn, g.goods_name, g.market_price, g.goods_thumb, ". + " IFNULL(mp.user_price, g.shop_price * '$_SESSION[discount]') AS rank_price " . + " FROM " . $GLOBALS['ecs']->table('package_goods') . " AS pg ". + " LEFT JOIN ". $GLOBALS['ecs']->table('goods') . " AS g ". + " ON g.goods_id = pg.goods_id ". + " LEFT JOIN " . $GLOBALS['ecs']->table('member_price') . " AS mp ". + "ON mp.goods_id = g.goods_id AND mp.user_rank = '$_SESSION[user_rank]' ". + " WHERE pg.package_id = " . $row['act_id']. " ". + " ORDER BY pg.goods_id"; + + $goods_res = $GLOBALS['db']->getAll($sql); + + $subtotal = 0; + foreach($goods_res as $key => $val) + { + $goods_res[$key]['goods_thumb'] = get_image_path($val['goods_id'], $val['goods_thumb'], true); + $goods_res[$key]['market_price'] = price_format($val['market_price']); + $goods_res[$key]['rank_price'] = price_format($val['rank_price']); + $subtotal += $val['rank_price'] * $val['goods_number']; + } + + + $row['goods_list'] = $goods_res; + $row['subtotal'] = price_format($subtotal); + $row['saving'] = price_format(($subtotal - $row['package_price'])); + $row['package_price'] = price_format($row['package_price']); + + $list[] = $row; +} + +$smarty->assign('list', $list); + +$smarty->assign('helps', get_shop_help()); // 网店帮助 +$smarty->assign('lang', $_LANG); + +$smarty->assign('feed_url', ($_CFG['rewrite'] == 1) ? "feed-typepackage.xml" : 'feed.php?type=package'); // RSS URL +$smarty->display('package.dwt'); + diff --git a/pick_out.php b/pick_out.php new file mode 100644 index 0000000..bac6e25 --- /dev/null +++ b/pick_out.php @@ -0,0 +1,303 @@ + $value) + { + if (!is_numeric($key)) + { + unset($_GET['attr'][$key]); + continue; + } + $key = intval($key); + $_GET['attr'][$key] = htmlspecialchars($value); + } +} + +if (empty($cat_id)) +{ + /* 获取所有符合条件的商品类型 */ + $sql = "SELECT DISTINCT t.cat_id, t.cat_name " . + "FROM " . $ecs->table('goods_type') . " AS t, " . $ecs->table('attribute') . " AS a, " . $ecs->table('goods_attr') . " AS g " . + "WHERE t.cat_id = a.cat_id AND a.attr_id = g.attr_id AND t.enabled = 1"; + $rs = $db->query($sql); + + $in_cat = array(); + $cat_name = array(); + $in_goods = ''; + + while ($row = $db->fetchRow($rs)) + { + $condition[$row['cat_id']]['name'] = $row['cat_name']; + $in_cat[] = $row['cat_id']; + } + + $in_cat = "AND a.cat_id ".db_create_in($in_cat); + + /* 获取符合条件的属性 */ + $sql = "SELECT DISTINCT a.attr_id ". + "FROM ".$ecs->table('goods_attr')." AS g, ".$ecs->table('attribute') ." AS a ". + "WHERE a.attr_id = g.attr_id " . $in_cat; + + $in_attr = $db->getCol($sql); //符合条件attr_id; + $in_attr = 'AND g.attr_id '.db_create_in($in_attr); + + /* 获取所有属性值 */ + $sql = "SELECT DISTINCT g.attr_id, a.attr_name, a.cat_id, g.attr_value". + " FROM ".$ecs->table('goods_attr')." AS g, ". + $ecs->table('attribute') ." AS a". + " WHERE a.attr_id = g.attr_id ".$in_attr." ORDER BY cat_id"; + $rs = $db->query($sql); + + while ($row = $db->fetchRow($rs)) + { + if (empty($condition[$row['cat_id']]['cat'][$row['attr_id']]['cat_name'])) + { + $condition[$row['cat_id']]['cat'][$row['attr_id']]['cat_name'] = $row['attr_name']; + } + + $condition[$row['cat_id']]['cat'][$row['attr_id']]['list'][] = array('name'=>$row['attr_value'], 'url'=>'pick_out.php?cat_id='.$row['cat_id'].'&attr['.$row['attr_id'].']='.urlencode($row['attr_value'])); + } + + /* 获取商品总数 */ + $goods_count = $db->GetOne("SELECT COUNT(DISTINCT(goods_id)) FROM " . $ecs->table('goods_attr')); + /* 获取符合条件的商品id */ + //$sql = "SELECT DISTINCT goods_id FROM " .$ecs->table('goods_attr'). " LIMIT 100"; + $sql = "SELECT DISTINCT goods_id FROM " .$ecs->table('goods_attr'); + $in_goods = $db->GetCol($sql); + $in_goods = 'AND g.goods_id ' . db_create_in(implode(',', $in_goods)); + $url = "search.php?pickout=1"; +} +else +{ + /* 取得商品类型名称 */ + $sql = "SELECT cat_name FROM ".$ecs->table('goods_type')." WHERE cat_id = '$cat_id'"; + $cat_name = $db->GetOne($sql); + $condition[0]['name'] = $cat_name; + + $picks[] = array('name'=>''.$_LANG['goods_type'].':
    '.$cat_name, 'url'=>'pick_out.php'); + + $attr_picks = array(); //选择过的attr_id + + /* 处理属性,获取满足属性的goods_id */ + if (!empty($_GET['attr'])) + { + $attr_table = ''; + $attr_where = ''; + $attr_url = ''; + $i = 0; + $goods_result = ''; + foreach ($_GET['attr'] AS $key => $value) + { + $attr_url .= '&attr[' . $key . ']=' . $value; + + $attr_picks[] = $key; + if ($i > 0) + { + if (empty($goods_result)) + { + break; + } + $goods_result = $db->getCol("SELECT goods_id FROM " . $ecs->table("goods_attr") . " WHERE goods_id IN (" . implode(',' , $goods_result) . ") AND attr_id='$key' AND attr_value='$value'"); + } + else + { + $goods_result = $db->getCol("SELECT goods_id FROM " . $ecs->table("goods_attr") . " WHERE attr_id='$key' AND attr_value='$value'"); + } + $i++; + } + + /* 获取指定attr_id的名字 */ + $sql = "SELECT attr_id, attr_name FROM ".$ecs->table('attribute')." WHERE attr_id ".db_create_in(implode(',',$attr_picks)); + $rs = $db->query($sql); + while ($row = $db->fetchRow($rs)) + { + $picks[] = array('name'=>''.$row['attr_name'].':
    '.htmlspecialchars(urldecode($_GET['attr'][$row['attr_id']])), 'url'=>'pick_out.php?cat_id='.$cat_id.search_url($attr_picks, $row['attr_id'])); + } + + /* 查出数量 */ + $goods_count = count($goods_result); + /* 获取符合条件的goods_id */ + $in_goods = 'AND g.goods_id '.db_create_in(implode(',', $goods_result)); + } + else + { + /* 仅选择了商品类型的情况 */ + + /* 查出数量 */ + $goods_count = $db->GetOne("SELECT COUNT(distinct(g.goods_id)) FROM ".$ecs->table('goods_attr')." AS g, ".$ecs->table('attribute')." AS a WHERE g.attr_id = a.attr_id AND a.cat_id = '$cat_id' "); + + /* 防止结果过大,最多只查出前100个goods_id */ + + $sql = "SELECT DISTINCT g.goods_id FROM ".$ecs->table('goods_attr')." AS g, ".$ecs->table('attribute')." AS a WHERE g.attr_id = a.attr_id AND a.cat_id = '$cat_id' LIMIT 100"; + $in_goods = $db->GetCol($sql); + $in_goods = 'AND g.goods_id '.db_create_in(implode(',', $in_goods)); + + } + + /* 获取符合条件的属性 */ + $sql = "SELECT DISTINCT a.attr_id FROM ".$ecs->table('goods_attr')." AS g, ".$ecs->table('attribute') ." AS a ". + "WHERE a.attr_id = g.attr_id " . $in_goods; + + $in_attr = $db->GetCol($sql); // 符合条件attr_id; + $in_attr = array_diff($in_attr, $attr_picks); // 除去已经选择过的attr_id + $in_attr = 'AND g.attr_id '.db_create_in(implode(',', $in_attr)); + + /* 获取所有属性值 */ + $sql = "SELECT DISTINCT g.attr_id, a.attr_name, g.attr_value FROM ".$ecs->table('goods_attr')." AS g, ".$ecs->table('attribute') ." AS a WHERE a.attr_id = g.attr_id ".$in_attr.$in_goods; + $rs = $db->query($sql); + + while ($row = $db->fetchRow($rs)) + { + if (empty($condition[0]['cat'][$row['attr_id']]['cat_name'])) + { + $condition[0]['cat'][$row['attr_id']]['cat_name'] = $row['attr_name']; + } + $condition[0]['cat'][$row['attr_id']]['list'][] = array('name'=>$row['attr_value'], 'url'=>'pick_out.php?cat_id='.$cat_id.search_url($attr_picks).'&attr['.$row['attr_id'].']='.urlencode($row['attr_value'])); + } + + /* 生成更多商品的url */ + $url = "search.php?pickout=1&cat_id=".$cat_id.search_url($attr_picks); + +} + +/* 显示商品 */ +$goods = array(); +$sql = "SELECT g.goods_id, g.goods_name, g.market_price, g.shop_price AS org_price, ". + "IFNULL(mp.user_price, g.shop_price * '$_SESSION[discount]') AS shop_price, ". + "g.promote_price, promote_start_date, promote_end_date, g.goods_brief, g.goods_thumb ". + "FROM " .$ecs->table('goods'). " AS g ". + "LEFT JOIN " . $GLOBALS['ecs']->table('member_price') . " AS mp ". + "ON mp.goods_id = g.goods_id AND mp.user_rank = '$_SESSION[user_rank]' ". + "WHERE g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0 ".$in_goods. + "ORDER BY g.sort_order, g.last_update DESC"; +$res = $db->SelectLimit($sql, 4); + +/* 获取品牌 */ +$sql = "SELECT b.brand_id, b.brand_name, b.brand_logo, COUNT(g.goods_id) AS goods_num ". + " FROM " . $ecs->table('goods') . " AS g ". + " LEFT JOIN " . $ecs->table('brand') . " AS b ON g.brand_id=b.brand_id ". + " WHERE g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0 AND b.brand_id > 0 " . $in_goods . + " GROUP BY g.brand_id "; + +$brand_list = $db->getAll($sql); +foreach ($brand_list as $key=>$val) +{ + $brand_list[$key]['url'] = $url . '&brand=' . $val['brand_id']; +} + +/* 获取分类 */ +$sql = "SELECT c.cat_id, c.cat_name, COUNT(g.goods_id) AS goods_num ". + " FROM " . $ecs->table('goods') . " AS g ". + " LEFT JOIN " . $ecs->table('category') . " AS c ON c.cat_id = g.cat_id ". + " WHERE g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0 " . $in_goods . + " GROUP BY g.cat_id "; + +$cat_list = $db->getAll($sql); + +foreach ($cat_list as $key=>$val) +{ + $cat_list[$key]['url'] = $url . '&category=' . $val['cat_id']; +} + + +$idx = 0; +while ($row = $db->fetchRow($res)) +{ + if ($row['promote_price'] > 0) + { + $promote_price = bargain_price($row['promote_price'], $row['promote_start_date'], $row['promote_end_date']); + } + else + { + $promote_price = 0; + } + + $goods[$idx]['id'] = $row['goods_id']; + $goods[$idx]['name'] = $row['goods_name']; + $goods[$idx]['short_name'] = $_CFG['goods_name_length'] > 0 ? sub_str($row['goods_name'], $_CFG['goods_name_length']) : $row['goods_name']; + $goods[$idx]['market_price'] = $row['market_price']; + $goods[$idx]['shop_price'] = price_format($row['shop_price']); + $goods[$idx]['promote_price'] = $promote_price > 0 ? price_format($promote_price) : ''; + $goods[$idx]['brief'] = $row['goods_brief']; + $goods[$idx]['thumb'] = get_image_path($row['goods_id'], $row['goods_thumb'], true); + $goods[$idx]['url'] = build_uri('goods', array('gid'=>$row['goods_id']), $row['goods_name']); + + $idx++; +} + +$picks[] = array('name'=>$_LANG['remove_all'], 'url'=>'pick_out.php'); + +assign_template(); +$position = assign_ur_here(0, $_LANG['pick_out']); +$smarty->assign('page_title', $position['title']); // 页面标题 +$smarty->assign('ur_here', $position['ur_here']); // 当前位置 + +$smarty->assign('brand_list', $brand_list); //品牌 +$smarty->assign('cat_list', $cat_list); //分类列表 + +$smarty->assign('categories', get_categories_tree()); // 分类树 +$smarty->assign('helps', get_shop_help()); // 网店帮助 +$smarty->assign('top_goods', get_top10()); // 销售排行 +$smarty->assign('data_dir', DATA_DIR); // 数据目录 + +/* 调查 */ +$vote = get_vote(); +if (!empty($vote)) +{ + $smarty->assign('vote_id', $vote['id']); + $smarty->assign('vote', $vote['content']); +} + +assign_dynamic('pick_out'); + +$smarty->assign('url', $url); +$smarty->assign('pickout_goods', $goods); +$smarty->assign('count', $goods_count); +$smarty->assign('picks', $picks); +$smarty->assign('condition', $condition); +$smarty->display('pick_out.dwt'); + +/** + * 生成搜索的链接地址 + * + * @access public + * @param int attr_id 要排除的attr_id + * + * @return string + */ +function search_url(&$attr_picks, $attr_id = 0) +{ + $str = ''; + foreach ($attr_picks AS $pick_id) + { + if ($pick_id != $attr_id) + { + $str .= '&attr['.$pick_id.']='.urlencode($_GET['attr'][$pick_id]); + } + } + + return $str; +} + +?> \ No newline at end of file diff --git a/pm.php b/pm.php new file mode 100644 index 0000000..9046305 --- /dev/null +++ b/pm.php @@ -0,0 +1,28 @@ + \ No newline at end of file diff --git a/png.htc b/png.htc new file mode 100644 index 0000000..e69de29 diff --git a/quotation.php b/quotation.php new file mode 100644 index 0000000..b3f9991 --- /dev/null +++ b/quotation.php @@ -0,0 +1,156 @@ +template_dir = DATA_DIR; + $smarty->assign('shop_name', $_CFG['shop_title']); + $smarty->assign('cfg', $_CFG); + $where = get_quotation_where($_POST); + $sql = "SELECT g.goods_id, g.goods_name, g.shop_price, g.goods_number, c.cat_name AS goods_category,p.product_id,p.product_number,p.goods_attr". + " FROM " . $ecs->table('goods') . " AS g LEFT JOIN " . $ecs->table('category') . " AS c ON g.cat_id = c.cat_id LEFT JOIN ".$ecs->table('products')."as p On g.goods_id=p.goods_id" . $where . " AND is_on_sale = 1 AND is_alone_sale = 1 "; + $goods_list = $db->getAll($sql); + + foreach($goods_list as $key=>$val) + { + if(!empty($val['product_id'])) + { + $goods_list[$key]['goods_number']=$val['product_number']; + $product_info=product_info($val['goods_attr'],$val['goods_id']); + $goods_list[$key]['members_price'] = $val['shop_price']; + $goods_list[$key]['shop_price'] += $product_info['attr_price']; + $goods_list[$key]['product_name']=$product_info['attr_value']; + $goods_list[$key]['attr_price'] =$product_info['attr_price']; + } + else + { + $goods_list[$key]['members_price'] = $val['shop_price']; + $goods_list[$key]['product_name']=' '; + $goods_list[$key]['product_price']=0; + } + $goods_list[$key]['goods_key']=$key; + } + $user_rank = $db->getAll("SELECT * FROM " .$ecs->table('user_rank') . "WHERE show_price = 1 OR rank_id = '$_SESSION[user_rank]'"); + $rank_point = 0; + if (!empty($_SESSION['user_id'])) + { + $rank_point = $db->getOne("SELECT rank_points FROM " . $ecs->table('users') . " WHERE user_id = '$_SESSION[user_id]'"); + } + $user_rank = calc_user_rank($user_rank, $rank_point); + $user_men = serve_user($goods_list); + $smarty->assign('extend_price', $user_rank['ext_price']); + $smarty->assign('extend_rank', $user_men); + $smarty->assign('goods_list', $goods_list); + + $html = $smarty->fetch('quotation_print.html'); + exit($html); +} + +assign_template(); + +$position = assign_ur_here(0, $_LANG['quotation']); +$smarty->assign('page_title', $position['title']); // 页面标题 +$smarty->assign('ur_here', $position['ur_here']); // 当前位置 + +$smarty->assign('cat_list', cat_list()); +$smarty->assign('brand_list', get_brand_list()); + +if (is_null($smarty->get_template_vars('helps'))) +{ + $smarty->assign('helps', get_shop_help()); // 网店帮助 +} + +$smarty->display('quotation.dwt'); + +function get_quotation_where($filter) +{ + include_once(ROOT_PATH . ADMIN_PATH . '/includes/lib_main.php'); + $_filter = new StdClass(); + $_filter->cat_id = $filter['cat_id']; + $_filter->brand_id = $filter['brand_id']; + $where = get_where_sql($_filter); + $_filter->keyword = $filter['keyword']; + $where .= isset($_filter->keyword) && trim($_filter->keyword) != '' ? " AND (g.goods_name LIKE '%" . mysql_like_quote($_filter->keyword) . "%' OR g.goods_sn LIKE '%" . mysql_like_quote($_filter->keyword) . "%' OR g.goods_id LIKE '%" . mysql_like_quote($_filter->keyword) . "%') " : ''; + return $where; +} + +function calc_user_rank($rank, $rank_point) +{ + $_tmprank = array(); + foreach($rank as $_rank) + { + if ($_rank['show_price']) + { + $_tmprank['ext_price'][] = $_rank['rank_name']; + $_tmprank['ext_rank'][] = $_rank['discount']; + } + else + { + if (!empty($_SESSION['user_id']) && ($rank_point >= $_rank['min_points'])) + { + $_tmprank['ext_price'][] = $_rank['rank_name']; + $_tmprank['ext_rank'][] = $_rank['discount']; + } + } + } + return $_tmprank; +} + +function serve_user($goods_list) +{ + foreach ( $goods_list as $key=> $all_list ) + { + $goods_id = $all_list['goods_id']; + $goods_key =$all_list['goods_key']; + $price = $all_list['members_price']; + $sql = "SELECT rank_id, IFNULL(mp.user_price, r.discount * $price / 100) AS price, r.rank_name, r.discount " . + 'FROM ' . $GLOBALS['ecs']->table('user_rank') . ' AS r ' . + 'LEFT JOIN ' . $GLOBALS['ecs']->table('member_price') . " AS mp ". + "ON mp.goods_id = '$goods_id' AND mp.user_rank = r.rank_id " . + "WHERE r.show_price = 1 OR r.rank_id = '$_SESSION[user_rank]'"; + $res = $GLOBALS['db']->getAll($sql); + + foreach ( $res as $row ) + { + $arr[$row['rank_id']] = array( + 'rank_name' => htmlspecialchars($row['rank_name']), + 'price' => price_format($row['price']+$all_list['attr_price'])); + + } + $arr_list[$goods_key] = $arr; + } + return $arr_list; +} +function product_info($goods_attr,$goods_id) +{ + $goods_attr=str_replace('|',' OR goods_attr_id=',$goods_attr); + $sql="SELECT attr_value,attr_price FROM ". $GLOBALS['ecs']->table('goods_attr') ." WHERE goods_id='$goods_id' AND (goods_attr_id = $goods_attr)"; + $result =$GLOBALS['db']->getAll($sql); + $i=1; + $count=count($result); + foreach ($result as $val) + { + $i==$count?$f='':$f='
    '; + $product_info['attr_value'].=$val['attr_value'].$f; + $product_info['attr_price']+=$val['attr_price']; + $i++; + } + return($product_info); +} +?> \ No newline at end of file diff --git a/receive.php b/receive.php new file mode 100644 index 0000000..1e30807 --- /dev/null +++ b/receive.php @@ -0,0 +1,71 @@ +table('order_info') . " WHERE order_id = '$order_id'"; +$order = $db->getRow($sql); + +if (empty($order)) +{ + $msg = $_LANG['order_not_exists']; +} +/* 检查订单 */ +elseif ($order['shipping_status'] == SS_RECEIVED) +{ + $msg = $_LANG['order_already_received']; +} +elseif ($order['shipping_status'] != SS_SHIPPED) +{ + $msg = $_LANG['order_invalid']; +} +elseif ($order['consignee'] != $consignee) +{ + $msg = $_LANG['order_invalid']; +} +else +{ + /* 修改订单发货状态为“确认收货” */ + $sql = "UPDATE " . $ecs->table('order_info') . " SET shipping_status = '" . SS_RECEIVED . "' WHERE order_id = '$order_id'"; + $db->query($sql); + + /* 记录日志 */ + order_action($order['order_sn'], $order['order_status'], SS_RECEIVED, $order['pay_status'], '', $_LANG['buyer']); + + $msg = $_LANG['act_ok']; +} + +/* 显示模板 */ +assign_template(); +$position = assign_ur_here(); +$smarty->assign('page_title', $position['title']); // 页面标题 +$smarty->assign('ur_here', $position['ur_here']); // 当前位置 + +$smarty->assign('categories', get_categories_tree()); // 分类树 +$smarty->assign('helps', get_shop_help()); // 网店帮助 + +assign_dynamic('receive'); + +$smarty->assign('msg', $msg); +$smarty->display('receive.dwt'); + +?> \ No newline at end of file diff --git a/region.php b/region.php new file mode 100644 index 0000000..73b46b2 --- /dev/null +++ b/region.php @@ -0,0 +1,36 @@ +encode($arr); + +?> \ No newline at end of file diff --git a/respond.php b/respond.php new file mode 100644 index 0000000..9bab1b6 --- /dev/null +++ b/respond.php @@ -0,0 +1,95 @@ +table('payment') . " WHERE pay_code = '$pay_code' AND enabled = 1"; + if ($db->getOne($sql) == 0) + { + $msg = $_LANG['pay_disabled']; + } + else + { + $plugin_file = 'includes/modules/payment/' . $pay_code . '.php'; + + /* 检查插件文件是否存在,如果存在则验证支付是否成功,否则则返回失败信息 */ + if (file_exists($plugin_file)) + { + /* 根据支付方式代码创建支付类的对象并调用其响应操作方法 */ + include_once($plugin_file); + + $payment = new $pay_code(); + $msg = ($payment->respond()) ? $_LANG['pay_success'] : $_LANG['pay_fail']; + } + else + { + $msg = $_LANG['pay_not_exist']; + } + } +} + +assign_template(); +$position = assign_ur_here(); +$smarty->assign('page_title', $position['title']); // 页面标题 +$smarty->assign('ur_here', $position['ur_here']); // 当前位置 +$smarty->assign('page_title', $position['title']); // 页面标题 +$smarty->assign('ur_here', $position['ur_here']); // 当前位置 +$smarty->assign('helps', get_shop_help()); // 网店帮助 + +$smarty->assign('message', $msg); +$smarty->assign('shop_url', $ecs->url()); + +$smarty->display('respond.dwt'); + +?> \ No newline at end of file diff --git a/robots.txt b/robots.txt new file mode 100644 index 0000000..d1c14ca --- /dev/null +++ b/robots.txt @@ -0,0 +1,23 @@ +User-agent: * +Disallow: /admin/ +Disallow: /cert/ +Disallow: /data/ +Disallow: /includes/ +Disallow: /install/ +Disallow: /languages/ +Disallow: /plugins/ +Disallow: /templates/ +Disallow: /themes/ +Disallow: /upgrade/ +Disallow: /api/ +Disallow: /js/ +Disallow: /affiche.php +Disallow: /captcha.php +Disallow: /comment.php +Disallow: /cycle_image.php +Disallow: /goods_script.php +Disallow: /receive.php +Disallow: /region.php +Disallow: /respond.php +Disallow: /feed.php +Disallow: /gallery.php \ No newline at end of file diff --git a/search.php b/search.php new file mode 100644 index 0000000..dc23ef9 --- /dev/null +++ b/search.php @@ -0,0 +1,600 @@ + $string['search_encode_time'] + 2) + { + define('INGORE_VISIT_STATS', true); + } + } + else + { + define('INGORE_VISIT_STATS', true); + } + } + else + { + $string = array(); + } + } + else + { + $string = array(); + } +} + +require(dirname(__FILE__) . '/includes/init.php'); + +$_REQUEST = array_merge($_REQUEST, addslashes_deep($string)); + +$_REQUEST['act'] = !empty($_REQUEST['act']) ? trim($_REQUEST['act']) : ''; + +/*------------------------------------------------------ */ +//-- 高级搜索 +/*------------------------------------------------------ */ +if ($_REQUEST['act'] == 'advanced_search') +{ + $goods_type = !empty($_REQUEST['goods_type']) ? intval($_REQUEST['goods_type']) : 0; + $attributes = get_seachable_attributes($goods_type); + $smarty->assign('goods_type_selected', $goods_type); + $smarty->assign('goods_type_list', $attributes['cate']); + $smarty->assign('goods_attributes', $attributes['attr']); + + assign_template(); + assign_dynamic('search'); + $position = assign_ur_here(0, $_LANG['advanced_search']); + $smarty->assign('page_title', $position['title']); // 页面标题 + $smarty->assign('ur_here', $position['ur_here']); // 当前位置 + + $smarty->assign('categories', get_categories_tree()); // 分类树 + $smarty->assign('helps', get_shop_help()); // 网店帮助 + $smarty->assign('top_goods', get_top10()); // 销售排行 + $smarty->assign('promotion_info', get_promotion_info()); + $smarty->assign('cat_list', cat_list(0, 0, true, 2, false)); + $smarty->assign('brand_list', get_brand_list()); + $smarty->assign('action', 'form'); + $smarty->assign('use_storage', $_CFG['use_storage']); + + $smarty->display('search.dwt'); + + exit; +} +/*------------------------------------------------------ */ +//-- 搜索结果 +/*------------------------------------------------------ */ +else +{ + $_REQUEST['keywords'] = !empty($_REQUEST['keywords']) ? trim($_REQUEST['keywords']) : ''; + $_REQUEST['brand'] = !empty($_REQUEST['brand']) ? intval($_REQUEST['brand']) : 0; + $_REQUEST['category'] = !empty($_REQUEST['category']) ? intval($_REQUEST['category']) : 0; + $_REQUEST['min_price'] = !empty($_REQUEST['min_price']) ? intval($_REQUEST['min_price']) : 0; + $_REQUEST['max_price'] = !empty($_REQUEST['max_price']) ? intval($_REQUEST['max_price']) : 0; + $_REQUEST['goods_type'] = !empty($_REQUEST['goods_type']) ? intval($_REQUEST['goods_type']) : 0; + $_REQUEST['sc_ds'] = !empty($_REQUEST['sc_ds']) ? intval($_REQUEST['sc_ds']) : 0; + $_REQUEST['outstock'] = !empty($_REQUEST['outstock']) ? 1 : 0; + + $action = ''; + if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'form') + { + /* 要显示高级搜索栏 */ + $adv_value['keywords'] = htmlspecialchars(stripcslashes($_REQUEST['keywords'])); + $adv_value['brand'] = $_REQUEST['brand']; + $adv_value['min_price'] = $_REQUEST['min_price']; + $adv_value['max_price'] = $_REQUEST['max_price']; + $adv_value['category'] = $_REQUEST['category']; + + $attributes = get_seachable_attributes($_REQUEST['goods_type']); + + /* 将提交数据重新赋值 */ + foreach ($attributes['attr'] AS $key => $val) + { + if (!empty($_REQUEST['attr'][$val['id']])) + { + if ($val['type'] == 2) + { + $attributes['attr'][$key]['value']['from'] = !empty($_REQUEST['attr'][$val['id']]['from']) ? trim($_REQUEST['attr'][$val['id']]['from']) : ''; + $attributes['attr'][$key]['value']['to'] = !empty($_REQUEST['attr'][$val['id']]['to']) ? trim($_REQUEST['attr'][$val['id']]['to']) : ''; + } + else + { + $attributes['attr'][$key]['value'] = !empty($_REQUEST['attr'][$val['id']]) ? trim($_REQUEST['attr'][$val['id']]) : ''; + } + } + } + if ($_REQUEST['sc_ds']) + { + $smarty->assign('scck', 'checked'); + } + $smarty->assign('adv_val', $adv_value); + $smarty->assign('goods_type_list', $attributes['cate']); + $smarty->assign('goods_attributes', $attributes['attr']); + $smarty->assign('goods_type_selected', $_REQUEST['goods_type']); + $smarty->assign('cat_list', cat_list(0, $adv_value['category'], true, 2, false)); + $smarty->assign('brand_list', get_brand_list()); + $smarty->assign('action', 'form'); + $smarty->assign('use_storage', $_CFG['use_storage']); + + $action = 'form'; + } + + /* 初始化搜索条件 */ + $keywords = ''; + $tag_where = ''; + if (!empty($_REQUEST['keywords'])) + { + $arr = array(); + if (stristr($_REQUEST['keywords'], ' AND ') !== false) + { + /* 检查关键字中是否有AND,如果存在就是并 */ + $arr = explode('AND', $_REQUEST['keywords']); + $operator = " AND "; + } + elseif (stristr($_REQUEST['keywords'], ' OR ') !== false) + { + /* 检查关键字中是否有OR,如果存在就是或 */ + $arr = explode('OR', $_REQUEST['keywords']); + $operator = " OR "; + } + elseif (stristr($_REQUEST['keywords'], ' + ') !== false) + { + /* 检查关键字中是否有加号,如果存在就是或 */ + $arr = explode('+', $_REQUEST['keywords']); + $operator = " OR "; + } + else + { + /* 检查关键字中是否有空格,如果存在就是并 */ + $arr = explode(' ', $_REQUEST['keywords']); + $operator = " AND "; + } + + $keywords = 'AND ('; + $goods_ids = array(); + foreach ($arr AS $key => $val) + { + if ($key > 0 && $key < count($arr) && count($arr) > 1) + { + $keywords .= $operator; + } + $val = mysql_like_quote(trim($val)); + $sc_dsad = $_REQUEST['sc_ds'] ? " OR goods_desc LIKE '%$val%'" : ''; + $keywords .= "(goods_name LIKE '%$val%' OR goods_sn LIKE '%$val%' OR keywords LIKE '%$val%' $sc_dsad)"; + + $sql = 'SELECT DISTINCT goods_id FROM ' . $ecs->table('tag') . " WHERE tag_words LIKE '%$val%' "; + $res = $db->query($sql); + while ($row = $db->FetchRow($res)) + { + $goods_ids[] = $row['goods_id']; + } + + $db->autoReplace($ecs->table('keywords'), array('date' => local_date('Y-m-d'), + 'searchengine' => 'ecshop', 'keyword' => $val, 'count' => 1), array('count' => 1)); + } + $keywords .= ')'; + + $goods_ids = array_unique($goods_ids); + $tag_where = implode(',', $goods_ids); + if (!empty($tag_where)) + { + $tag_where = 'OR g.goods_id ' . db_create_in($tag_where); + } + } + + $category = !empty($_REQUEST['category']) ? intval($_REQUEST['category']) : 0; + $categories = ($category > 0) ? ' AND ' . get_children($category) : ''; + $brand = $_REQUEST['brand'] ? " AND brand_id = '$_REQUEST[brand]'" : ''; + $outstock = !empty($_REQUEST['outstock']) ? " AND g.goods_number > 0 " : ''; + + $min_price = $_REQUEST['min_price'] != 0 ? " AND g.shop_price >= '$_REQUEST[min_price]'" : ''; + $max_price = $_REQUEST['max_price'] != 0 || $_REQUEST['min_price'] < 0 ? " AND g.shop_price <= '$_REQUEST[max_price]'" : ''; + + /* 排序、显示方式以及类型 */ + $default_display_type = $_CFG['show_order_type'] == '0' ? 'list' : ($_CFG['show_order_type'] == '1' ? 'grid' : 'text'); + $default_sort_order_method = $_CFG['sort_order_method'] == '0' ? 'DESC' : 'ASC'; + $default_sort_order_type = $_CFG['sort_order_type'] == '0' ? 'goods_id' : ($_CFG['sort_order_type'] == '1' ? 'shop_price' : 'last_update'); + + $sort = (isset($_REQUEST['sort']) && in_array(trim(strtolower($_REQUEST['sort'])), array('goods_id', 'shop_price', 'last_update'))) ? trim($_REQUEST['sort']) : $default_sort_order_type; + $order = (isset($_REQUEST['order']) && in_array(trim(strtoupper($_REQUEST['order'])), array('ASC', 'DESC'))) ? trim($_REQUEST['order']) : $default_sort_order_method; + $display = (isset($_REQUEST['display']) && in_array(trim(strtolower($_REQUEST['display'])), array('list', 'grid', 'text'))) ? trim($_REQUEST['display']) : (isset($_SESSION['display_search']) ? $_SESSION['display_search'] : $default_display_type); + + $_SESSION['display_search'] = $display; + + $page = !empty($_REQUEST['page']) && intval($_REQUEST['page']) > 0 ? intval($_REQUEST['page']) : 1; + $size = !empty($_CFG['page_size']) && intval($_CFG['page_size']) > 0 ? intval($_CFG['page_size']) : 10; + + $intromode = ''; //方式,用于决定搜索结果页标题图片 + + if (!empty($_REQUEST['intro'])) + { + switch ($_REQUEST['intro']) + { + case 'best': + $intro = ' AND g.is_best = 1'; + $intromode = 'best'; + $ur_here = $_LANG['best_goods']; + break; + case 'new': + $intro = ' AND g.is_new = 1'; + $intromode ='new'; + $ur_here = $_LANG['new_goods']; + break; + case 'hot': + $intro = ' AND g.is_hot = 1'; + $intromode = 'hot'; + $ur_here = $_LANG['hot_goods']; + break; + case 'promotion': + $time = gmtime(); + $intro = " AND g.promote_price > 0 AND g.promote_start_date <= '$time' AND g.promote_end_date >= '$time'"; + $intromode = 'promotion'; + $ur_here = $_LANG['promotion_goods']; + break; + default: + $intro = ''; + } + } + else + { + $intro = ''; + } + + if (empty($ur_here)) + { + $ur_here = $_LANG['search_goods']; + } + + /*------------------------------------------------------ */ + //-- 属性检索 + /*------------------------------------------------------ */ + $attr_in = ''; + $attr_num = 0; + $attr_url = ''; + $attr_arg = array(); + + if (!empty($_REQUEST['attr'])) + { + $sql = "SELECT goods_id, COUNT(*) AS num FROM " . $ecs->table("goods_attr") . " WHERE 0 "; + foreach ($_REQUEST['attr'] AS $key => $val) + { + if (is_not_null($val) && is_numeric($key)) + { + $attr_num++; + $sql .= " OR (1 "; + + if (is_array($val)) + { + $sql .= " AND attr_id = '$key'"; + + if (!empty($val['from'])) + { + $sql .= is_numeric($val['from']) ? " AND attr_value >= " . floatval($val['from']) : " AND attr_value >= '$val[from]'"; + $attr_arg["attr[$key][from]"] = $val['from']; + $attr_url .= "&attr[$key][from]=$val[from]"; + } + + if (!empty($val['to'])) + { + $sql .= is_numeric($val['to']) ? " AND attr_value <= " . floatval($val['to']) : " AND attr_value <= '$val[to]'"; + $attr_arg["attr[$key][to]"] = $val['to']; + $attr_url .= "&attr[$key][to]=$val[to]"; + } + } + else + { + /* 处理选购中心过来的链接 */ + $sql .= isset($_REQUEST['pickout']) ? " AND attr_id = '$key' AND attr_value = '" . $val . "' " : " AND attr_id = '$key' AND attr_value LIKE '%" . mysql_like_quote($val) . "%' "; + $attr_url .= "&attr[$key]=$val"; + $attr_arg["attr[$key]"] = $val; + } + + $sql .= ')'; + } + } + + /* 如果检索条件都是无效的,就不用检索 */ + if ($attr_num > 0) + { + $sql .= " GROUP BY goods_id HAVING num = '$attr_num'"; + + $row = $db->getCol($sql); + if (count($row)) + { + $attr_in = " AND " . db_create_in($row, 'g.goods_id'); + } + else + { + $attr_in = " AND 0 "; + } + } + } + elseif (isset($_REQUEST['pickout'])) + { + /* 从选购中心进入的链接 */ + $sql = "SELECT DISTINCT(goods_id) FROM " . $ecs->table('goods_attr'); + $col = $db->getCol($sql); + //如果商店没有设置商品属性,那么此检索条件是无效的 + if (!empty($col)) + { + $attr_in = " AND " . db_create_in($col, 'g.goods_id'); + } + } + + /* 获得符合条件的商品总数 */ + $sql = "SELECT COUNT(*) FROM " .$ecs->table('goods'). " AS g ". + "WHERE g.is_delete = 0 AND g.is_on_sale = 1 AND g.is_alone_sale = 1 $attr_in ". + "AND (( 1 " . $categories . $keywords . $brand . $min_price . $max_price . $intro . $outstock ." ) ".$tag_where." )"; + $count = $db->getOne($sql); + + $max_page = ($count> 0) ? ceil($count / $size) : 1; + if ($page > $max_page) + { + $page = $max_page; + } + + /* 查询商品 */ + $sql = "SELECT g.goods_id, g.goods_name, g.market_price, g.is_new, g.is_best, g.is_hot, g.shop_price AS org_price, ". + "IFNULL(mp.user_price, g.shop_price * '$_SESSION[discount]') AS shop_price, ". + "g.promote_price, g.promote_start_date, g.promote_end_date, g.goods_thumb, g.goods_img, g.goods_brief, g.goods_type ". + "FROM " .$ecs->table('goods'). " AS g ". + "LEFT JOIN " . $GLOBALS['ecs']->table('member_price') . " AS mp ". + "ON mp.goods_id = g.goods_id AND mp.user_rank = '$_SESSION[user_rank]' ". + "WHERE g.is_delete = 0 AND g.is_on_sale = 1 AND g.is_alone_sale = 1 $attr_in ". + "AND (( 1 " . $categories . $keywords . $brand . $min_price . $max_price . $intro . $outstock . " ) ".$tag_where." ) " . + "ORDER BY $sort $order"; + $res = $db->SelectLimit($sql, $size, ($page - 1) * $size); + + $arr = array(); + while ($row = $db->FetchRow($res)) + { + if ($row['promote_price'] > 0) + { + $promote_price = bargain_price($row['promote_price'], $row['promote_start_date'], $row['promote_end_date']); + } + else + { + $promote_price = 0; + } + + /* 处理商品水印图片 */ + /* 处理商品水印图片 */ + $watermark_img = ''; + + if ($promote_price != 0) + { + $watermark_img = "watermark_promote_small"; + } + elseif ($row['is_new'] != 0) + { + $watermark_img = "watermark_new_small"; + } + elseif ($row['is_best'] != 0) + { + $watermark_img = "watermark_best_small"; + } + elseif ($row['is_hot'] != 0) + { + $watermark_img = 'watermark_hot_small'; + } + + if ($watermark_img != '') + { + $arr[$row['goods_id']]['watermark_img'] = $watermark_img; + } + + $arr[$row['goods_id']]['goods_id'] = $row['goods_id']; + if($display == 'grid') + { + $arr[$row['goods_id']]['goods_name'] = $GLOBALS['_CFG']['goods_name_length'] > 0 ? sub_str($row['goods_name'], $GLOBALS['_CFG']['goods_name_length']) : $row['goods_name']; + } + else + { + $arr[$row['goods_id']]['goods_name'] = $row['goods_name']; + } + $arr[$row['goods_id']]['type'] = $row['goods_type']; + $arr[$row['goods_id']]['market_price'] = price_format($row['market_price']); + $arr[$row['goods_id']]['shop_price'] = price_format($row['shop_price']); + $arr[$row['goods_id']]['promote_price'] = ($promote_price > 0) ? price_format($promote_price) : ''; + $arr[$row['goods_id']]['goods_brief'] = $row['goods_brief']; + $arr[$row['goods_id']]['goods_thumb'] = get_image_path($row['goods_id'], $row['goods_thumb'], true); + $arr[$row['goods_id']]['goods_img'] = get_image_path($row['goods_id'], $row['goods_img']); + $arr[$row['goods_id']]['url'] = build_uri('goods', array('gid' => $row['goods_id']), $row['goods_name']); + } + + if($display == 'grid') + { + if(count($arr) % 2 != 0) + { + $arr[] = array(); + } + } + $smarty->assign('goods_list', $arr); + $smarty->assign('category', $category); + $smarty->assign('keywords', htmlspecialchars(stripslashes($_REQUEST['keywords']))); + $smarty->assign('search_keywords', stripslashes($_REQUEST['keywords'])); + $smarty->assign('brand', $_REQUEST['brand']); + $smarty->assign('min_price', $min_price); + $smarty->assign('max_price', $max_price); + $smarty->assign('outstock', $_REQUEST['outstock']); + + /* 分页 */ + $url_format = "search.php?category=$category&keywords=" . urlencode(stripslashes($_REQUEST['keywords'])) . "&brand=" . $_REQUEST['brand']."&action=".$action."&goods_type=" . $_REQUEST['goods_type'] . "&sc_ds=" . $_REQUEST['sc_ds']; + if (!empty($intromode)) + { + $url_format .= "&intro=" . $intromode; + } + if (isset($_REQUEST['pickout'])) + { + $url_format .= '&pickout=1'; + } + $url_format .= "&min_price=" . $_REQUEST['min_price'] ."&max_price=" . $_REQUEST['max_price'] . "&sort=$sort"; + + $url_format .= "$attr_url&order=$order&page="; + + $pager['search'] = array( + 'keywords' => stripslashes(urlencode($_REQUEST['keywords'])), + 'category' => $category, + 'brand' => $_REQUEST['brand'], + 'sort' => $sort, + 'order' => $order, + 'min_price' => $_REQUEST['min_price'], + 'max_price' => $_REQUEST['max_price'], + 'action' => $action, + 'intro' => empty($intromode) ? '' : trim($intromode), + 'goods_type' => $_REQUEST['goods_type'], + 'sc_ds' => $_REQUEST['sc_ds'], + 'outstock' => $_REQUEST['outstock'] + ); + $pager['search'] = array_merge($pager['search'], $attr_arg); + + $pager = get_pager('search.php', $pager['search'], $count, $page, $size); + $pager['display'] = $display; + + $smarty->assign('url_format', $url_format); + $smarty->assign('pager', $pager); + + assign_template(); + assign_dynamic('search'); + $position = assign_ur_here(0, $ur_here . ($_REQUEST['keywords'] ? '_' . $_REQUEST['keywords'] : '')); + $smarty->assign('page_title', $position['title']); // 页面标题 + $smarty->assign('ur_here', $position['ur_here']); // 当前位置 + $smarty->assign('intromode', $intromode); + $smarty->assign('categories', get_categories_tree()); // 分类树 + $smarty->assign('helps', get_shop_help()); // 网店帮助 + $smarty->assign('top_goods', get_top10()); // 销售排行 + $smarty->assign('promotion_info', get_promotion_info()); + + $smarty->display('search.dwt'); +} + +/*------------------------------------------------------ */ +//-- PRIVATE FUNCTION +/*------------------------------------------------------ */ +/** + * + * + * @access public + * @param + * + * @return void + */ +function is_not_null($value) +{ + if (is_array($value)) + { + return (!empty($value['from'])) || (!empty($value['to'])); + } + else + { + return !empty($value); + } +} + +/** + * 获得可以检索的属性 + * + * @access public + * @params integer $cat_id + * @return void + */ +function get_seachable_attributes($cat_id = 0) +{ + $attributes = array( + 'cate' => array(), + 'attr' => array() + ); + + /* 获得可用的商品类型 */ + $sql = "SELECT t.cat_id, cat_name FROM " .$GLOBALS['ecs']->table('goods_type'). " AS t, ". + $GLOBALS['ecs']->table('attribute') ." AS a". + " WHERE t.cat_id = a.cat_id AND t.enabled = 1 AND a.attr_index > 0 "; + $cat = $GLOBALS['db']->getAll($sql); + + /* 获取可以检索的属性 */ + if (!empty($cat)) + { + foreach ($cat AS $val) + { + $attributes['cate'][$val['cat_id']] = $val['cat_name']; + } + $where = $cat_id > 0 ? ' AND a.cat_id = ' . $cat_id : " AND a.cat_id = " . $cat[0]['cat_id']; + + $sql = 'SELECT attr_id, attr_name, attr_input_type, attr_type, attr_values, attr_index, sort_order ' . + ' FROM ' . $GLOBALS['ecs']->table('attribute') . ' AS a ' . + ' WHERE a.attr_index > 0 ' .$where. + ' ORDER BY cat_id, sort_order ASC'; + $res = $GLOBALS['db']->query($sql); + + while ($row = $GLOBALS['db']->FetchRow($res)) + { + if ($row['attr_index'] == 1 && $row['attr_input_type'] == 1) + { + $row['attr_values'] = str_replace("\r", '', $row['attr_values']); + $options = explode("\n", $row['attr_values']); + + $attr_value = array(); + foreach ($options AS $opt) + { + $attr_value[$opt] = $opt; + } + $attributes['attr'][] = array( + 'id' => $row['attr_id'], + 'attr' => $row['attr_name'], + 'options' => $attr_value, + 'type' => 3 + ); + } + else + { + $attributes['attr'][] = array( + 'id' => $row['attr_id'], + 'attr' => $row['attr_name'], + 'type' => $row['attr_index'] + ); + } + } + } + + return $attributes; +} +?> \ No newline at end of file diff --git a/sitemaps.php b/sitemaps.php new file mode 100644 index 0000000..dd9c188 --- /dev/null +++ b/sitemaps.php @@ -0,0 +1,129 @@ +\n\n"; + var $footer = "\n"; + var $item; + function item($item) + { + $this->item .= "\n"; + foreach($item as $key => $val){ + $this->item .=" <$key>".htmlentities($val, ENT_QUOTES)."\n"; + } + $this->item .= "\n"; + } + function generate() + { + $all = $this->head; + $all .= $this->item; + $all .= $this->footer; + + return $all; + } +} + +define('IN_ECS', true); +define('INIT_NO_USERS', true); +define('INIT_NO_SMARTY', true); +require(dirname(__FILE__) . '/includes/init.php'); +if (file_exists(ROOT_PATH . DATA_DIR . '/sitemap.dat') && time() - filemtime(ROOT_PATH . DATA_DIR . '/sitemap.dat') < 86400) +{ + $out = file_get_contents(ROOT_PATH . DATA_DIR . '/sitemap.dat'); +} +else +{ + $site_url = rtrim($ecs->url(),'/'); + $sitemap = new sitemap; + $config = unserialize($_CFG['sitemap']); + $item = array( + 'loc' => "$site_url/", + 'lastmod' => local_date('Y-m-d'), + 'changefreq' => $config['homepage_changefreq'], + 'priority' => $config['homepage_priority'], + ); + $sitemap->item($item); + /* 商品分类 */ + $sql = "SELECT cat_id,cat_name FROM " .$ecs->table('category'). " ORDER BY parent_id"; + $res = $db->query($sql); + + while ($row = $db->fetchRow($res)) + { + $item = array( + 'loc' => "$site_url/" . build_uri('category', array('cid' => $row['cat_id']), $row['cat_name']), + 'lastmod' => local_date('Y-m-d'), + 'changefreq' => $config['category_changefreq'], + 'priority' => $config['category_priority'], + ); + $sitemap->item($item); + } + /* 文章分类 */ + $sql = "SELECT cat_id,cat_name FROM " .$ecs->table('article_cat'). " WHERE cat_type=1"; + $res = $db->query($sql); + + while ($row = $db->fetchRow($res)) + { + $item = array( + 'loc' => "$site_url/" . build_uri('article_cat', array('acid' => $row['cat_id']), $row['cat_name']), + 'lastmod' => local_date('Y-m-d'), + 'changefreq' => $config['category_changefreq'], + 'priority' => $config['category_priority'], + ); + $sitemap->item($item); + } + /* 商品 */ + $sql = "SELECT goods_id, goods_name, last_update FROM " .$ecs->table('goods'). " WHERE is_delete = 0 LIMIT 300"; + $res = $db->query($sql); + + while ($row = $db->fetchRow($res)) + { + $item = array( + 'loc' => "$site_url/" . build_uri('goods', array('gid' => $row['goods_id']), $row['goods_name']), + 'lastmod' => local_date('Y-m-d', $row['last_update']), + 'changefreq' => $config['content_changefreq'], + 'priority' => $config['content_priority'], + ); + $sitemap->item($item); + } + /* 文章 */ + $sql = "SELECT article_id,title,file_url,open_type, add_time FROM " .$ecs->table('article'). " WHERE is_open=1"; + $res = $db->query($sql); + + while ($row = $db->fetchRow($res)) + { + $article_url=$row['open_type'] != 1 ? build_uri('article', array('aid'=>$row['article_id']), $row['title']) : trim($row['file_url']); + $item = array( + 'loc' => "$site_url/" . $article_url, + 'lastmod' => local_date('Y-m-d', $row['add_time']), + 'changefreq' => $config['content_changefreq'], + 'priority' => $config['content_priority'], + ); + $sitemap->item($item); + } + $out = $sitemap->generate(); + file_put_contents(ROOT_PATH . DATA_DIR . '/sitemap.dat', $out); +} +if (function_exists('gzencode')) +{ + header('Content-type: application/x-gzip'); + $out = gzencode($out, 9); +} +else +{ + header('Content-type: application/xml; charset=utf-8'); +} +die($out); +?> \ No newline at end of file diff --git a/snatch.php b/snatch.php new file mode 100644 index 0000000..512e15b --- /dev/null +++ b/snatch.php @@ -0,0 +1,493 @@ +$id)); + ecs_header("Location: $page\n"); + exit; + } + else + { + /* 当前没有任何可默认的活动 */ + $id = 0; + } +} +else +{ + $id = intval($_REQUEST['id']); +} + +/* 显示页面部分 */ +if ($_REQUEST['act'] == 'main') +{ + $goods = get_snatch($id); + if ($goods) + { + $position = assign_ur_here(0,$goods['snatch_name']); + $myprice = get_myprice($id); + if ($goods['is_end']) + { + //如果活动已经结束,获取活动结果 + $smarty->assign('result', get_snatch_result($id)); + } + $smarty->assign('id', $id); + $smarty->assign('snatch_goods', $goods); // 竞价商品 + $smarty->assign('myprice', get_myprice($id)); + if ($goods['product_id'] > 0) + { + $goods_specifications = get_specifications_list($goods['goods_id']); + + $good_products = get_good_products($goods['goods_id'], 'AND product_id = ' . $goods['product_id']); + + $_good_products = explode('|', $good_products[0]['goods_attr']); + $products_info = ''; + foreach ($_good_products as $value) + { + $products_info .= ' ' . $goods_specifications[$value]['attr_name'] . ':' . $goods_specifications[$value]['attr_value']; + } + $smarty->assign('products_info', $products_info); + unset($goods_specifications, $good_products, $_good_products, $products_info); + } + } + else + { + show_message($_LANG['now_not_snatch']); + } + + /* 调查 */ + $vote = get_vote(); + if (!empty($vote)) + { + $smarty->assign('vote_id', $vote['id']); + $smarty->assign('vote', $vote['content']); + } + + assign_template(); + assign_dynamic('snatch'); + $smarty->assign('page_title', $position['title']); + $smarty->assign('ur_here', $position['ur_here']); + $smarty->assign('categories', get_categories_tree()); // 分类树 + $smarty->assign('helps', get_shop_help()); // 网店帮助 + $smarty->assign('snatch_list', get_snatch_list()); //所有有效的夺宝奇兵列表 + $smarty->assign('price_list', get_price_list($id)); + $smarty->assign('promotion_info', get_promotion_info()); + $smarty->assign('feed_url', ($_CFG['rewrite'] == 1) ? "feed-typesnatch.xml" : 'feed.php?type=snatch'); // RSS URL + $smarty->display('snatch.dwt'); + + exit; +} + +/* 最新出价列表 */ +if ($_REQUEST['act'] == 'new_price_list') +{ + $smarty->assign('price_list', get_price_list($id)); + $smarty->display('library/snatch_price.lbi'); + + exit; +} + +/* 用户出价处理 */ +if ($_REQUEST['act'] == 'bid') +{ + include_once(ROOT_PATH .'includes/cls_json.php'); + $json = new JSON(); + $result = array('error'=>0, 'content'=>''); + + $price = isset($_POST['price']) ? floatval($_POST['price']) : 0; + $price = round($price, 2); + + /* 测试是否登陆 */ + if (empty($_SESSION['user_id'])) + { + $result['error'] = 1; + $result['content'] = $_LANG['not_login']; + die($json->encode($result)); + } + + /* 获取活动基本信息用于校验 */ + $sql = 'SELECT act_name AS snatch_name, end_time, ext_info FROM ' . $GLOBALS['ecs']->table('goods_activity') . " WHERE act_id ='$id'"; + $row = $db->getRow($sql, 'SILENT'); + + if ($row) + { + $info = unserialize($row['ext_info']); + if ($info) + { + foreach ($info as $key => $val) + { + $row[$key] = $val; + } + } + } + + if (empty($row)) + { + $result['error'] = 1; + $result['content'] = $db->error(); + die($json->encode($result)); + } + + if ($row['end_time']< gmtime() ) + { + $result['error'] = 1; + $result['content'] = $_LANG['snatch_is_end']; + die($json->encode($result)); + } + + /* 检查出价是否合理 */ + if ($price < $row['start_price'] || $price > $row['end_price']) + { + $result['error'] = 1; + $result['content'] = sprintf($GLOBALS['_LANG']['not_in_range'],$row['start_price'], $row['end_price']); + die($json->encode($result)); + } + + /* 检查用户是否已经出同一价格 */ + $sql = 'SELECT COUNT(*) FROM '.$GLOBALS['ecs']->table('snatch_log'). " WHERE snatch_id = '$id' AND user_id = '$_SESSION[user_id]' AND bid_price = '$price'"; + if ($GLOBALS['db']->getOne($sql) > 0) + { + $result['error'] = 1; + $result['content'] = sprintf($GLOBALS['_LANG']['also_bid'], price_format($price, false)); + die($json->encode($result)); + } + + /* 检查用户积分是否足够 */ + $sql = 'SELECT pay_points FROM ' .$ecs->table('users'). " WHERE user_id = '" . $_SESSION['user_id']. "'"; + $pay_points = $db->getOne($sql); + if ($row['cost_points'] > $pay_points) + { + $result['error'] = 1; + $result['content'] = $_LANG['lack_pay_points']; + die($json->encode($result)); + } + + log_account_change($_SESSION['user_id'], 0, 0, 0, 0-$row['cost_points'],sprintf($_LANG['snatch_log'], $row['snatch_name'])); //扣除用户积分 + $sql = 'INSERT INTO ' .$ecs->table('snatch_log'). '(snatch_id, user_id, bid_price, bid_time) VALUES'. + "('$id', '" .$_SESSION['user_id']. "', '" .$price."', " .gmtime(). ")"; + $db->query($sql); + + $smarty->assign('myprice', get_myprice($id)); + $smarty->assign('id', $id); + $result['content'] = $smarty->fetch('library/snatch.lbi'); + die($json->encode($result)); +} + +/*------------------------------------------------------ */ +//-- 购买商品 +/*------------------------------------------------------ */ +if ($_REQUEST['act'] == 'buy') +{ + if (empty($id)) + { + ecs_header("Location: ./\n"); + exit; + } + + if (empty($_SESSION['user_id'])) + { + show_message($_LANG['not_login']); + } + + $snatch = get_snatch($id); + + + if (empty($snatch)) + { + ecs_header("Location: ./\n"); + exit; + } + + /* 未结束,不能购买 */ + if (empty($snatch['is_end'])) + { + $page = build_uri('snatch', array('sid'=>$id)); + ecs_header("Location: $page\n"); + exit; + } + + $result = get_snatch_result($id); + + if ($_SESSION['user_id'] != $result['user_id']) + { + show_message($_LANG['not_for_you']); + } + + //检查是否已经购买过 + if ($result['order_count'] > 0) + { + show_message($_LANG['order_placed']); + } + + /* 处理规格属性 */ + $goods_attr = ''; + $goods_attr_id = ''; + if ($snatch['product_id'] > 0) + { + $product_info = get_good_products($snatch['goods_id'], 'AND product_id = ' . $snatch['product_id']); + + $goods_attr_id = str_replace('|', ',', $product_info[0]['goods_attr']); + + $attr_list = array(); + $sql = "SELECT a.attr_name, g.attr_value " . + "FROM " . $ecs->table('goods_attr') . " AS g, " . + $ecs->table('attribute') . " AS a " . + "WHERE g.attr_id = a.attr_id " . + "AND g.goods_attr_id " . db_create_in($goods_attr_id); + $res = $db->query($sql); + while ($row = $db->fetchRow($res)) + { + $attr_list[] = $row['attr_name'] . ': ' . $row['attr_value']; + } + $goods_attr = join('', $attr_list); + } + else + { + $snatch['product_id'] = 0; + } + + /* 清空购物车中所有商品 */ + include_once(ROOT_PATH . 'includes/lib_order.php'); + clear_cart(CART_SNATCH_GOODS); + + /* 加入购物车 */ + $cart = array( + 'user_id' => $_SESSION['user_id'], + 'session_id' => SESS_ID, + 'goods_id' => $snatch['goods_id'], + 'product_id' => $snatch['product_id'], + 'goods_sn' => addslashes($snatch['goods_sn']), + 'goods_name' => addslashes($snatch['goods_name']), + 'market_price' => $snatch['market_price'], + 'goods_price' => $result['buy_price'], + 'goods_number' => 1, + 'goods_attr' => $goods_attr, + 'goods_attr_id' => $goods_attr_id, + 'is_real' => $snatch['is_real'], + 'extension_code' => addslashes($snatch['extension_code']), + 'parent_id' => 0, + 'rec_type' => CART_SNATCH_GOODS, + 'is_gift' => 0 + ); + + $db->autoExecute($ecs->table('cart'), $cart, 'INSERT'); + + /* 记录购物流程类型:夺宝奇兵 */ + $_SESSION['flow_type'] = CART_SNATCH_GOODS; + $_SESSION['extension_code'] = 'snatch'; + $_SESSION['extension_id'] = $id; + + /* 进入收货人页面 */ + ecs_header("Location: ./flow.php?step=consignee\n"); + exit; + +} + +/** + * 取得用户对当前活动的所出过的价格 + * + * @access public + * @param + * + * @return void + */ +function get_myprice($id) +{ + $my_only_price = array(); + $my_price = array(); + $pay_points = 0; + $bid_price = array(); + if (!empty($_SESSION['user_id'])) + { + /* 取得用户所有价格 */ + $sql = 'SELECT bid_price FROM '.$GLOBALS['ecs']->table('snatch_log'). " WHERE snatch_id = '$id' AND user_id = '$_SESSION[user_id]' ORDER BY bid_time DESC"; + $my_price = $GLOBALS['db']->GetCol($sql); + + if ($my_price) + { + /* 取得用户唯一价格 */ + $sql = 'SELECT bid_price , count(*) AS num FROM '.$GLOBALS['ecs']->table('snatch_log'). " WHERE snatch_id ='$id' AND bid_price " . db_create_in(join(',', $my_price)). ' GROUP BY bid_price HAVING num = 1'; + $my_only_price = $GLOBALS['db']->GetCol($sql); + } + + for ($i = 0, $count = count($my_price); $i < $count; $i++) + { + $bid_price[] = array('price' => price_format($my_price[$i], false), + 'is_only' => in_array($my_price[$i],$my_only_price) + ); + } + + $sql = 'SELECT pay_points FROM '. $GLOBALS['ecs']->table('users')." WHERE user_id = '$_SESSION[user_id]'"; + $pay_points = $GLOBALS['db']->GetOne($sql); + $pay_points = $pay_points.$GLOBALS['_CFG']['integral_name']; + } + + /* 活动结束时间 */ + $sql = 'SELECT end_time FROM ' .$GLOBALS['ecs']->table('goods_activity'). + " WHERE act_id = '$id' AND act_type=" . GAT_SNATCH; + $end_time = $GLOBALS['db']->getOne($sql); + $my_price = array( + 'pay_points' => $pay_points, + 'bid_price' => $bid_price, + 'is_end' => gmtime() > $end_time + ); + + return $my_price; +} + +/** + * 取得当前活动的前n个出价 + * + * @access public + * @param int $num 列表个数(取前5个) + * + * @return void + */ +function get_price_list($id, $num = 5) +{ + $sql = 'SELECT t1.log_id, t1.bid_price, t2.user_name FROM '.$GLOBALS['ecs']->table('snatch_log').' AS t1, '.$GLOBALS['ecs']->table('users')." AS t2 WHERE snatch_id = '$id' AND t1.user_id = t2.user_id ORDER BY t1.log_id DESC LIMIT $num"; + $res = $GLOBALS['db']->query($sql); + $price_list = array(); + while ($row = $GLOBALS['db']->FetchRow($res)) + { + $price_list[] = array('bid_price'=>price_format($row['bid_price'], false),'user_name'=>$row['user_name']); + } + return $price_list; +} + +/** + * 取的最近的几次活动。 + * + * @access public + * @param + * + * @return void + */ +function get_snatch_list($num = 10) +{ + $now = gmtime(); + $sql = 'SELECT act_id AS snatch_id, act_name AS snatch_name, end_time '. + ' FROM ' . $GLOBALS['ecs']->table('goods_activity'). + " WHERE start_time <= '$now' AND act_type=" . GAT_SNATCH . + " ORDER BY end_time DESC LIMIT $num"; + $snatch_list = array(); + $overtime = 0; + $res = $GLOBALS['db']->query($sql); + while ($row = $GLOBALS['db']->FetchRow($res)) + { + $overtime = $row['end_time'] > $now ? 0 : 1; + $snatch_list[] = array( + 'snatch_id' => $row['snatch_id'], + 'snatch_name' => $row['snatch_name'], + 'overtime' => $overtime, + 'url'=>build_uri('snatch', array('sid'=>$row['snatch_id'])) + ); + } + return $snatch_list; + +} + +/** + * 取得当前活动信息 + * + * @access public + * + * @return 活动名称 + */ +function get_snatch($id) +{ + $sql = "SELECT g.goods_id, g.goods_sn, g.is_real, g.goods_name, g.extension_code, g.market_price, g.shop_price AS org_price, product_id, " . + "IFNULL(mp.user_price, g.shop_price * '$_SESSION[discount]') AS shop_price, " . + "g.promote_price, g.promote_start_date, g.promote_end_date, g.goods_brief, g.goods_thumb, " . + "ga.act_name AS snatch_name, ga.start_time, ga.end_time, ga.ext_info, ga.act_desc AS `desc` ". + "FROM " .$GLOBALS['ecs']->table('goods_activity'). " AS ga " . + "LEFT JOIN " . $GLOBALS['ecs']->table('goods')." AS g " . + "ON g.goods_id = ga.goods_id " . + "LEFT JOIN " . $GLOBALS['ecs']->table('member_price') . " AS mp " . + "ON mp.goods_id = g.goods_id AND mp.user_rank = '$_SESSION[user_rank]' " . + "WHERE ga.act_id = '$id' AND g.is_delete = 0"; + + $goods = $GLOBALS['db']->GetRow($sql); + + if ($goods) + { + $promote_price = bargain_price($goods['promote_price'], $goods['promote_start_date'], $goods['promote_end_date']); + $goods['formated_market_price'] = price_format($goods['market_price']); + $goods['formated_shop_price'] = price_format($goods['shop_price']); + $goods['formated_promote_price'] = ($promote_price > 0) ? price_format($promote_price) : ''; + $goods['goods_thumb'] = get_image_path($goods['goods_id'], $goods['goods_thumb'], true); + $goods['url'] = build_uri('goods', array('gid'=>$goods['goods_id']), $goods['goods_name']); + $goods['start_time'] = local_date($GLOBALS['_CFG']['time_format'], $goods['start_time']); + + $info = unserialize($goods['ext_info']); + if ($info) + { + foreach ($info as $key => $val) + { + $goods[$key] = $val; + } + $goods['is_end'] = gmtime() > $goods['end_time']; + $goods['formated_start_price'] = price_format($goods['start_price']); + $goods['formated_end_price'] = price_format($goods['end_price']); + $goods['formated_max_price'] = price_format($goods['max_price']); + } + /* 将结束日期格式化为格林威治标准时间时间戳 */ + $goods['gmt_end_time'] = $goods['end_time']; + $goods['end_time'] = local_date($GLOBALS['_CFG']['time_format'], $goods['end_time']); + $goods['snatch_time'] = sprintf($GLOBALS['_LANG']['snatch_start_time'], $goods['start_time'], $goods['end_time']); + + return $goods; + } + else + { + return false; + } +} + +/** + * 获取最近要到期的活动id,没有则返回 0 + * + * @access public + * @param + * + * @return void + */ +function get_last_snatch() +{ + $now = gmtime(); + $sql = 'SELECT act_id FROM ' . $GLOBALS['ecs']->table('goods_activity'). + " WHERE start_time < '$now' AND end_time > '$now' AND act_type = " . GAT_SNATCH . + " ORDER BY end_time ASC LIMIT 1"; + return $GLOBALS['db']->GetOne($sql); +} + +?> \ No newline at end of file diff --git a/suggest.css b/suggest.css new file mode 100644 index 0000000..d8c3e75 --- /dev/null +++ b/suggest.css @@ -0,0 +1,71 @@ +#search_suggest +{ + position:absolute; + background:#ffffff; + text-align:left; + border:1px solid #91A8B4; + width:265px; + top:200px; + left:757px; + z-index:100001; + padding:0; + margin:0; + clear:left; +} +#search_suggest ol{ +margin:0; +padding:0; +display:block; +} + +#search_suggest ol li{ +margin:0; +padding:0; +clear:both; +overflow:hidden; +float:left; +font-size:12px; +line-height:18px; +padding:0 5px; +width:255px; +display:list-item; +} + +#search_suggest li.selected { +background-color:#3366CC; +color:white; +cursor:default; +} + +#search_suggest li.selected span { +color:white; +cursor:default; +} + +#search_suggest li.selected span { +color:white; +cursor:default; +} + + + +#search_suggest li { +list-style-image:none; +list-style-position:outside; +list-style-type:none; +display:list-item; +} + + +.suggest-key { +float:left; +padding-left:5px; +text-align:left; +} + +.suggest-result{ +color:green; +float:right; +padding-right:5px; +text-align:right; +} \ No newline at end of file diff --git a/suggest.js b/suggest.js new file mode 100644 index 0000000..fd7577f --- /dev/null +++ b/suggest.js @@ -0,0 +1,128 @@ +var $$=function(node){ +return document.getElementById(node); +} +var $N=function(obj,node){ +return obj.getElementsByTagName(node); +} + + +var j=-1; +var temp_str; +function ajax_keyword(V) +{ + Ajax.call('search_suggest.php', 'keywords='+V, search_response, "POST", "TEXT"); +} + +function search_response(result) +{ + var res = result.parseJSON(); + var ele = document.getElementById("search_suggest"); + if(res.content!="") + { + ele.innerHTML = res.content; + $$("search_suggest").style.display="block"; + } + else + { + closediv();return; + } +} + +function keyupdeal(e,V) +{ + initdiv(); + if(temp_str==V)return; + if(V==""){temp_str="";closediv();return;} + var keyc; + if(window.event){keyc=e.keyCode;}else if(e.which){keyc=e.which;} + if(keyc==1)return; + if(keyc!=40 && keyc!=38){ajax_keyword(V);temp_str=V;} +} + +function form_submit(obj) +{ + $$("keyword").value=obj.childNodes[0].firstChild.nodeValue; + $$("searchForm").submit(); +} + +function keydowndeal(e) +{ +var keyc; +var obj=$$("search_suggest"); +if(window.event){keyc=e.keyCode;}else if(e.which){keyc=e.which;} +if(keyc==40||keyc==38) + { + if(keyc==40) + { + if(j<$N(obj,"li").length){j++;if(j>=$N(obj,"li").length){j=-1;}} + if(j>=$N(obj,"li").length){j=-1;} + } + if(keyc==38) + { + if(j>=0){j--;if(j<=-1){j=$N(obj,"li").length;}}else{j=$N(obj,"li").length-1;} + } + set_style(obj,j); + if(j>=0&&j<$N(obj,"li").length){$$("keyword").value=$N(obj,"li")[j].childNodes[0].firstChild.nodeValue;} + else{$$("keyword").value=temp_str;} + } +} + +function set_style(obj,num) +{ + for(var i=0;i<$N(obj,"li").length;i++){var li_node=$N(obj,"li")[i];li_node.className="";} + if(j>=0 && j<$N(obj,"li").length){var i_node=$N(obj,"li")[j];$N(obj,"li")[j].className="selected";} +} +function closediv() +{ + document.getElementById("search_suggest").innerHTML=""; + document.getElementById("search_suggest").style.display="none"; +} + +function initdiv(){ + var x=0,y=0; + p=$$("keyword"); + //alert("suggest_top"+$$("search_suggest").style.top.toString()); + //alert("suggest_left"+$$("search_suggest").style.left.toString()); + while (p) + { + x += p.offsetLeft || 0; + y += p.offsetTop || 0; + p = p.offsetParent; + } + $$("search_suggest").style.top=(y+20).toString()+"px"; + $$("search_suggest").style.left=x.toString()+"px"; +} + +function suggestOver(obj) +{ + _over(); + obj.className='selected'; +} + +function suggestOut(obj) +{ + _out(); + obj.className=''; +} + +function AddEvent(a, b, c){ + !document.all ? a.addEventListener(b, c, false) : a.attachEvent("on" + b, c); + +} +function DelEvent(a, b, c){ + !document.all ? a.removeEventListener(b, c, false) : a.detachEvent("on" + b, c); + a.onblur=""; +} + +function _over() +{ + DelEvent($$('keyword'), 'blur', closediv); +} + +function _out() +{ + AddEvent($$('keyword'), 'blur', closediv); +} +window.onresize = function(){ + initdiv(); +} diff --git a/tag_cloud.php b/tag_cloud.php new file mode 100644 index 0000000..9fa9387 --- /dev/null +++ b/tag_cloud.php @@ -0,0 +1,49 @@ +assign('page_title', $position['title']); // 页面标题 + $smarty->assign('ur_here', $position['ur_here']); // 当前位置 + $smarty->assign('categories', get_categories_tree()); // 分类树 + $smarty->assign('helps', get_shop_help()); // 网店帮助 + $smarty->assign('top_goods', get_top10()); // 销售排行 + $smarty->assign('promotion_info', get_promotion_info()); + + /* 调查 */ + $vote = get_vote(); + if (!empty($vote)) + { + $smarty->assign('vote_id', $vote['id']); + $smarty->assign('vote', $vote['content']); + } + + assign_dynamic('tag_cloud'); + + $tags = get_tags(); + + if (!empty($tags)) + { + include_once(ROOT_PATH . 'includes/lib_clips.php'); + color_tag($tags); + } + + $smarty->assign('tags', $tags); + + $smarty->display('tag_cloud.dwt'); +?> \ No newline at end of file diff --git a/topic.php b/topic.php new file mode 100644 index 0000000..fac7ab5 --- /dev/null +++ b/topic.php @@ -0,0 +1,135 @@ + + * @version: v2.1 + * --------------------------------------------- + */ + +define('IN_ECS', true); + +require(dirname(__FILE__) . '/includes/init.php'); + +if ((DEBUG_MODE & 2) != 2) +{ + $smarty->caching = true; +} +$topic_id = empty($_REQUEST['topic_id']) ? 0 : intval($_REQUEST['topic_id']); + +$sql = "SELECT template FROM " . $ecs->table('topic') . + "WHERE topic_id = '$topic_id' and " . gmtime() . " >= start_time and " . gmtime() . "<= end_time"; + +$topic = $db->getRow($sql); + +if(empty($topic)) +{ + /* 如果没有找到任何记录则跳回到首页 */ + ecs_header("Location: ./\n"); + exit; +} + +$templates = empty($topic['template']) ? 'topic.dwt' : $topic['template']; + +$cache_id = sprintf('%X', crc32($_SESSION['user_rank'] . '-' . $_CFG['lang'] . '-' . $topic_id)); + +if (!$smarty->is_cached($templates, $cache_id)) +{ + $sql = "SELECT * FROM " . $ecs->table('topic') . " WHERE topic_id = '$topic_id'"; + + $topic = $db->getRow($sql); + $topic['data'] = addcslashes($topic['data'], "'"); + $tmp = @unserialize($topic["data"]); + $arr = (array)$tmp; + + $goods_id = array(); + + foreach ($arr AS $key=>$value) + { + foreach($value AS $k => $val) + { + $opt = explode('|', $val); + $arr[$key][$k] = $opt[1]; + $goods_id[] = $opt[1]; + } + } + + $sql = 'SELECT g.goods_id, g.goods_name, g.goods_name_style, g.market_price, g.is_new, g.is_best, g.is_hot, g.shop_price AS org_price, ' . + "IFNULL(mp.user_price, g.shop_price * '$_SESSION[discount]') AS shop_price, g.promote_price, " . + 'g.promote_start_date, g.promote_end_date, g.goods_brief, g.goods_thumb , g.goods_img ' . + 'FROM ' . $GLOBALS['ecs']->table('goods') . ' AS g ' . + 'LEFT JOIN ' . $GLOBALS['ecs']->table('member_price') . ' AS mp ' . + "ON mp.goods_id = g.goods_id AND mp.user_rank = '$_SESSION[user_rank]' " . + "WHERE " . db_create_in($goods_id, 'g.goods_id'); + + $res = $GLOBALS['db']->query($sql); + + $sort_goods_arr = array(); + + while ($row = $GLOBALS['db']->fetchRow($res)) + { + if ($row['promote_price'] > 0) + { + $promote_price = bargain_price($row['promote_price'], $row['promote_start_date'], $row['promote_end_date']); + $row['promote_price'] = $promote_price > 0 ? price_format($promote_price) : ''; + } + else + { + $row['promote_price'] = ''; + } + + if ($row['shop_price'] > 0) + { + $row['shop_price'] = price_format($row['shop_price']); + } + else + { + $row['shop_price'] = ''; + } + + $row['url'] = build_uri('goods', array('gid'=>$row['goods_id']), $row['goods_name']); + $row['goods_style_name'] = add_style($row['goods_name'], $row['goods_name_style']); + $row['short_name'] = $GLOBALS['_CFG']['goods_name_length'] > 0 ? + sub_str($row['goods_name'], $GLOBALS['_CFG']['goods_name_length']) : $row['goods_name']; + $row['goods_thumb'] = get_image_path($row['goods_id'], $row['goods_thumb'], true); + $row['short_style_name'] = add_style($row['short_name'], $row['goods_name_style']); + + foreach ($arr AS $key => $value) + { + foreach ($value AS $val) + { + if ($val == $row['goods_id']) + { + $key = $key == 'default' ? $_LANG['all_goods'] : $key; + $sort_goods_arr[$key][] = $row; + } + } + } + } + + /* 模板赋值 */ + assign_template(); + $position = assign_ur_here(); + $smarty->assign('page_title', $position['title']); // 页面标题 + $smarty->assign('ur_here', $position['ur_here'] . '> ' . $topic['title']); // 当前位置 + $smarty->assign('show_marketprice', $_CFG['show_marketprice']); + $smarty->assign('sort_goods_arr', $sort_goods_arr); // 商品列表 + $smarty->assign('topic', $topic); // 专题信息 + $smarty->assign('keywords', $topic['keywords']); // 专题信息 + $smarty->assign('description', $topic['description']); // 专题信息 + $smarty->assign('title_pic', $topic['title_pic']); // 分类标题图片地址 + $smarty->assign('base_style', '#' . $topic['base_style']); // 基本风格样式颜色 + + $template_file = empty($topic['template']) ? 'topic.dwt' : $topic['template']; +} +/* 显示模板 */ +$smarty->display($templates, $cache_id); + +?> \ No newline at end of file diff --git a/update_cart_goods.php b/update_cart_goods.php new file mode 100644 index 0000000..1bdead1 --- /dev/null +++ b/update_cart_goods.php @@ -0,0 +1,92 @@ + 0, 'message' => '', 'content' => '', 'goods_id' => ''); +$json = new JSON; +if($_POST['id']) +{ + //查询商品id + $sql = "select goods_id from ".$GLOBALS['ecs']->table('cart')." where rec_id = ". $_POST['id']; + $goods_id = $GLOBALS['db']->getOne($sql); + + //验证库存 by mike + $sql = "select goods_number from ".$GLOBALS['ecs']->table('goods')." where goods_id = ". $goods_id; + $goods_stock_number = $GLOBALS['db']->getOne($sql); + + if($_POST['number'] > $goods_stock_number){ + $result['rec_id'] = $_POST['id']; + $result['error'] = 1; + $result['message'] = '库存不足'; + $result['stock'] = $goods_stock_number; + die($json->encode($result)); + } + + $sql = 'UPDATE '.$GLOBALS['ecs']->table('cart')." SET goods_number = '". $_POST['number'] ."' WHERE rec_id=".$_POST['id']; + $GLOBALS['db']->query($sql); +} +$sql = 'SELECT c.*,g.goods_name,g.goods_thumb,g.goods_id,c.goods_number,c.goods_price' . + ' FROM ' . $GLOBALS['ecs']->table('cart') ." AS c ". + " LEFT JOIN ".$GLOBALS['ecs']->table('goods')." AS g ON g.goods_id=c.goods_id ". + " WHERE session_id = '" . SESS_ID . "' AND rec_type = '" . CART_GENERAL_GOODS . "'"; +$row = $GLOBALS['db']->GetAll($sql); +$arr = array(); +foreach($row AS $k=>$v) +{ + $arr[$k]['goods_thumb'] =get_image_path($v['goods_id'], $v['goods_thumb'], true); + $arr[$k]['short_name'] = $GLOBALS['_CFG']['goods_name_length'] > 0 ? + sub_str($v['goods_name'], $GLOBALS['_CFG']['goods_name_length']) : $v['goods_name']; + $arr[$k]['url'] = build_uri('goods', array('gid' => $v['goods_id']), $v['goods_name']); + $arr[$k]['goods_number'] = $v['goods_number']; + $arr[$k]['goods_name'] = $v['goods_name']; + $arr[$k]['goods_price'] = price_format($v['goods_price']); + $arr[$k]['goods_amount_price'] = price_format($v['goods_price']*$v['goods_number']); + $arr[$k]['rec_id'] = $v['rec_id']; +} +$sql = 'SELECT SUM(goods_number) AS number, SUM(goods_price * goods_number) AS amount' . + ' FROM ' . $GLOBALS['ecs']->table('cart') . + " WHERE session_id = '" . SESS_ID . "' AND rec_type = '" . CART_GENERAL_GOODS . "'"; +$row = $GLOBALS['db']->GetRow($sql); + +if ($row) +{ + $number = intval($row['number']); + $amount = floatval($row['amount']); +} +else +{ + $number = 0; + $amount = 0; +} + +$GLOBALS['smarty']->assign('str',sprintf($GLOBALS['_LANG']['cart_info'], $number, price_format($amount, false))); +$GLOBALS['smarty']->assign('cart_list_number',$number); +$GLOBALS['smarty']->assign('cart_list_amount',price_format($amount)); +$GLOBALS['smarty']->assign('goods',$arr); + +$result['content'] = $GLOBALS['smarty']->fetch('library/cart_info.lbi'); + +//$smarty->assign('order',$order); + +die($json->encode($result)); + + +?> \ No newline at end of file diff --git a/user.php b/user.php new file mode 100644 index 0000000..ab87a57 --- /dev/null +++ b/user.php @@ -0,0 +1,2747 @@ +assign('affiliate', $affiliate); + +// 不需要登录的操作或自己验证是否登录(如ajax处理)的act +$not_login_arr = +array('login','act_login','register','act_register','act_edit_password','get_password','send_pwd_email','password', 'signin', 'add_tag', 'collect', 'return_to_cart', 'logout', 'email_list', 'validate_email', 'send_hash_mail', 'order_query', 'is_registered', 'check_email','clear_history','qpassword_name', 'get_passwd_question', 'check_answer'); + +/* 显示页面的action列表 */ +$ui_arr = array('register', 'login', 'profile', 'order_list', 'order_detail', 'address_list', 'collection_list', +'message_list', 'tag_list', 'get_password', 'reset_password', 'booking_list', 'add_booking', 'account_raply', +'account_deposit', 'account_log', 'account_detail', 'act_account', 'pay', 'default', 'bonus', 'group_buy', 'group_buy_detail', 'affiliate', 'comment_list','validate_email','track_packages', 'transform_points','qpassword_name', 'get_passwd_question', 'check_answer'); + +/* 未登录处理 */ +if (empty($_SESSION['user_id'])) +{ + if (!in_array($action, $not_login_arr)) + { + if (in_array($action, $ui_arr)) + { + /* 如果需要登录,并是显示页面的操作,记录当前操作,用于登录后跳转到相应操作 + if ($action == 'login') + { + if (isset($_REQUEST['back_act'])) + { + $back_act = trim($_REQUEST['back_act']); + } + } + else + {}*/ + if (!empty($_SERVER['QUERY_STRING'])) + { + $back_act = 'user.php?' . $_SERVER['QUERY_STRING']; + } + $action = 'login'; + } + else + { + //未登录提交数据。非正常途径提交数据! + die($_LANG['require_login']); + } + } +} + +/* 如果是显示页面,对页面进行相应赋值 */ +if (in_array($action, $ui_arr)) +{ + assign_template(); + $position = assign_ur_here(0, $_LANG['user_center']); + $smarty->assign('page_title', $position['title']); // 页面标题 + $smarty->assign('ur_here', $position['ur_here']); + $sql = "SELECT value FROM " . $ecs->table('shop_config') . " WHERE id = 419"; + $row = $db->getRow($sql); + $car_off = $row['value']; + $smarty->assign('car_off', $car_off); + /* 是否显示积分兑换 */ + if (!empty($_CFG['points_rule']) && unserialize($_CFG['points_rule'])) + { + $smarty->assign('show_transform_points', 1); + } + $smarty->assign('helps', get_shop_help()); // 网店帮助 + $smarty->assign('data_dir', DATA_DIR); // 数据目录 + $smarty->assign('action', $action); + $smarty->assign('lang', $_LANG); +} + +//用户中心欢迎页 +if ($action == 'default') +{ + include_once(ROOT_PATH .'includes/lib_clips.php'); + if ($rank = get_rank_info()) + { + $smarty->assign('rank_name', sprintf($_LANG['your_level'], $rank['rank_name'])); + if (!empty($rank['next_rank_name'])) + { + $smarty->assign('next_rank_name', sprintf($_LANG['next_level'], $rank['next_rank'] ,$rank['next_rank_name'])); + } + } + $smarty->assign('info', get_user_default($user_id)); + $smarty->assign('user_notice', $_CFG['user_notice']); + $smarty->assign('prompt', get_user_prompt($user_id)); + $smarty->display('user_clips.dwt'); +} + +/* 显示会员注册界面 */ +if ($action == 'register') +{ + if (!isset($back_act) && isset($GLOBALS['_SERVER']['HTTP_REFERER'])) + { + $back_act = strpos($GLOBALS['_SERVER']['HTTP_REFERER'], 'user.php') ? './index.php' : $GLOBALS['_SERVER']['HTTP_REFERER']; + } + + /* 取出注册扩展字段 */ + $sql = 'SELECT * FROM ' . $ecs->table('reg_fields') . ' WHERE type < 2 AND display = 1 ORDER BY dis_order, id'; + $extend_info_list = $db->getAll($sql); + $smarty->assign('extend_info_list', $extend_info_list); + + /* 验证码相关设置 */ + if ((intval($_CFG['captcha']) & CAPTCHA_REGISTER) && gd_version() > 0) + { + $smarty->assign('enabled_captcha', 1); + $smarty->assign('rand', mt_rand()); + } + + /* 密码提示问题 */ + $smarty->assign('passwd_questions', $_LANG['passwd_questions']); + + /* 增加是否关闭注册 */ + $smarty->assign('shop_reg_closed', $_CFG['shop_reg_closed']); +// $smarty->assign('back_act', $back_act); + $smarty->display('user_passport.dwt'); +} + +/* 注册会员的处理 */ +elseif ($action == 'act_register') +{ + /* 增加是否关闭注册 */ + if ($_CFG['shop_reg_closed']) + { + $smarty->assign('action', 'register'); + $smarty->assign('shop_reg_closed', $_CFG['shop_reg_closed']); + $smarty->display('user_passport.dwt'); + } + else + { + include_once(ROOT_PATH . 'includes/lib_passport.php'); + + $username = isset($_POST['username']) ? trim($_POST['username']) : ''; + $password = isset($_POST['password']) ? trim($_POST['password']) : ''; + $email = isset($_POST['email']) ? trim($_POST['email']) : ''; + $other['msn'] = isset($_POST['extend_field1']) ? $_POST['extend_field1'] : ''; + $other['qq'] = isset($_POST['extend_field2']) ? $_POST['extend_field2'] : ''; + $other['office_phone'] = isset($_POST['extend_field3']) ? $_POST['extend_field3'] : ''; + $other['home_phone'] = isset($_POST['extend_field4']) ? $_POST['extend_field4'] : ''; + $other['mobile_phone'] = isset($_POST['extend_field5']) ? $_POST['extend_field5'] : ''; + $sel_question = empty($_POST['sel_question']) ? '' : $_POST['sel_question']; + $passwd_answer = isset($_POST['passwd_answer']) ? trim($_POST['passwd_answer']) : ''; + + $back_act = isset($_POST['back_act']) ? trim($_POST['back_act']) : ''; + + if(empty($_POST['agreement'])) + { + show_message($_LANG['passport_js']['agreement']); + } + if (strlen($username) < 3) + { + show_message($_LANG['passport_js']['username_shorter']); + } + + if (strlen($password) < 6) + { + show_message($_LANG['passport_js']['password_shorter']); + } + + if (strpos($password, ' ') > 0) + { + show_message($_LANG['passwd_balnk']); + } + + /* 验证码检查 */ + if ((intval($_CFG['captcha']) & CAPTCHA_REGISTER) && gd_version() > 0) + { + if (empty($_POST['captcha'])) + { + show_message($_LANG['invalid_captcha'], $_LANG['sign_up'], 'user.php?act=register', 'error'); + } + + /* 检查验证码 */ + include_once('includes/cls_captcha.php'); + + $validator = new captcha(); + if (!$validator->check_word($_POST['captcha'])) + { + show_message($_LANG['invalid_captcha'], $_LANG['sign_up'], 'user.php?act=register', 'error'); + } + } + + if (register($username, $password, $email, $other) !== false) + { + /*把新注册用户的扩展信息插入数据库*/ + $sql = 'SELECT id FROM ' . $ecs->table('reg_fields') . ' WHERE type = 0 AND display = 1 ORDER BY dis_order, id'; //读出所有自定义扩展字段的id + $fields_arr = $db->getAll($sql); + + $extend_field_str = ''; //生成扩展字段的内容字符串 + foreach ($fields_arr AS $val) + { + $extend_field_index = 'extend_field' . $val['id']; + if(!empty($_POST[$extend_field_index])) + { + $temp_field_content = strlen($_POST[$extend_field_index]) > 100 ? mb_substr($_POST[$extend_field_index], 0, 99) : $_POST[$extend_field_index]; + $extend_field_str .= " ('" . $_SESSION['user_id'] . "', '" . $val['id'] . "', '" . $temp_field_content . "'),"; + } + } + $extend_field_str = substr($extend_field_str, 0, -1); + + if ($extend_field_str) //插入注册扩展数据 + { + $sql = 'INSERT INTO '. $ecs->table('reg_extend_info') . ' (`user_id`, `reg_field_id`, `content`) VALUES' . $extend_field_str; + $db->query($sql); + } + + /* 写入密码提示问题和答案 */ + if (!empty($passwd_answer) && !empty($sel_question)) + { + $sql = 'UPDATE ' . $ecs->table('users') . " SET `passwd_question`='$sel_question', `passwd_answer`='$passwd_answer' WHERE `user_id`='" . $_SESSION['user_id'] . "'"; + $db->query($sql); + } + + $ucdata = empty($user->ucdata)? "" : $user->ucdata; + show_message(sprintf($_LANG['register_success'], $username . $ucdata), array($_LANG['back_up_page'], $_LANG['profile_lnk']), array($back_act, 'user.php'), 'info'); + } + else + { + $err->show($_LANG['sign_up'], 'user.php?act=register'); + } + } +} + +/* 验证用户注册邮件 */ +elseif ($action == 'validate_email') +{ + $hash = empty($_GET['hash']) ? '' : trim($_GET['hash']); + if ($hash) + { + include_once(ROOT_PATH . 'includes/lib_passport.php'); + $id = register_hash('decode', $hash); + if ($id > 0) + { + $sql = "UPDATE " . $ecs->table('users') . " SET is_validated = 1 WHERE user_id='$id'"; + $db->query($sql); + $sql = 'SELECT user_name, email FROM ' . $ecs->table('users') . " WHERE user_id = '$id'"; + $row = $db->getRow($sql); + show_message(sprintf($_LANG['validate_ok'], $row['user_name'], $row['email']),$_LANG['profile_lnk'], 'user.php'); + } + } + show_message($_LANG['validate_fail']); +} + +/* 验证用户注册用户名是否可以注册 */ +elseif ($action == 'is_registered') +{ + include_once(ROOT_PATH . 'includes/lib_passport.php'); + + $username = trim($_GET['username']); + $username = json_str_iconv($username); + + if ($user->check_user($username) || admin_registered($username)) + { + echo 'false'; + } + else + { + echo 'true'; + } +} + +/* 验证用户邮箱地址是否被注册 */ +elseif($action == 'check_email') +{ + $email = trim($_GET['email']); + if ($user->check_email($email)) + { + echo 'false'; + } + else + { + echo 'ok'; + } +} +/* 用户登录界面 */ +elseif ($action == 'login') +{ + if (empty($back_act)) + { + if (empty($back_act) && isset($GLOBALS['_SERVER']['HTTP_REFERER'])) + { + $back_act = strpos($GLOBALS['_SERVER']['HTTP_REFERER'], 'user.php') ? './index.php' : $GLOBALS['_SERVER']['HTTP_REFERER']; + } + else + { + $back_act = 'user.php'; + } + + } + + + $captcha = intval($_CFG['captcha']); + if (($captcha & CAPTCHA_LOGIN) && (!($captcha & CAPTCHA_LOGIN_FAIL) || (($captcha & CAPTCHA_LOGIN_FAIL) && $_SESSION['login_fail'] > 2)) && gd_version() > 0) + { + $GLOBALS['smarty']->assign('enabled_captcha', 1); + $GLOBALS['smarty']->assign('rand', mt_rand()); + } + + $smarty->assign('back_act', $back_act); + $smarty->display('user_passport.dwt'); +} + +/* 处理会员的登录 */ +elseif ($action == 'act_login') +{ + $username = isset($_POST['username']) ? trim($_POST['username']) : ''; + $password = isset($_POST['password']) ? trim($_POST['password']) : ''; + $back_act = isset($_POST['back_act']) ? trim($_POST['back_act']) : ''; + + + $captcha = intval($_CFG['captcha']); + if (($captcha & CAPTCHA_LOGIN) && (!($captcha & CAPTCHA_LOGIN_FAIL) || (($captcha & CAPTCHA_LOGIN_FAIL) && $_SESSION['login_fail'] > 2)) && gd_version() > 0) + { + if (empty($_POST['captcha'])) + { + show_message($_LANG['invalid_captcha'], $_LANG['relogin_lnk'], 'user.php', 'error'); + } + + /* 检查验证码 */ + include_once('includes/cls_captcha.php'); + + $validator = new captcha(); + $validator->session_word = 'captcha_login'; + if (!$validator->check_word($_POST['captcha'])) + { + show_message($_LANG['invalid_captcha'], $_LANG['relogin_lnk'], 'user.php', 'error'); + } + } + + if ($user->login($username, $password,isset($_POST['remember']))) + { + update_user_info(); + recalculate_price(); + + $ucdata = isset($user->ucdata)? $user->ucdata : ''; + show_message($_LANG['login_success'] . $ucdata , array($_LANG['back_up_page'], $_LANG['profile_lnk']), array($back_act,'user.php'), 'info'); + } + else + { + $_SESSION['login_fail'] ++ ; + show_message($_LANG['login_failure'], $_LANG['relogin_lnk'], 'user.php', 'error'); + } +} + +/* 处理 ajax 的登录请求 */ +elseif ($action == 'signin') +{ + include_once('includes/cls_json.php'); + $json = new JSON; + + $username = !empty($_POST['username']) ? json_str_iconv(trim($_POST['username'])) : ''; + $password = !empty($_POST['password']) ? trim($_POST['password']) : ''; + $captcha = !empty($_POST['captcha']) ? json_str_iconv(trim($_POST['captcha'])) : ''; + $result = array('error' => 0, 'content' => ''); + + $captcha = intval($_CFG['captcha']); + if (($captcha & CAPTCHA_LOGIN) && (!($captcha & CAPTCHA_LOGIN_FAIL) || (($captcha & CAPTCHA_LOGIN_FAIL) && $_SESSION['login_fail'] > 2)) && gd_version() > 0) + { + if (empty($captcha)) + { + $result['error'] = 1; + $result['content'] = $_LANG['invalid_captcha']; + die($json->encode($result)); + } + + /* 检查验证码 */ + include_once('includes/cls_captcha.php'); + + $validator = new captcha(); + $validator->session_word = 'captcha_login'; + if (!$validator->check_word($_POST['captcha'])) + { + + $result['error'] = 1; + $result['content'] = $_LANG['invalid_captcha']; + die($json->encode($result)); + } + } + + if ($user->login($username, $password)) + { + update_user_info(); //更新用户信息 + recalculate_price(); // 重新计算购物车中的商品价格 + $smarty->assign('user_info', get_user_info()); + $ucdata = empty($user->ucdata)? "" : $user->ucdata; + $result['ucdata'] = $ucdata; + $result['content'] = $smarty->fetch('library/member_info.lbi'); + } + else + { + $_SESSION['login_fail']++; + if ($_SESSION['login_fail'] > 2) + { + $smarty->assign('enabled_captcha', 1); + $result['html'] = $smarty->fetch('library/member_info.lbi'); + } + $result['error'] = 1; + $result['content'] = $_LANG['login_failure']; + } + die($json->encode($result)); +} + +/* 退出会员中心 */ +elseif ($action == 'logout') +{ + if (!isset($back_act) && isset($GLOBALS['_SERVER']['HTTP_REFERER'])) + { + $back_act = strpos($GLOBALS['_SERVER']['HTTP_REFERER'], 'user.php') ? './index.php' : $GLOBALS['_SERVER']['HTTP_REFERER']; + } + + $user->logout(); + $ucdata = empty($user->ucdata)? "" : $user->ucdata; + show_message($_LANG['logout'] . $ucdata, array($_LANG['back_up_page'], $_LANG['back_home_lnk']), array($back_act, 'index.php'), 'info'); +} + +/* 个人资料页面 */ +elseif ($action == 'profile') +{ + include_once(ROOT_PATH . 'includes/lib_transaction.php'); + + $user_info = get_profile($user_id); + + /* 取出注册扩展字段 */ + $sql = 'SELECT * FROM ' . $ecs->table('reg_fields') . ' WHERE type < 2 AND display = 1 ORDER BY dis_order, id'; + $extend_info_list = $db->getAll($sql); + + $sql = 'SELECT reg_field_id, content ' . + 'FROM ' . $ecs->table('reg_extend_info') . + " WHERE user_id = $user_id"; + $extend_info_arr = $db->getAll($sql); + + $temp_arr = array(); + foreach ($extend_info_arr AS $val) + { + $temp_arr[$val['reg_field_id']] = $val['content']; + } + + foreach ($extend_info_list AS $key => $val) + { + switch ($val['id']) + { + case 1: $extend_info_list[$key]['content'] = $user_info['msn']; break; + case 2: $extend_info_list[$key]['content'] = $user_info['qq']; break; + case 3: $extend_info_list[$key]['content'] = $user_info['office_phone']; break; + case 4: $extend_info_list[$key]['content'] = $user_info['home_phone']; break; + case 5: $extend_info_list[$key]['content'] = $user_info['mobile_phone']; break; + default: $extend_info_list[$key]['content'] = empty($temp_arr[$val['id']]) ? '' : $temp_arr[$val['id']] ; + } + } + + $smarty->assign('extend_info_list', $extend_info_list); + + /* 密码提示问题 */ + $smarty->assign('passwd_questions', $_LANG['passwd_questions']); + + $smarty->assign('profile', $user_info); + $smarty->display('user_transaction.dwt'); +} + +/* 修改个人资料的处理 */ +elseif ($action == 'act_edit_profile') +{ + include_once(ROOT_PATH . 'includes/lib_transaction.php'); + + $birthday = trim($_POST['birthdayYear']) .'-'. trim($_POST['birthdayMonth']) .'-'. + trim($_POST['birthdayDay']); + $email = trim($_POST['email']); + $other['msn'] = $msn = isset($_POST['extend_field1']) ? trim($_POST['extend_field1']) : ''; + $other['qq'] = $qq = isset($_POST['extend_field2']) ? trim($_POST['extend_field2']) : ''; + $other['office_phone'] = $office_phone = isset($_POST['extend_field3']) ? trim($_POST['extend_field3']) : ''; + $other['home_phone'] = $home_phone = isset($_POST['extend_field4']) ? trim($_POST['extend_field4']) : ''; + $other['mobile_phone'] = $mobile_phone = isset($_POST['extend_field5']) ? trim($_POST['extend_field5']) : ''; + $sel_question = empty($_POST['sel_question']) ? '' : $_POST['sel_question']; + $passwd_answer = isset($_POST['passwd_answer']) ? trim($_POST['passwd_answer']) : ''; + + /* 更新用户扩展字段的数据 */ + $sql = 'SELECT id FROM ' . $ecs->table('reg_fields') . ' WHERE type = 0 AND display = 1 ORDER BY dis_order, id'; //读出所有扩展字段的id + $fields_arr = $db->getAll($sql); + + foreach ($fields_arr AS $val) //循环更新扩展用户信息 + { + $extend_field_index = 'extend_field' . $val['id']; + if(isset($_POST[$extend_field_index])) + { + $temp_field_content = strlen($_POST[$extend_field_index]) > 100 ? mb_substr(htmlspecialchars($_POST[$extend_field_index]), 0, 99) : htmlspecialchars($_POST[$extend_field_index]); + $sql = 'SELECT * FROM ' . $ecs->table('reg_extend_info') . " WHERE reg_field_id = '$val[id]' AND user_id = '$user_id'"; + if ($db->getOne($sql)) //如果之前没有记录,则插入 + { + $sql = 'UPDATE ' . $ecs->table('reg_extend_info') . " SET content = '$temp_field_content' WHERE reg_field_id = '$val[id]' AND user_id = '$user_id'"; + } + else + { + $sql = 'INSERT INTO '. $ecs->table('reg_extend_info') . " (`user_id`, `reg_field_id`, `content`) VALUES ('$user_id', '$val[id]', '$temp_field_content')"; + } + $db->query($sql); + } + } + + /* 写入密码提示问题和答案 */ + if (!empty($passwd_answer) && !empty($sel_question)) + { + $sql = 'UPDATE ' . $ecs->table('users') . " SET `passwd_question`='$sel_question', `passwd_answer`='$passwd_answer' WHERE `user_id`='" . $_SESSION['user_id'] . "'"; + $db->query($sql); + } + + if (!empty($office_phone) && !preg_match( '/^[\d|\_|\-|\s]+$/', $office_phone ) ) + { + show_message($_LANG['passport_js']['office_phone_invalid']); + } + if (!empty($home_phone) && !preg_match( '/^[\d|\_|\-|\s]+$/', $home_phone) ) + { + show_message($_LANG['passport_js']['home_phone_invalid']); + } + if (!is_email($email)) + { + show_message($_LANG['msg_email_format']); + } + if (!empty($msn) && !is_email($msn)) + { + show_message($_LANG['passport_js']['msn_invalid']); + } + if (!empty($qq) && !preg_match('/^\d+$/', $qq)) + { + show_message($_LANG['passport_js']['qq_invalid']); + } + if (!empty($mobile_phone) && !preg_match('/^[\d-\s]+$/', $mobile_phone)) + { + show_message($_LANG['passport_js']['mobile_phone_invalid']); + } + + + $profile = array( + 'user_id' => $user_id, + 'email' => isset($_POST['email']) ? trim($_POST['email']) : '', + 'sex' => isset($_POST['sex']) ? intval($_POST['sex']) : 0, + 'birthday' => $birthday, + 'other' => isset($other) ? $other : array() + ); + + + if (edit_profile($profile)) + { + show_message($_LANG['edit_profile_success'], $_LANG['profile_lnk'], 'user.php?act=profile', 'info'); + } + else + { + if ($user->error == ERR_EMAIL_EXISTS) + { + $msg = sprintf($_LANG['email_exist'], $profile['email']); + } + else + { + $msg = $_LANG['edit_profile_failed']; + } + show_message($msg, '', '', 'info'); + } +} + +/* 密码找回-->修改密码界面 */ +elseif ($action == 'get_password') +{ + include_once(ROOT_PATH . 'includes/lib_passport.php'); + + if (isset($_GET['code']) && isset($_GET['uid'])) //从邮件处获得的act + { + $code = trim($_GET['code']); + $uid = intval($_GET['uid']); + + /* 判断链接的合法性 */ + $user_info = $user->get_profile_by_id($uid); + if (empty($user_info) || ($user_info && md5($user_info['user_id'] . $_CFG['hash_code'] . $user_info['reg_time']) != $code)) + { + show_message($_LANG['parm_error'], $_LANG['back_home_lnk'], './', 'info'); + } + + $smarty->assign('uid', $uid); + $smarty->assign('code', $code); + $smarty->assign('action', 'reset_password'); + $smarty->display('user_passport.dwt'); + } + else + { + //显示用户名和email表单 + $smarty->display('user_passport.dwt'); + } +} + +/* 密码找回-->输入用户名界面 */ +elseif ($action == 'qpassword_name') +{ + //显示输入要找回密码的账号表单 + $smarty->display('user_passport.dwt'); +} + +/* 密码找回-->根据注册用户名取得密码提示问题界面 */ +elseif ($action == 'get_passwd_question') +{ + if (empty($_POST['user_name'])) + { + show_message($_LANG['no_passwd_question'], $_LANG['back_home_lnk'], './', 'info'); + } + else + { + $user_name = trim($_POST['user_name']); + } + + //取出会员密码问题和答案 + $sql = 'SELECT user_id, user_name, passwd_question, passwd_answer FROM ' . $ecs->table('users') . " WHERE user_name = '" . $user_name . "'"; + $user_question_arr = $db->getRow($sql); + + //如果没有设置密码问题,给出错误提示 + if (empty($user_question_arr['passwd_answer'])) + { + show_message($_LANG['no_passwd_question'], $_LANG['back_home_lnk'], './', 'info'); + } + + $_SESSION['temp_user'] = $user_question_arr['user_id']; //设置临时用户,不具有有效身份 + $_SESSION['temp_user_name'] = $user_question_arr['user_name']; //设置临时用户,不具有有效身份 + $_SESSION['passwd_answer'] = $user_question_arr['passwd_answer']; //存储密码问题答案,减少一次数据库访问 + + $captcha = intval($_CFG['captcha']); + if (($captcha & CAPTCHA_LOGIN) && (!($captcha & CAPTCHA_LOGIN_FAIL) || (($captcha & CAPTCHA_LOGIN_FAIL) && $_SESSION['login_fail'] > 2)) && gd_version() > 0) + { + $GLOBALS['smarty']->assign('enabled_captcha', 1); + $GLOBALS['smarty']->assign('rand', mt_rand()); + } + + $smarty->assign('passwd_question', $_LANG['passwd_questions'][$user_question_arr['passwd_question']]); + $smarty->display('user_passport.dwt'); +} + +/* 密码找回-->根据提交的密码答案进行相应处理 */ +elseif ($action == 'check_answer') +{ + $captcha = intval($_CFG['captcha']); + if (($captcha & CAPTCHA_LOGIN) && (!($captcha & CAPTCHA_LOGIN_FAIL) || (($captcha & CAPTCHA_LOGIN_FAIL) && $_SESSION['login_fail'] > 2)) && gd_version() > 0) + { + if (empty($_POST['captcha'])) + { + show_message($_LANG['invalid_captcha'], $_LANG['back_retry_answer'], 'user.php?act=qpassword_name', 'error'); + } + + /* 检查验证码 */ + include_once('includes/cls_captcha.php'); + + $validator = new captcha(); + $validator->session_word = 'captcha_login'; + if (!$validator->check_word($_POST['captcha'])) + { + show_message($_LANG['invalid_captcha'], $_LANG['back_retry_answer'], 'user.php?act=qpassword_name', 'error'); + } + } + + if (empty($_POST['passwd_answer']) || $_POST['passwd_answer'] != $_SESSION['passwd_answer']) + { + show_message($_LANG['wrong_passwd_answer'], $_LANG['back_retry_answer'], 'user.php?act=qpassword_name', 'info'); + } + else + { + $_SESSION['user_id'] = $_SESSION['temp_user']; + $_SESSION['user_name'] = $_SESSION['temp_user_name']; + unset($_SESSION['temp_user']); + unset($_SESSION['temp_user_name']); + $smarty->assign('uid', $_SESSION['user_id']); + $smarty->assign('action', 'reset_password'); + $smarty->display('user_passport.dwt'); + } +} + +/* 发送密码修改确认邮件 */ +elseif ($action == 'send_pwd_email') +{ + include_once(ROOT_PATH . 'includes/lib_passport.php'); + + /* 初始化会员用户名和邮件地址 */ + $user_name = !empty($_POST['user_name']) ? trim($_POST['user_name']) : ''; + $email = !empty($_POST['email']) ? trim($_POST['email']) : ''; + + //用户名和邮件地址是否匹配 + $user_info = $user->get_user_info($user_name); + + if ($user_info && $user_info['email'] == $email) + { + //生成code + //$code = md5($user_info[0] . $user_info[1]); + + $code = md5($user_info['user_id'] . $_CFG['hash_code'] . $user_info['reg_time']); + //发送邮件的函数 + if (send_pwd_email($user_info['user_id'], $user_name, $email, $code)) + { + show_message($_LANG['send_success'] . $email, $_LANG['back_home_lnk'], './', 'info'); + } + else + { + //发送邮件出错 + show_message($_LANG['fail_send_password'], $_LANG['back_page_up'], './', 'info'); + } + } + else + { + //用户名与邮件地址不匹配 + show_message($_LANG['username_no_email'], $_LANG['back_page_up'], '', 'info'); + } +} + +/* 重置新密码 */ +elseif ($action == 'reset_password') +{ + //显示重置密码的表单 + $smarty->display('user_passport.dwt'); +} + +/* 修改会员密码 */ +elseif ($action == 'act_edit_password') +{ + include_once(ROOT_PATH . 'includes/lib_passport.php'); + + $old_password = isset($_POST['old_password']) ? trim($_POST['old_password']) : null; + $new_password = isset($_POST['new_password']) ? trim($_POST['new_password']) : ''; + $user_id = isset($_POST['uid']) ? intval($_POST['uid']) : $user_id; + $code = isset($_POST['code']) ? trim($_POST['code']) : ''; + + if (strlen($new_password) < 6) + { + show_message($_LANG['passport_js']['password_shorter']); + } + + $user_info = $user->get_profile_by_id($user_id); //论坛记录 + + if (($user_info && (!empty($code) && md5($user_info['user_id'] . $_CFG['hash_code'] . $user_info['reg_time']) == $code)) || ($_SESSION['user_id']>0 && $_SESSION['user_id'] == $user_id && $user->check_user($_SESSION['user_name'], $old_password))) + { + if ($user->edit_user(array('username'=> (empty($code) ? $_SESSION['user_name'] : $user_info['user_name']), 'old_password'=>$old_password, 'password'=>$new_password), empty($code) ? 0 : 1)) + { + $user->logout(); + show_message($_LANG['edit_password_success'], $_LANG['relogin_lnk'], 'user.php?act=login', 'info'); + } + else + { + show_message($_LANG['edit_password_failure'], $_LANG['back_page_up'], '', 'info'); + } + } + else + { + show_message($_LANG['edit_password_failure'], $_LANG['back_page_up'], '', 'info'); + } + +} + +/* 添加一个红包 */ +elseif ($action == 'act_add_bonus') +{ + include_once(ROOT_PATH . 'includes/lib_transaction.php'); + + $bouns_sn = isset($_POST['bonus_sn']) ? intval($_POST['bonus_sn']) : ''; + + if (add_bonus($user_id, $bouns_sn)) + { + show_message($_LANG['add_bonus_sucess'], $_LANG['back_up_page'], 'user.php?act=bonus', 'info'); + } + else + { + $err->show($_LANG['back_up_page'], 'user.php?act=bonus'); + } +} + +/* 查看订单列表 */ +elseif ($action == 'order_list') +{ + include_once(ROOT_PATH . 'includes/lib_transaction.php'); + + $page = isset($_REQUEST['page']) ? intval($_REQUEST['page']) : 1; + + $record_count = $db->getOne("SELECT COUNT(*) FROM " .$ecs->table('order_info'). " WHERE user_id = '$user_id'"); + + $pager = get_pager('user.php', array('act' => $action), $record_count, $page); + + $orders = get_user_orders($user_id, $pager['size'], $pager['start']); + $merge = get_user_merge($user_id); + + $smarty->assign('merge', $merge); + $smarty->assign('pager', $pager); + $smarty->assign('orders', $orders); + $smarty->display('user_transaction.dwt'); +} + +/* 查看订单详情 */ +elseif ($action == 'order_detail') +{ + include_once(ROOT_PATH . 'includes/lib_transaction.php'); + include_once(ROOT_PATH . 'includes/lib_payment.php'); + include_once(ROOT_PATH . 'includes/lib_order.php'); + include_once(ROOT_PATH . 'includes/lib_clips.php'); + + $order_id = isset($_GET['order_id']) ? intval($_GET['order_id']) : 0; + + /* 订单详情 */ + $order = get_order_detail($order_id, $user_id); + + if ($order === false) + { + $err->show($_LANG['back_home_lnk'], './'); + + exit; + } + + /* 是否显示添加到购物车 */ + if ($order['extension_code'] != 'group_buy' && $order['extension_code'] != 'exchange_goods') + { + $smarty->assign('allow_to_cart', 1); + } + + /* 订单商品 */ + $goods_list = order_goods($order_id); + foreach ($goods_list AS $key => $value) + { + $goods_list[$key]['market_price'] = price_format($value['market_price'], false); + $goods_list[$key]['goods_price'] = price_format($value['goods_price'], false); + $goods_list[$key]['subtotal'] = price_format($value['subtotal'], false); + } + + /* 设置能否修改使用余额数 */ + if ($order['order_amount'] > 0) + { + if ($order['order_status'] == OS_UNCONFIRMED || $order['order_status'] == OS_CONFIRMED) + { + $user = user_info($order['user_id']); + if ($user['user_money'] + $user['credit_line'] > 0) + { + $smarty->assign('allow_edit_surplus', 1); + $smarty->assign('max_surplus', sprintf($_LANG['max_surplus'], $user['user_money'])); + } + } + } + + /* 未发货,未付款时允许更换支付方式 */ + if ($order['order_amount'] > 0 && $order['pay_status'] == PS_UNPAYED && $order['shipping_status'] == SS_UNSHIPPED) + { + $payment_list = available_payment_list(false, 0, true); + + /* 过滤掉当前支付方式和余额支付方式 */ + if(is_array($payment_list)) + { + foreach ($payment_list as $key => $payment) + { + if ($payment['pay_id'] == $order['pay_id'] || $payment['pay_code'] == 'balance') + { + unset($payment_list[$key]); + } + } + } + $smarty->assign('payment_list', $payment_list); + } + + /* 订单 支付 配送 状态语言项 */ + $order['order_status'] = $_LANG['os'][$order['order_status']]; + $order['pay_status'] = $_LANG['ps'][$order['pay_status']]; + $order['shipping_status'] = $_LANG['ss'][$order['shipping_status']]; + + $smarty->assign('order', $order); + $smarty->assign('goods_list', $goods_list); + $smarty->display('user_transaction.dwt'); +} + +/* 取消订单 */ +elseif ($action == 'cancel_order') +{ + include_once(ROOT_PATH . 'includes/lib_transaction.php'); + include_once(ROOT_PATH . 'includes/lib_order.php'); + + $order_id = isset($_GET['order_id']) ? intval($_GET['order_id']) : 0; + + if (cancel_order($order_id, $user_id)) + { + ecs_header("Location: user.php?act=order_list\n"); + exit; + } + else + { + $err->show($_LANG['order_list_lnk'], 'user.php?act=order_list'); + } +} + +/* 收货地址列表界面*/ +elseif ($action == 'address_list') +{ + include_once(ROOT_PATH . 'includes/lib_transaction.php'); + include_once(ROOT_PATH . 'languages/' .$_CFG['lang']. '/shopping_flow.php'); + $smarty->assign('lang', $_LANG); + + /* 取得国家列表、商店所在国家、商店所在国家的省列表 */ + $smarty->assign('country_list', get_regions()); + $smarty->assign('shop_province_list', get_regions(1, $_CFG['shop_country'])); + + /* 获得用户所有的收货人信息 */ + $consignee_list = get_consignee_list($_SESSION['user_id']); + + if (count($consignee_list) < 5 && $_SESSION['user_id'] > 0) + { + /* 如果用户收货人信息的总数小于5 则增加一个新的收货人信息 */ + $consignee_list[] = array('country' => $_CFG['shop_country'], 'email' => isset($_SESSION['email']) ? $_SESSION['email'] : ''); + } + + $smarty->assign('consignee_list', $consignee_list); + + //取得国家列表,如果有收货人列表,取得省市区列表 + foreach ($consignee_list AS $region_id => $consignee) + { + $consignee['country'] = isset($consignee['country']) ? intval($consignee['country']) : 0; + $consignee['province'] = isset($consignee['province']) ? intval($consignee['province']) : 0; + $consignee['city'] = isset($consignee['city']) ? intval($consignee['city']) : 0; + + $province_list[$region_id] = get_regions(1, $consignee['country']); + $city_list[$region_id] = get_regions(2, $consignee['province']); + $district_list[$region_id] = get_regions(3, $consignee['city']); + } + + /* 获取默认收货ID */ + $address_id = $db->getOne("SELECT address_id FROM " .$ecs->table('users'). " WHERE user_id='$user_id'"); + + //赋值于模板 + $smarty->assign('real_goods_count', 1); + $smarty->assign('shop_country', $_CFG['shop_country']); + $smarty->assign('shop_province', get_regions(1, $_CFG['shop_country'])); + $smarty->assign('province_list', $province_list); + $smarty->assign('address', $address_id); + $smarty->assign('city_list', $city_list); + $smarty->assign('district_list', $district_list); + $smarty->assign('currency_format', $_CFG['currency_format']); + $smarty->assign('integral_scale', $_CFG['integral_scale']); + $smarty->assign('name_of_region', array($_CFG['name_of_region_1'], $_CFG['name_of_region_2'], $_CFG['name_of_region_3'], $_CFG['name_of_region_4'])); + + $smarty->display('user_transaction.dwt'); +} + +/* 添加/编辑收货地址的处理 */ +elseif ($action == 'act_edit_address') +{ + include_once(ROOT_PATH . 'includes/lib_transaction.php'); + include_once(ROOT_PATH . 'languages/' .$_CFG['lang']. '/shopping_flow.php'); + $smarty->assign('lang', $_LANG); + + $address = array( + 'user_id' => $user_id, + 'address_id' => intval($_POST['address_id']), + 'country' => isset($_POST['country']) ? intval($_POST['country']) : 0, + 'province' => isset($_POST['province']) ? intval($_POST['province']) : 0, + 'city' => isset($_POST['city']) ? intval($_POST['city']) : 0, + 'district' => isset($_POST['district']) ? intval($_POST['district']) : 0, + 'address' => isset($_POST['address']) ? trim($_POST['address']) : '', + 'consignee' => isset($_POST['consignee']) ? trim($_POST['consignee']) : '', + 'email' => isset($_POST['email']) ? trim($_POST['email']) : '', + 'tel' => isset($_POST['tel']) ? make_semiangle(trim($_POST['tel'])) : '', + 'mobile' => isset($_POST['mobile']) ? make_semiangle(trim($_POST['mobile'])) : '', + 'best_time' => isset($_POST['best_time']) ? trim($_POST['best_time']) : '', + 'sign_building' => isset($_POST['sign_building']) ? trim($_POST['sign_building']) : '', + 'zipcode' => isset($_POST['zipcode']) ? make_semiangle(trim($_POST['zipcode'])) : '', + ); + + if (update_address($address)) + { + show_message($_LANG['edit_address_success'], $_LANG['address_list_lnk'], 'user.php?act=address_list'); + } +} + +/* 删除收货地址 */ +elseif ($action == 'drop_consignee') +{ + include_once('includes/lib_transaction.php'); + + $consignee_id = intval($_GET['id']); + + if (drop_consignee($consignee_id)) + { + ecs_header("Location: user.php?act=address_list\n"); + exit; + } + else + { + show_message($_LANG['del_address_false']); + } +} + +/* 显示收藏商品列表 */ +elseif ($action == 'collection_list') +{ + include_once(ROOT_PATH . 'includes/lib_clips.php'); + + $page = isset($_REQUEST['page']) ? intval($_REQUEST['page']) : 1; + + $record_count = $db->getOne("SELECT COUNT(*) FROM " .$ecs->table('collect_goods'). + " WHERE user_id='$user_id' ORDER BY add_time DESC"); + + $pager = get_pager('user.php', array('act' => $action), $record_count, $page); + $smarty->assign('pager', $pager); + $smarty->assign('goods_list', get_collection_goods($user_id, $pager['size'], $pager['start'])); + $smarty->assign('url', $ecs->url()); + $lang_list = array( + 'UTF8' => $_LANG['charset']['utf8'], + 'GB2312' => $_LANG['charset']['zh_cn'], + 'BIG5' => $_LANG['charset']['zh_tw'], + ); + $smarty->assign('lang_list', $lang_list); + $smarty->assign('user_id', $user_id); + $smarty->display('user_clips.dwt'); +} + +/* 删除收藏的商品 */ +elseif ($action == 'delete_collection') +{ + include_once(ROOT_PATH . 'includes/lib_clips.php'); + + $collection_id = isset($_GET['collection_id']) ? intval($_GET['collection_id']) : 0; + + if ($collection_id > 0) + { + $db->query('DELETE FROM ' .$ecs->table('collect_goods'). " WHERE rec_id='$collection_id' AND user_id ='$user_id'" ); + } + + ecs_header("Location: user.php?act=collection_list\n"); + exit; +} + +/* 添加关注商品 */ +elseif ($action == 'add_to_attention') +{ + $rec_id = (int)$_GET['rec_id']; + if ($rec_id) + { + $db->query('UPDATE ' .$ecs->table('collect_goods'). "SET is_attention = 1 WHERE rec_id='$rec_id' AND user_id ='$user_id'" ); + } + ecs_header("Location: user.php?act=collection_list\n"); + exit; +} +/* 取消关注商品 */ +elseif ($action == 'del_attention') +{ + $rec_id = (int)$_GET['rec_id']; + if ($rec_id) + { + $db->query('UPDATE ' .$ecs->table('collect_goods'). "SET is_attention = 0 WHERE rec_id='$rec_id' AND user_id ='$user_id'" ); + } + ecs_header("Location: user.php?act=collection_list\n"); + exit; +} +/* 显示留言列表 */ +elseif ($action == 'message_list') +{ + include_once(ROOT_PATH . 'includes/lib_clips.php'); + + $page = isset($_REQUEST['page']) ? intval($_REQUEST['page']) : 1; + + $order_id = empty($_GET['order_id']) ? 0 : intval($_GET['order_id']); + $order_info = array(); + + /* 获取用户留言的数量 */ + if ($order_id) + { + $sql = "SELECT COUNT(*) FROM " .$ecs->table('feedback'). + " WHERE parent_id = 0 AND order_id = '$order_id' AND user_id = '$user_id'"; + $order_info = $db->getRow("SELECT * FROM " . $ecs->table('order_info') . " WHERE order_id = '$order_id' AND user_id = '$user_id'"); + $order_info['url'] = 'user.php?act=order_detail&order_id=' . $order_id; + } + else + { + $sql = "SELECT COUNT(*) FROM " .$ecs->table('feedback'). + " WHERE parent_id = 0 AND user_id = '$user_id' AND user_name = '" . $_SESSION['user_name'] . "' AND order_id=0"; + } + + $record_count = $db->getOne($sql); + $act = array('act' => $action); + + if ($order_id != '') + { + $act['order_id'] = $order_id; + } + + $pager = get_pager('user.php', $act, $record_count, $page, 5); + + $smarty->assign('message_list', get_message_list($user_id, $_SESSION['user_name'], $pager['size'], $pager['start'], $order_id)); + $smarty->assign('pager', $pager); + $smarty->assign('order_info', $order_info); + $smarty->display('user_clips.dwt'); +} + +/* 显示评论列表 */ +elseif ($action == 'comment_list') +{ + include_once(ROOT_PATH . 'includes/lib_clips.php'); + + $page = isset($_REQUEST['page']) ? intval($_REQUEST['page']) : 1; + + /* 获取用户留言的数量 */ + $sql = "SELECT COUNT(*) FROM " .$ecs->table('comment'). + " WHERE parent_id = 0 AND user_id = '$user_id'"; + $record_count = $db->getOne($sql); + $pager = get_pager('user.php', array('act' => $action), $record_count, $page, 5); + + $smarty->assign('comment_list', get_comment_list($user_id, $pager['size'], $pager['start'])); + $smarty->assign('pager', $pager); + $smarty->display('user_clips.dwt'); +} + +/* 添加我的留言 */ +elseif ($action == 'act_add_message') +{ + include_once(ROOT_PATH . 'includes/lib_clips.php'); + + $message = array( + 'user_id' => $user_id, + 'user_name' => $_SESSION['user_name'], + 'user_email' => $_SESSION['email'], + 'msg_type' => isset($_POST['msg_type']) ? intval($_POST['msg_type']) : 0, + 'msg_title' => isset($_POST['msg_title']) ? trim($_POST['msg_title']) : '', + 'msg_content' => isset($_POST['msg_content']) ? trim($_POST['msg_content']) : '', + 'order_id'=>empty($_POST['order_id']) ? 0 : intval($_POST['order_id']), + 'upload' => (isset($_FILES['message_img']['error']) && $_FILES['message_img']['error'] == 0) || (!isset($_FILES['message_img']['error']) && isset($_FILES['message_img']['tmp_name']) && $_FILES['message_img']['tmp_name'] != 'none') + ? $_FILES['message_img'] : array() + ); + + if (add_message($message)) + { + show_message($_LANG['add_message_success'], $_LANG['message_list_lnk'], 'user.php?act=message_list&order_id=' . $message['order_id'],'info'); + } + else + { + $err->show($_LANG['message_list_lnk'], 'user.php?act=message_list'); + } +} + +/* 标签云列表 */ +elseif ($action == 'tag_list') +{ + include_once(ROOT_PATH . 'includes/lib_clips.php'); + + $good_id = isset($_GET['id']) ? intval($_GET['id']) : 0; + + $smarty->assign('tags', get_user_tags($user_id)); + $smarty->assign('tags_from', 'user'); + $smarty->display('user_clips.dwt'); +} + +/* 删除标签云的处理 */ +elseif ($action == 'act_del_tag') +{ + include_once(ROOT_PATH . 'includes/lib_clips.php'); + + $tag_words = isset($_GET['tag_words']) ? trim($_GET['tag_words']) : ''; + delete_tag($tag_words, $user_id); + + ecs_header("Location: user.php?act=tag_list\n"); + exit; + +} + +/* 显示缺货登记列表 */ +elseif ($action == 'booking_list') +{ + include_once(ROOT_PATH . 'includes/lib_clips.php'); + + $page = isset($_REQUEST['page']) ? intval($_REQUEST['page']) : 1; + + /* 获取缺货登记的数量 */ + $sql = "SELECT COUNT(*) " . + "FROM " .$ecs->table('booking_goods'). " AS bg, " . + $ecs->table('goods') . " AS g " . + "WHERE bg.goods_id = g.goods_id AND user_id = '$user_id'"; + $record_count = $db->getOne($sql); + $pager = get_pager('user.php', array('act' => $action), $record_count, $page); + + $smarty->assign('booking_list', get_booking_list($user_id, $pager['size'], $pager['start'])); + $smarty->assign('pager', $pager); + $smarty->display('user_clips.dwt'); +} +/* 添加缺货登记页面 */ +elseif ($action == 'add_booking') +{ + include_once(ROOT_PATH . 'includes/lib_clips.php'); + + $goods_id = isset($_GET['id']) ? intval($_GET['id']) : 0; + if ($goods_id == 0) + { + show_message($_LANG['no_goods_id'], $_LANG['back_page_up'], '', 'error'); + } + + /* 根据规格属性获取货品规格信息 */ + $goods_attr = ''; + if ($_GET['spec'] != '') + { + $goods_attr_id = $_GET['spec']; + + $attr_list = array(); + $sql = "SELECT a.attr_name, g.attr_value " . + "FROM " . $ecs->table('goods_attr') . " AS g, " . + $ecs->table('attribute') . " AS a " . + "WHERE g.attr_id = a.attr_id " . + "AND g.goods_attr_id " . db_create_in($goods_attr_id); + $res = $db->query($sql); + while ($row = $db->fetchRow($res)) + { + $attr_list[] = $row['attr_name'] . ': ' . $row['attr_value']; + } + $goods_attr = join(chr(13) . chr(10), $attr_list); + } + $smarty->assign('goods_attr', $goods_attr); + + $smarty->assign('info', get_goodsinfo($goods_id)); + $smarty->display('user_clips.dwt'); + +} + +/* 添加缺货登记的处理 */ +elseif ($action == 'act_add_booking') +{ + include_once(ROOT_PATH . 'includes/lib_clips.php'); + + $booking = array( + 'goods_id' => isset($_POST['id']) ? intval($_POST['id']) : 0, + 'goods_amount' => isset($_POST['number']) ? intval($_POST['number']) : 0, + 'desc' => isset($_POST['desc']) ? trim($_POST['desc']) : '', + 'linkman' => isset($_POST['linkman']) ? trim($_POST['linkman']) : '', + 'email' => isset($_POST['email']) ? trim($_POST['email']) : '', + 'tel' => isset($_POST['tel']) ? trim($_POST['tel']) : '', + 'booking_id' => isset($_POST['rec_id']) ? intval($_POST['rec_id']) : 0 + ); + + // 查看此商品是否已经登记过 + $rec_id = get_booking_rec($user_id, $booking['goods_id']); + if ($rec_id > 0) + { + show_message($_LANG['booking_rec_exist'], $_LANG['back_page_up'], '', 'error'); + } + + if (add_booking($booking)) + { + show_message($_LANG['booking_success'], $_LANG['back_booking_list'], 'user.php?act=booking_list', + 'info'); + } + else + { + $err->show($_LANG['booking_list_lnk'], 'user.php?act=booking_list'); + } +} + +/* 删除缺货登记 */ +elseif ($action == 'act_del_booking') +{ + include_once(ROOT_PATH . 'includes/lib_clips.php'); + + $id = isset($_GET['id']) ? intval($_GET['id']) : 0; + if ($id == 0 || $user_id == 0) + { + ecs_header("Location: user.php?act=booking_list\n"); + exit; + } + + $result = delete_booking($id, $user_id); + if ($result) + { + ecs_header("Location: user.php?act=booking_list\n"); + exit; + } +} + +/* 确认收货 */ +elseif ($action == 'affirm_received') +{ + include_once(ROOT_PATH . 'includes/lib_transaction.php'); + + $order_id = isset($_GET['order_id']) ? intval($_GET['order_id']) : 0; + + if (affirm_received($order_id, $user_id)) + { + ecs_header("Location: user.php?act=order_list\n"); + exit; + } + else + { + $err->show($_LANG['order_list_lnk'], 'user.php?act=order_list'); + } +} + +/* 会员退款申请界面 */ +elseif ($action == 'account_raply') +{ + $smarty->display('user_transaction.dwt'); +} + +/* 会员预付款界面 */ +elseif ($action == 'account_deposit') +{ + include_once(ROOT_PATH . 'includes/lib_clips.php'); + + $surplus_id = isset($_GET['id']) ? intval($_GET['id']) : 0; + $account = get_surplus_info($surplus_id); + + $smarty->assign('payment', get_online_payment_list(false)); + $smarty->assign('order', $account); + $smarty->display('user_transaction.dwt'); +} + +/* 会员账目明细界面 */ +elseif ($action == 'account_detail') +{ + include_once(ROOT_PATH . 'includes/lib_clips.php'); + + $page = isset($_REQUEST['page']) ? intval($_REQUEST['page']) : 1; + + $account_type = 'user_money'; + + /* 获取记录条数 */ + $sql = "SELECT COUNT(*) FROM " .$ecs->table('account_log'). + " WHERE user_id = '$user_id'" . + " AND $account_type <> 0 "; + $record_count = $db->getOne($sql); + + //分页函数 + $pager = get_pager('user.php', array('act' => $action), $record_count, $page); + + //获取剩余余额 + $surplus_amount = get_user_surplus($user_id); + if (empty($surplus_amount)) + { + $surplus_amount = 0; + } + + //获取余额记录 + $account_log = array(); + $sql = "SELECT * FROM " . $ecs->table('account_log') . + " WHERE user_id = '$user_id'" . + " AND $account_type <> 0 " . + " ORDER BY log_id DESC"; + $res = $GLOBALS['db']->selectLimit($sql, $pager['size'], $pager['start']); + while ($row = $db->fetchRow($res)) + { + $row['change_time'] = local_date($_CFG['date_format'], $row['change_time']); + $row['type'] = $row[$account_type] > 0 ? $_LANG['account_inc'] : $_LANG['account_dec']; + $row['user_money'] = price_format(abs($row['user_money']), false); + $row['frozen_money'] = price_format(abs($row['frozen_money']), false); + $row['rank_points'] = abs($row['rank_points']); + $row['pay_points'] = abs($row['pay_points']); + $row['short_change_desc'] = sub_str($row['change_desc'], 60); + $row['amount'] = $row[$account_type]; + $account_log[] = $row; + } + + //模板赋值 + $smarty->assign('surplus_amount', price_format($surplus_amount, false)); + $smarty->assign('account_log', $account_log); + $smarty->assign('pager', $pager); + $smarty->display('user_transaction.dwt'); +} + +/* 会员充值和提现申请记录 */ +elseif ($action == 'account_log') +{ + include_once(ROOT_PATH . 'includes/lib_clips.php'); + + $page = isset($_REQUEST['page']) ? intval($_REQUEST['page']) : 1; + + /* 获取记录条数 */ + $sql = "SELECT COUNT(*) FROM " .$ecs->table('user_account'). + " WHERE user_id = '$user_id'" . + " AND process_type " . db_create_in(array(SURPLUS_SAVE, SURPLUS_RETURN)); + $record_count = $db->getOne($sql); + + //分页函数 + $pager = get_pager('user.php', array('act' => $action), $record_count, $page); + + //获取剩余余额 + $surplus_amount = get_user_surplus($user_id); + if (empty($surplus_amount)) + { + $surplus_amount = 0; + } + + //获取余额记录 + $account_log = get_account_log($user_id, $pager['size'], $pager['start']); + + //模板赋值 + $smarty->assign('surplus_amount', price_format($surplus_amount, false)); + $smarty->assign('account_log', $account_log); + $smarty->assign('pager', $pager); + $smarty->display('user_transaction.dwt'); +} + +/* 对会员余额申请的处理 */ +elseif ($action == 'act_account') +{ + include_once(ROOT_PATH . 'includes/lib_clips.php'); + include_once(ROOT_PATH . 'includes/lib_order.php'); + $amount = isset($_POST['amount']) ? floatval($_POST['amount']) : 0; + if ($amount <= 0) + { + show_message($_LANG['amount_gt_zero']); + } + + /* 变量初始化 */ + $surplus = array( + 'user_id' => $user_id, + 'rec_id' => !empty($_POST['rec_id']) ? intval($_POST['rec_id']) : 0, + 'process_type' => isset($_POST['surplus_type']) ? intval($_POST['surplus_type']) : 0, + 'payment_id' => isset($_POST['payment_id']) ? intval($_POST['payment_id']) : 0, + 'user_note' => isset($_POST['user_note']) ? trim($_POST['user_note']) : '', + 'amount' => $amount + ); + + /* 退款申请的处理 */ + if ($surplus['process_type'] == 1) + { + /* 判断是否有足够的余额的进行退款的操作 */ + $sur_amount = get_user_surplus($user_id); + if ($amount > $sur_amount) + { + $content = $_LANG['surplus_amount_error']; + show_message($content, $_LANG['back_page_up'], '', 'info'); + } + + //插入会员账目明细 + $amount = '-'.$amount; + $surplus['payment'] = ''; + $surplus['rec_id'] = insert_user_account($surplus, $amount); + + /* 如果成功提交 */ + if ($surplus['rec_id'] > 0) + { + $content = $_LANG['surplus_appl_submit']; + show_message($content, $_LANG['back_account_log'], 'user.php?act=account_log', 'info'); + } + else + { + $content = $_LANG['process_false']; + show_message($content, $_LANG['back_page_up'], '', 'info'); + } + } + /* 如果是会员预付款,跳转到下一步,进行线上支付的操作 */ + else + { + if ($surplus['payment_id'] <= 0) + { + show_message($_LANG['select_payment_pls']); + } + + include_once(ROOT_PATH .'includes/lib_payment.php'); + + //获取支付方式名称 + $payment_info = array(); + $payment_info = payment_info($surplus['payment_id']); + $surplus['payment'] = $payment_info['pay_name']; + + if ($surplus['rec_id'] > 0) + { + //更新会员账目明细 + $surplus['rec_id'] = update_user_account($surplus); + } + else + { + //插入会员账目明细 + $surplus['rec_id'] = insert_user_account($surplus, $amount); + } + + //取得支付信息,生成支付代码 + $payment = unserialize_config($payment_info['pay_config']); + + //生成伪订单号, 不足的时候补0 + $order = array(); + $order['order_sn'] = $surplus['rec_id']; + $order['user_name'] = $_SESSION['user_name']; + $order['surplus_amount'] = $amount; + + //计算支付手续费用 + $payment_info['pay_fee'] = pay_fee($surplus['payment_id'], $order['surplus_amount'], 0); + + //计算此次预付款需要支付的总金额 + $order['order_amount'] = $amount + $payment_info['pay_fee']; + + //记录支付log + $order['log_id'] = insert_pay_log($surplus['rec_id'], $order['order_amount'], $type=PAY_SURPLUS, 0); + + /* 调用相应的支付方式文件 */ + include_once(ROOT_PATH . 'includes/modules/payment/' . $payment_info['pay_code'] . '.php'); + + /* 取得在线支付方式的支付按钮 */ + $pay_obj = new $payment_info['pay_code']; + $payment_info['pay_button'] = $pay_obj->get_code($order, $payment); + + /* 模板赋值 */ + $smarty->assign('payment', $payment_info); + $smarty->assign('pay_fee', price_format($payment_info['pay_fee'], false)); + $smarty->assign('amount', price_format($amount, false)); + $smarty->assign('order', $order); + $smarty->display('user_transaction.dwt'); + } +} + +/* 删除会员余额 */ +elseif ($action == 'cancel') +{ + include_once(ROOT_PATH . 'includes/lib_clips.php'); + + $id = isset($_GET['id']) ? intval($_GET['id']) : 0; + if ($id == 0 || $user_id == 0) + { + ecs_header("Location: user.php?act=account_log\n"); + exit; + } + + $result = del_user_account($id, $user_id); + if ($result) + { + ecs_header("Location: user.php?act=account_log\n"); + exit; + } +} + +/* 会员通过帐目明细列表进行再付款的操作 */ +elseif ($action == 'pay') +{ + include_once(ROOT_PATH . 'includes/lib_clips.php'); + include_once(ROOT_PATH . 'includes/lib_payment.php'); + include_once(ROOT_PATH . 'includes/lib_order.php'); + + //变量初始化 + $surplus_id = isset($_GET['id']) ? intval($_GET['id']) : 0; + $payment_id = isset($_GET['pid']) ? intval($_GET['pid']) : 0; + + if ($surplus_id == 0) + { + ecs_header("Location: user.php?act=account_log\n"); + exit; + } + + //如果原来的支付方式已禁用或者已删除, 重新选择支付方式 + if ($payment_id == 0) + { + ecs_header("Location: user.php?act=account_deposit&id=".$surplus_id."\n"); + exit; + } + + //获取单条会员帐目信息 + $order = array(); + $order = get_surplus_info($surplus_id); + + //支付方式的信息 + $payment_info = array(); + $payment_info = payment_info($payment_id); + + /* 如果当前支付方式没有被禁用,进行支付的操作 */ + if (!empty($payment_info)) + { + //取得支付信息,生成支付代码 + $payment = unserialize_config($payment_info['pay_config']); + + //生成伪订单号 + $order['order_sn'] = $surplus_id; + + //获取需要支付的log_id + $order['log_id'] = get_paylog_id($surplus_id, $pay_type = PAY_SURPLUS); + + $order['user_name'] = $_SESSION['user_name']; + $order['surplus_amount'] = $order['amount']; + + //计算支付手续费用 + $payment_info['pay_fee'] = pay_fee($payment_id, $order['surplus_amount'], 0); + + //计算此次预付款需要支付的总金额 + $order['order_amount'] = $order['surplus_amount'] + $payment_info['pay_fee']; + + //如果支付费用改变了,也要相应的更改pay_log表的order_amount + $order_amount = $db->getOne("SELECT order_amount FROM " .$ecs->table('pay_log')." WHERE log_id = '$order[log_id]'"); + if ($order_amount <> $order['order_amount']) + { + $db->query("UPDATE " .$ecs->table('pay_log'). + " SET order_amount = '$order[order_amount]' WHERE log_id = '$order[log_id]'"); + } + + /* 调用相应的支付方式文件 */ + include_once(ROOT_PATH . 'includes/modules/payment/' . $payment_info['pay_code'] . '.php'); + + /* 取得在线支付方式的支付按钮 */ + $pay_obj = new $payment_info['pay_code']; + $payment_info['pay_button'] = $pay_obj->get_code($order, $payment); + + /* 模板赋值 */ + $smarty->assign('payment', $payment_info); + $smarty->assign('order', $order); + $smarty->assign('pay_fee', price_format($payment_info['pay_fee'], false)); + $smarty->assign('amount', price_format($order['surplus_amount'], false)); + $smarty->assign('action', 'act_account'); + $smarty->display('user_transaction.dwt'); + } + /* 重新选择支付方式 */ + else + { + include_once(ROOT_PATH . 'includes/lib_clips.php'); + + $smarty->assign('payment', get_online_payment_list()); + $smarty->assign('order', $order); + $smarty->assign('action', 'account_deposit'); + $smarty->display('user_transaction.dwt'); + } +} + +/* 添加标签(ajax) */ +elseif ($action == 'add_tag') +{ + include_once('includes/cls_json.php'); + include_once('includes/lib_clips.php'); + + $result = array('error' => 0, 'message' => '', 'content' => ''); + $id = isset($_POST['id']) ? intval($_POST['id']) : 0; + $tag = isset($_POST['tag']) ? json_str_iconv(trim($_POST['tag'])) : ''; + + if ($user_id == 0) + { + /* 用户没有登录 */ + $result['error'] = 1; + $result['message'] = $_LANG['tag_anonymous']; + } + else + { + add_tag($id, $tag); // 添加tag + clear_cache_files('goods'); // 删除缓存 + + /* 重新获得该商品的所有缓存 */ + $arr = get_tags($id); + + foreach ($arr AS $row) + { + $result['content'][] = array('word' => htmlspecialchars($row['tag_words']), 'count' => $row['tag_count']); + } + } + + $json = new JSON; + + echo $json->encode($result); + exit; +} + +/* 添加收藏商品(ajax) */ +elseif ($action == 'collect') +{ + include_once(ROOT_PATH .'includes/cls_json.php'); + $json = new JSON(); + $result = array('error' => 0, 'message' => ''); + $goods_id = $_GET['id']; + + if (!isset($_SESSION['user_id']) || $_SESSION['user_id'] == 0) + { + $result['error'] = 1; + $result['message'] = $_LANG['login_please']; + die($json->encode($result)); + } + else + { + /* 检查是否已经存在于用户的收藏夹 */ + $sql = "SELECT COUNT(*) FROM " .$GLOBALS['ecs']->table('collect_goods') . + " WHERE user_id='$_SESSION[user_id]' AND goods_id = '$goods_id'"; + if ($GLOBALS['db']->GetOne($sql) > 0) + { + $result['error'] = 1; + $result['message'] = $GLOBALS['_LANG']['collect_existed']; + die($json->encode($result)); + } + else + { + $time = gmtime(); + $sql = "INSERT INTO " .$GLOBALS['ecs']->table('collect_goods'). " (user_id, goods_id, add_time)" . + "VALUES ('$_SESSION[user_id]', '$goods_id', '$time')"; + + if ($GLOBALS['db']->query($sql) === false) + { + $result['error'] = 1; + $result['message'] = $GLOBALS['db']->errorMsg(); + die($json->encode($result)); + } + else + { + $result['error'] = 0; + $result['message'] = $GLOBALS['_LANG']['collect_success']; + die($json->encode($result)); + } + } + } +} + +/* 删除留言 */ +elseif ($action == 'del_msg') +{ + $id = isset($_GET['id']) ? intval($_GET['id']) : 0; + $order_id = empty($_GET['order_id']) ? 0 : intval($_GET['order_id']); + + if ($id > 0) + { + $sql = 'SELECT user_id, message_img FROM ' .$ecs->table('feedback'). " WHERE msg_id = '$id' LIMIT 1"; + $row = $db->getRow($sql); + if ($row && $row['user_id'] == $user_id) + { + /* 验证通过,删除留言,回复,及相应文件 */ + if ($row['message_img']) + { + @unlink(ROOT_PATH . DATA_DIR . '/feedbackimg/'. $row['message_img']); + } + $sql = "DELETE FROM " .$ecs->table('feedback'). " WHERE msg_id = '$id' OR parent_id = '$id'"; + $db->query($sql); + } + } + ecs_header("Location: user.php?act=message_list&order_id=$order_id\n"); + exit; +} + +/* 删除评论 */ +elseif ($action == 'del_cmt') +{ + $id = isset($_GET['id']) ? intval($_GET['id']) : 0; + if ($id > 0) + { + $sql = "DELETE FROM " .$ecs->table('comment'). " WHERE comment_id = '$id' AND user_id = '$user_id'"; + $db->query($sql); + } + ecs_header("Location: user.php?act=comment_list\n"); + exit; +} + +/* 合并订单 */ +elseif ($action == 'merge_order') +{ + include_once(ROOT_PATH .'includes/lib_transaction.php'); + include_once(ROOT_PATH .'includes/lib_order.php'); + $from_order = isset($_POST['from_order']) ? trim($_POST['from_order']) : ''; + $to_order = isset($_POST['to_order']) ? trim($_POST['to_order']) : ''; + if (merge_user_order($from_order, $to_order, $user_id)) + { + show_message($_LANG['merge_order_success'],$_LANG['order_list_lnk'],'user.php?act=order_list', 'info'); + } + else + { + $err->show($_LANG['order_list_lnk']); + } +} +/* 将指定订单中商品添加到购物车 */ +elseif ($action == 'return_to_cart') +{ + include_once(ROOT_PATH .'includes/cls_json.php'); + include_once(ROOT_PATH .'includes/lib_transaction.php'); + $json = new JSON(); + + $result = array('error' => 0, 'message' => '', 'content' => ''); + $order_id = isset($_POST['order_id']) ? intval($_POST['order_id']) : 0; + if ($order_id == 0) + { + $result['error'] = 1; + $result['message'] = $_LANG['order_id_empty']; + die($json->encode($result)); + } + + if ($user_id == 0) + { + /* 用户没有登录 */ + $result['error'] = 1; + $result['message'] = $_LANG['login_please']; + die($json->encode($result)); + } + + /* 检查订单是否属于该用户 */ + $order_user = $db->getOne("SELECT user_id FROM " .$ecs->table('order_info'). " WHERE order_id = '$order_id'"); + if (empty($order_user)) + { + $result['error'] = 1; + $result['message'] = $_LANG['order_exist']; + die($json->encode($result)); + } + else + { + if ($order_user != $user_id) + { + $result['error'] = 1; + $result['message'] = $_LANG['no_priv']; + die($json->encode($result)); + } + } + + $message = return_to_cart($order_id); + + if ($message === true) + { + $result['error'] = 0; + $result['message'] = $_LANG['return_to_cart_success']; + die($json->encode($result)); + } + else + { + $result['error'] = 1; + $result['message'] = $_LANG['order_exist']; + die($json->encode($result)); + } + +} + +/* 编辑使用余额支付的处理 */ +elseif ($action == 'act_edit_surplus') +{ + /* 检查是否登录 */ + if ($_SESSION['user_id'] <= 0) + { + ecs_header("Location: ./\n"); + exit; + } + + /* 检查订单号 */ + $order_id = intval($_POST['order_id']); + if ($order_id <= 0) + { + ecs_header("Location: ./\n"); + exit; + } + + /* 检查余额 */ + $surplus = floatval($_POST['surplus']); + if ($surplus <= 0) + { + $err->add($_LANG['error_surplus_invalid']); + $err->show($_LANG['order_detail'], 'user.php?act=order_detail&order_id=' . $order_id); + } + + include_once(ROOT_PATH . 'includes/lib_order.php'); + + /* 取得订单 */ + $order = order_info($order_id); + if (empty($order)) + { + ecs_header("Location: ./\n"); + exit; + } + + /* 检查订单用户跟当前用户是否一致 */ + if ($_SESSION['user_id'] != $order['user_id']) + { + ecs_header("Location: ./\n"); + exit; + } + + /* 检查订单是否未付款,检查应付款金额是否大于0 */ + if ($order['pay_status'] != PS_UNPAYED || $order['order_amount'] <= 0) + { + $err->add($_LANG['error_order_is_paid']); + $err->show($_LANG['order_detail'], 'user.php?act=order_detail&order_id=' . $order_id); + } + + /* 计算应付款金额(减去支付费用) */ + $order['order_amount'] -= $order['pay_fee']; + + /* 余额是否超过了应付款金额,改为应付款金额 */ + if ($surplus > $order['order_amount']) + { + $surplus = $order['order_amount']; + } + + /* 取得用户信息 */ + $user = user_info($_SESSION['user_id']); + + /* 用户帐户余额是否足够 */ + if ($surplus > $user['user_money'] + $user['credit_line']) + { + $err->add($_LANG['error_surplus_not_enough']); + $err->show($_LANG['order_detail'], 'user.php?act=order_detail&order_id=' . $order_id); + } + + /* 修改订单,重新计算支付费用 */ + $order['surplus'] += $surplus; + $order['order_amount'] -= $surplus; + if ($order['order_amount'] > 0) + { + $cod_fee = 0; + if ($order['shipping_id'] > 0) + { + $regions = array($order['country'], $order['province'], $order['city'], $order['district']); + $shipping = shipping_area_info($order['shipping_id'], $regions); + if ($shipping['support_cod'] == '1') + { + $cod_fee = $shipping['pay_fee']; + } + } + + $pay_fee = 0; + if ($order['pay_id'] > 0) + { + $pay_fee = pay_fee($order['pay_id'], $order['order_amount'], $cod_fee); + } + + $order['pay_fee'] = $pay_fee; + $order['order_amount'] += $pay_fee; + } + + /* 如果全部支付,设为已确认、已付款 */ + if ($order['order_amount'] == 0) + { + if ($order['order_status'] == OS_UNCONFIRMED) + { + $order['order_status'] = OS_CONFIRMED; + $order['confirm_time'] = gmtime(); + } + $order['pay_status'] = PS_PAYED; + $order['pay_time'] = gmtime(); + } + $order = addslashes_deep($order); + update_order($order_id, $order); + + /* 更新用户余额 */ + $change_desc = sprintf($_LANG['pay_order_by_surplus'], $order['order_sn']); + log_account_change($user['user_id'], (-1) * $surplus, 0, 0, 0, $change_desc); + + /* 跳转 */ + ecs_header('Location: user.php?act=order_detail&order_id=' . $order_id . "\n"); + exit; +} + +/* 编辑使用余额支付的处理 */ +elseif ($action == 'act_edit_payment') +{ + /* 检查是否登录 */ + if ($_SESSION['user_id'] <= 0) + { + ecs_header("Location: ./\n"); + exit; + } + + /* 检查支付方式 */ + $pay_id = intval($_POST['pay_id']); + if ($pay_id <= 0) + { + ecs_header("Location: ./\n"); + exit; + } + + include_once(ROOT_PATH . 'includes/lib_order.php'); + $payment_info = payment_info($pay_id); + if (empty($payment_info)) + { + ecs_header("Location: ./\n"); + exit; + } + + /* 检查订单号 */ + $order_id = intval($_POST['order_id']); + if ($order_id <= 0) + { + ecs_header("Location: ./\n"); + exit; + } + + /* 取得订单 */ + $order = order_info($order_id); + if (empty($order)) + { + ecs_header("Location: ./\n"); + exit; + } + + /* 检查订单用户跟当前用户是否一致 */ + if ($_SESSION['user_id'] != $order['user_id']) + { + ecs_header("Location: ./\n"); + exit; + } + + /* 检查订单是否未付款和未发货 以及订单金额是否为0 和支付id是否为改变*/ + if ($order['pay_status'] != PS_UNPAYED || $order['shipping_status'] != SS_UNSHIPPED || $order['goods_amount'] <= 0 || $order['pay_id'] == $pay_id) + { + ecs_header("Location: user.php?act=order_detail&order_id=$order_id\n"); + exit; + } + + $order_amount = $order['order_amount'] - $order['pay_fee']; + $pay_fee = pay_fee($pay_id, $order_amount); + $order_amount += $pay_fee; + + $sql = "UPDATE " . $ecs->table('order_info') . + " SET pay_id='$pay_id', pay_name='$payment_info[pay_name]', pay_fee='$pay_fee', order_amount='$order_amount'". + " WHERE order_id = '$order_id'"; + $db->query($sql); + + /* 跳转 */ + ecs_header("Location: user.php?act=order_detail&order_id=$order_id\n"); + exit; +} + +/* 保存订单详情收货地址 */ +elseif ($action == 'save_order_address') +{ + include_once(ROOT_PATH .'includes/lib_transaction.php'); + + $address = array( + 'consignee' => isset($_POST['consignee']) ? trim($_POST['consignee']) : '', + 'email' => isset($_POST['email']) ? trim($_POST['email']) : '', + 'address' => isset($_POST['address']) ? trim($_POST['address']) : '', + 'zipcode' => isset($_POST['zipcode']) ? make_semiangle(trim($_POST['zipcode'])) : '', + 'tel' => isset($_POST['tel']) ? trim($_POST['tel']) : '', + 'mobile' => isset($_POST['mobile']) ? trim($_POST['mobile']) : '', + 'sign_building' => isset($_POST['sign_building']) ? trim($_POST['sign_building']) : '', + 'best_time' => isset($_POST['best_time']) ? trim($_POST['best_time']) : '', + 'order_id' => isset($_POST['order_id']) ? intval($_POST['order_id']) : 0 + ); + if (save_order_address($address, $user_id)) + { + ecs_header('Location: user.php?act=order_detail&order_id=' .$address['order_id']. "\n"); + exit; + } + else + { + $err->show($_LANG['order_list_lnk'], 'user.php?act=order_list'); + } +} + +/* 我的红包列表 */ +elseif ($action == 'bonus') +{ + include_once(ROOT_PATH .'includes/lib_transaction.php'); + + $page = isset($_REQUEST['page']) ? intval($_REQUEST['page']) : 1; + $record_count = $db->getOne("SELECT COUNT(*) FROM " .$ecs->table('user_bonus'). " WHERE user_id = '$user_id'"); + + $pager = get_pager('user.php', array('act' => $action), $record_count, $page); + $bonus = get_user_bouns_list($user_id, $pager['size'], $pager['start']); + + $smarty->assign('pager', $pager); + $smarty->assign('bonus', $bonus); + $smarty->display('user_transaction.dwt'); +} + +/* 我的团购列表 */ +elseif ($action == 'group_buy') +{ + include_once(ROOT_PATH .'includes/lib_transaction.php'); + + //待议 + $smarty->display('user_transaction.dwt'); +} + +/* 团购订单详情 */ +elseif ($action == 'group_buy_detail') +{ + include_once(ROOT_PATH .'includes/lib_transaction.php'); + + //待议 + $smarty->display('user_transaction.dwt'); +} + +// 用户推荐页面 +elseif ($action == 'affiliate') +{ + $goodsid = intval(isset($_REQUEST['goodsid']) ? $_REQUEST['goodsid'] : 0); + if(empty($goodsid)) + { + //我的推荐页面 + + $page = !empty($_REQUEST['page']) && intval($_REQUEST['page']) > 0 ? intval($_REQUEST['page']) : 1; + $size = !empty($_CFG['page_size']) && intval($_CFG['page_size']) > 0 ? intval($_CFG['page_size']) : 10; + + empty($affiliate) && $affiliate = array(); + + if(empty($affiliate['config']['separate_by'])) + { + //推荐注册分成 + $affdb = array(); + $num = count($affiliate['item']); + $up_uid = "'$user_id'"; + $all_uid = "'$user_id'"; + for ($i = 1 ; $i <=$num ;$i++) + { + $count = 0; + if ($up_uid) + { + $sql = "SELECT user_id FROM " . $ecs->table('users') . " WHERE parent_id IN($up_uid)"; + $query = $db->query($sql); + $up_uid = ''; + while ($rt = $db->fetch_array($query)) + { + $up_uid .= $up_uid ? ",'$rt[user_id]'" : "'$rt[user_id]'"; + if($i < $num) + { + $all_uid .= ", '$rt[user_id]'"; + } + $count++; + } + } + $affdb[$i]['num'] = $count; + $affdb[$i]['point'] = $affiliate['item'][$i-1]['level_point']; + $affdb[$i]['money'] = $affiliate['item'][$i-1]['level_money']; + } + $smarty->assign('affdb', $affdb); + + $sqlcount = "SELECT count(*) FROM " . $ecs->table('order_info') . " o". + " LEFT JOIN".$ecs->table('users')." u ON o.user_id = u.user_id". + " LEFT JOIN " . $ecs->table('affiliate_log') . " a ON o.order_id = a.order_id" . + " WHERE o.user_id > 0 AND (u.parent_id IN ($all_uid) AND o.is_separate = 0 OR a.user_id = '$user_id' AND o.is_separate > 0)"; + + $sql = "SELECT o.*, a.log_id, a.user_id as suid, a.user_name as auser, a.money, a.point, a.separate_type FROM " . $ecs->table('order_info') . " o". + " LEFT JOIN".$ecs->table('users')." u ON o.user_id = u.user_id". + " LEFT JOIN " . $ecs->table('affiliate_log') . " a ON o.order_id = a.order_id" . + " WHERE o.user_id > 0 AND (u.parent_id IN ($all_uid) AND o.is_separate = 0 OR a.user_id = '$user_id' AND o.is_separate > 0)". + " ORDER BY order_id DESC" ; + + /* + SQL解释: + + 订单、用户、分成记录关联 + 一个订单可能有多个分成记录 + + 1、订单有效 o.user_id > 0 + 2、满足以下之一: + a.直接下线的未分成订单 u.parent_id IN ($all_uid) AND o.is_separate = 0 + 其中$all_uid为该ID及其下线(不包含最后一层下线) + b.全部已分成订单 a.user_id = '$user_id' AND o.is_separate > 0 + + */ + + $affiliate_intro = nl2br(sprintf($_LANG['affiliate_intro'][$affiliate['config']['separate_by']], $affiliate['config']['expire'], $_LANG['expire_unit'][$affiliate['config']['expire_unit']], $affiliate['config']['level_register_all'], $affiliate['config']['level_register_up'], $affiliate['config']['level_money_all'], $affiliate['config']['level_point_all'])); + } + else + { + //推荐订单分成 + $sqlcount = "SELECT count(*) FROM " . $ecs->table('order_info') . " o". + " LEFT JOIN".$ecs->table('users')." u ON o.user_id = u.user_id". + " LEFT JOIN " . $ecs->table('affiliate_log') . " a ON o.order_id = a.order_id" . + " WHERE o.user_id > 0 AND (o.parent_id = '$user_id' AND o.is_separate = 0 OR a.user_id = '$user_id' AND o.is_separate > 0)"; + + + $sql = "SELECT o.*, a.log_id,a.user_id as suid, a.user_name as auser, a.money, a.point, a.separate_type,u.parent_id as up FROM " . $ecs->table('order_info') . " o". + " LEFT JOIN".$ecs->table('users')." u ON o.user_id = u.user_id". + " LEFT JOIN " . $ecs->table('affiliate_log') . " a ON o.order_id = a.order_id" . + " WHERE o.user_id > 0 AND (o.parent_id = '$user_id' AND o.is_separate = 0 OR a.user_id = '$user_id' AND o.is_separate > 0)" . + " ORDER BY order_id DESC" ; + + /* + SQL解释: + + 订单、用户、分成记录关联 + 一个订单可能有多个分成记录 + + 1、订单有效 o.user_id > 0 + 2、满足以下之一: + a.订单下线的未分成订单 o.parent_id = '$user_id' AND o.is_separate = 0 + b.全部已分成订单 a.user_id = '$user_id' AND o.is_separate > 0 + + */ + + $affiliate_intro = nl2br(sprintf($_LANG['affiliate_intro'][$affiliate['config']['separate_by']], $affiliate['config']['expire'], $_LANG['expire_unit'][$affiliate['config']['expire_unit']], $affiliate['config']['level_money_all'], $affiliate['config']['level_point_all'])); + + } + + $count = $db->getOne($sqlcount); + + $max_page = ($count> 0) ? ceil($count / $size) : 1; + if ($page > $max_page) + { + $page = $max_page; + } + + $res = $db->SelectLimit($sql, $size, ($page - 1) * $size); + $logdb = array(); + while ($rt = $GLOBALS['db']->fetchRow($res)) + { + if(!empty($rt['suid'])) + { + //在affiliate_log有记录 + if($rt['separate_type'] == -1 || $rt['separate_type'] == -2) + { + //已被撤销 + $rt['is_separate'] = 3; + } + } + $rt['order_sn'] = substr($rt['order_sn'], 0, strlen($rt['order_sn']) - 5) . "***" . substr($rt['order_sn'], -2, 2); + $logdb[] = $rt; + } + + $url_format = "user.php?act=affiliate&page="; + + $pager = array( + 'page' => $page, + 'size' => $size, + 'sort' => '', + 'order' => '', + 'record_count' => $count, + 'page_count' => $max_page, + 'page_first' => $url_format. '1', + 'page_prev' => $page > 1 ? $url_format.($page - 1) : "javascript:;", + 'page_next' => $page < $max_page ? $url_format.($page + 1) : "javascript:;", + 'page_last' => $url_format. $max_page, + 'array' => array() + ); + for ($i = 1; $i <= $max_page; $i++) + { + $pager['array'][$i] = $i; + } + + $smarty->assign('url_format', $url_format); + $smarty->assign('pager', $pager); + + + $smarty->assign('affiliate_intro', $affiliate_intro); + $smarty->assign('affiliate_type', $affiliate['config']['separate_by']); + + $smarty->assign('logdb', $logdb); + } + else + { + //单个商品推荐 + $smarty->assign('userid', $user_id); + $smarty->assign('goodsid', $goodsid); + + $types = array(1,2,3,4,5); + $smarty->assign('types', $types); + + $goods = get_goods_info($goodsid); + $shopurl = $ecs->url(); + $goods['goods_img'] = (strpos($goods['goods_img'], 'http://') === false && strpos($goods['goods_img'], 'https://') === false) ? $shopurl . $goods['goods_img'] : $goods['goods_img']; + $goods['goods_thumb'] = (strpos($goods['goods_thumb'], 'http://') === false && strpos($goods['goods_thumb'], 'https://') === false) ? $shopurl . $goods['goods_thumb'] : $goods['goods_thumb']; + $goods['shop_price'] = price_format($goods['shop_price']); + + $smarty->assign('goods', $goods); + } + + $smarty->assign('shopname', $_CFG['shop_name']); + $smarty->assign('userid', $user_id); + $smarty->assign('shopurl', $ecs->url()); + $smarty->assign('logosrc', 'themes/' . $_CFG['template'] . '/images/logo.gif'); + + $smarty->display('user_clips.dwt'); +} + +//首页邮件订阅ajax操做和验证操作 +elseif ($action =='email_list') +{ + $job = $_GET['job']; + + if($job == 'add' || $job == 'del') + { + if(isset($_SESSION['last_email_query'])) + { + if(time() - $_SESSION['last_email_query'] <= 30) + { + die($_LANG['order_query_toofast']); + } + } + $_SESSION['last_email_query'] = time(); + } + + $email = trim($_GET['email']); + $email = htmlspecialchars($email); + + if (!is_email($email)) + { + $info = sprintf($_LANG['email_invalid'], $email); + die($info); + } + $ck = $db->getRow("SELECT * FROM " . $ecs->table('email_list') . " WHERE email = '$email'"); + if ($job == 'add') + { + if (empty($ck)) + { + $hash = substr(md5(time()), 1, 10); + $sql = "INSERT INTO " . $ecs->table('email_list') . " (email, stat, hash) VALUES ('$email', 0, '$hash')"; + $db->query($sql); + $info = $_LANG['email_check']; + $url = $ecs->url() . "user.php?act=email_list&job=add_check&hash=$hash&email=$email"; + send_mail('', $email, $_LANG['check_mail'], sprintf($_LANG['check_mail_content'], $email, $_CFG['shop_name'], $url, $url, $_CFG['shop_name'], local_date('Y-m-d')), 1); + } + elseif ($ck['stat'] == 1) + { + $info = sprintf($_LANG['email_alreadyin_list'], $email); + } + else + { + $hash = substr(md5(time()),1 , 10); + $sql = "UPDATE " . $ecs->table('email_list') . "SET hash = '$hash' WHERE email = '$email'"; + $db->query($sql); + $info = $_LANG['email_re_check']; + $url = $ecs->url() . "user.php?act=email_list&job=add_check&hash=$hash&email=$email"; + send_mail('', $email, $_LANG['check_mail'], sprintf($_LANG['check_mail_content'], $email, $_CFG['shop_name'], $url, $url, $_CFG['shop_name'], local_date('Y-m-d')), 1); + } + die($info); + } + elseif ($job == 'del') + { + if (empty($ck)) + { + $info = sprintf($_LANG['email_notin_list'], $email); + } + elseif ($ck['stat'] == 1) + { + $hash = substr(md5(time()),1,10); + $sql = "UPDATE " . $ecs->table('email_list') . "SET hash = '$hash' WHERE email = '$email'"; + $db->query($sql); + $info = $_LANG['email_check']; + $url = $ecs->url() . "user.php?act=email_list&job=del_check&hash=$hash&email=$email"; + send_mail('', $email, $_LANG['check_mail'], sprintf($_LANG['check_mail_content'], $email, $_CFG['shop_name'], $url, $url, $_CFG['shop_name'], local_date('Y-m-d')), 1); + } + else + { + $info = $_LANG['email_not_alive']; + } + die($info); + } + elseif ($job == 'add_check') + { + if (empty($ck)) + { + $info = sprintf($_LANG['email_notin_list'], $email); + } + elseif ($ck['stat'] == 1) + { + $info = $_LANG['email_checked']; + } + else + { + if ($_GET['hash'] == $ck['hash']) + { + $sql = "UPDATE " . $ecs->table('email_list') . "SET stat = 1 WHERE email = '$email'"; + $db->query($sql); + $info = $_LANG['email_checked']; + } + else + { + $info = $_LANG['hash_wrong']; + } + } + show_message($info, $_LANG['back_home_lnk'], 'index.php'); + } + elseif ($job == 'del_check') + { + if (empty($ck)) + { + $info = sprintf($_LANG['email_invalid'], $email); + } + elseif ($ck['stat'] == 1) + { + if ($_GET['hash'] == $ck['hash']) + { + $sql = "DELETE FROM " . $ecs->table('email_list') . "WHERE email = '$email'"; + $db->query($sql); + $info = $_LANG['email_canceled']; + } + else + { + $info = $_LANG['hash_wrong']; + } + } + else + { + $info = $_LANG['email_not_alive']; + } + show_message($info, $_LANG['back_home_lnk'], 'index.php'); + } +} + +/* ajax 发送验证邮件 */ +elseif ($action == 'send_hash_mail') +{ + include_once(ROOT_PATH .'includes/cls_json.php'); + include_once(ROOT_PATH .'includes/lib_passport.php'); + $json = new JSON(); + + $result = array('error' => 0, 'message' => '', 'content' => ''); + + if ($user_id == 0) + { + /* 用户没有登录 */ + $result['error'] = 1; + $result['message'] = $_LANG['login_please']; + die($json->encode($result)); + } + + if (send_regiter_hash($user_id)) + { + /* 用户没有登录 */ + $result['message'] = $_LANG['validate_mail_ok']; + die($json->encode($result)); + } + else + { + $result['error'] = 1; + $result['message'] = $GLOBALS['err']->last_message(); + } + + die($json->encode($result)); +} +else if ($action == 'track_packages') +{ + include_once(ROOT_PATH . 'includes/lib_transaction.php'); + include_once(ROOT_PATH .'includes/lib_order.php'); + + $page = isset($_REQUEST['page']) ? intval($_REQUEST['page']) : 1; + + $orders = array(); + + $sql = "SELECT order_id,order_sn,invoice_no,shipping_id FROM " .$ecs->table('order_info'). + " WHERE user_id = '$user_id' AND shipping_status = '" . SS_SHIPPED . "'"; + $res = $db->query($sql); + $record_count = 0; + while ($item = $db->fetch_array($res)) + { + $shipping = get_shipping_object($item['shipping_id']); + + if (method_exists ($shipping, 'query')) + { + $query_link = $shipping->query($item['invoice_no']); + } + else + { + $query_link = $item['invoice_no']; + } + + if ($query_link != $item['invoice_no']) + { + $item['query_link'] = $query_link; + $orders[] = $item; + $record_count += 1; + } + } + $pager = get_pager('user.php', array('act' => $action), $record_count, $page); + $smarty->assign('pager', $pager); + $smarty->assign('orders', $orders); + $smarty->display('user_transaction.dwt'); +} +else if ($action == 'order_query') +{ + $_GET['order_sn'] = trim(substr($_GET['order_sn'], 1)); + $order_sn = empty($_GET['order_sn']) ? '' : addslashes($_GET['order_sn']); + include_once(ROOT_PATH .'includes/cls_json.php'); + $json = new JSON(); + + $result = array('error'=>0, 'message'=>'', 'content'=>''); + + if(isset($_SESSION['last_order_query'])) + { + if(time() - $_SESSION['last_order_query'] <= 10) + { + $result['error'] = 1; + $result['message'] = $_LANG['order_query_toofast']; + die($json->encode($result)); + } + } + $_SESSION['last_order_query'] = time(); + + if (empty($order_sn)) + { + $result['error'] = 1; + $result['message'] = $_LANG['invalid_order_sn']; + die($json->encode($result)); + } + + $sql = "SELECT order_id, order_status, shipping_status, pay_status, ". + " shipping_time, shipping_id, invoice_no, user_id ". + " FROM " . $ecs->table('order_info'). + " WHERE order_sn = '$order_sn' LIMIT 1"; + + $row = $db->getRow($sql); + if (empty($row)) + { + $result['error'] = 1; + $result['message'] = $_LANG['invalid_order_sn']; + die($json->encode($result)); + } + + $order_query = array(); + $order_query['order_sn'] = $order_sn; + $order_query['order_id'] = $row['order_id']; + $order_query['order_status'] = $_LANG['os'][$row['order_status']] . ',' . $_LANG['ps'][$row['pay_status']] . ',' . $_LANG['ss'][$row['shipping_status']]; + + if ($row['invoice_no'] && $row['shipping_id'] > 0) + { + $sql = "SELECT shipping_code FROM " . $ecs->table('shipping') . " WHERE shipping_id = '$row[shipping_id]'"; + $shipping_code = $db->getOne($sql); + $plugin = ROOT_PATH . 'includes/modules/shipping/' . $shipping_code . '.php'; + if (file_exists($plugin)) + { + include_once($plugin); + $shipping = new $shipping_code; + $order_query['invoice_no'] = $shipping->query((string)$row['invoice_no']); + } + else + { + $order_query['invoice_no'] = (string)$row['invoice_no']; + } + } + + $order_query['user_id'] = $row['user_id']; + /* 如果是匿名用户显示发货时间 */ + if ($row['user_id'] == 0 && $row['shipping_time'] > 0) + { + $order_query['shipping_date'] = local_date($GLOBALS['_CFG']['date_format'], $row['shipping_time']); + } + $smarty->assign('order_query', $order_query); + $result['content'] = $smarty->fetch('library/order_query.lbi'); + die($json->encode($result)); +} +elseif ($action == 'transform_points') +{ + $rule = array(); + if (!empty($_CFG['points_rule'])) + { + $rule = unserialize($_CFG['points_rule']); + } + $cfg = array(); + if (!empty($_CFG['integrate_config'])) + { + $cfg = unserialize($_CFG['integrate_config']); + $_LANG['exchange_points'][0] = empty($cfg['uc_lang']['credits'][0][0])? $_LANG['exchange_points'][0] : $cfg['uc_lang']['credits'][0][0]; + $_LANG['exchange_points'][1] = empty($cfg['uc_lang']['credits'][1][0])? $_LANG['exchange_points'][1] : $cfg['uc_lang']['credits'][1][0]; + } + $sql = "SELECT user_id, user_name, pay_points, rank_points FROM " . $ecs->table('users') . " WHERE user_id='$user_id'"; + $row = $db->getRow($sql); + if ($_CFG['integrate_code'] == 'ucenter') + { + $exchange_type = 'ucenter'; + $to_credits_options = array(); + $out_exchange_allow = array(); + foreach ($rule as $credit) + { + $out_exchange_allow[$credit['appiddesc'] . '|' . $credit['creditdesc'] . '|' . $credit['creditsrc']] = $credit['ratio']; + if (!array_key_exists($credit['appiddesc']. '|' .$credit['creditdesc'], $to_credits_options)) + { + $to_credits_options[$credit['appiddesc']. '|' .$credit['creditdesc']] = $credit['title']; + } + } + $smarty->assign('selected_org', $rule[0]['creditsrc']); + $smarty->assign('selected_dst', $rule[0]['appiddesc']. '|' .$rule[0]['creditdesc']); + $smarty->assign('descreditunit', $rule[0]['unit']); + $smarty->assign('orgcredittitle', $_LANG['exchange_points'][$rule[0]['creditsrc']]); + $smarty->assign('descredittitle', $rule[0]['title']); + $smarty->assign('descreditamount', round((1 / $rule[0]['ratio']), 2)); + $smarty->assign('to_credits_options', $to_credits_options); + $smarty->assign('out_exchange_allow', $out_exchange_allow); + } + else + { + $exchange_type = 'other'; + + $bbs_points_name = $user->get_points_name(); + $total_bbs_points = $user->get_points($row['user_name']); + + /* 论坛积分 */ + $bbs_points = array(); + foreach ($bbs_points_name as $key=>$val) + { + $bbs_points[$key] = array('title'=>$_LANG['bbs'] . $val['title'], 'value'=>$total_bbs_points[$key]); + } + + /* 兑换规则 */ + $rule_list = array(); + foreach ($rule as $key=>$val) + { + $rule_key = substr($key, 0, 1); + $bbs_key = substr($key, 1); + $rule_list[$key]['rate'] = $val; + switch ($rule_key) + { + case TO_P : + $rule_list[$key]['from'] = $_LANG['bbs'] . $bbs_points_name[$bbs_key]['title']; + $rule_list[$key]['to'] = $_LANG['pay_points']; + break; + case TO_R : + $rule_list[$key]['from'] = $_LANG['bbs'] . $bbs_points_name[$bbs_key]['title']; + $rule_list[$key]['to'] = $_LANG['rank_points']; + break; + case FROM_P : + $rule_list[$key]['from'] = $_LANG['pay_points'];$_LANG['bbs'] . $bbs_points_name[$bbs_key]['title']; + $rule_list[$key]['to'] =$_LANG['bbs'] . $bbs_points_name[$bbs_key]['title']; + break; + case FROM_R : + $rule_list[$key]['from'] = $_LANG['rank_points']; + $rule_list[$key]['to'] = $_LANG['bbs'] . $bbs_points_name[$bbs_key]['title']; + break; + } + } + $smarty->assign('bbs_points', $bbs_points); + $smarty->assign('rule_list', $rule_list); + } + $smarty->assign('shop_points', $row); + $smarty->assign('exchange_type', $exchange_type); + $smarty->assign('action', $action); + $smarty->assign('lang', $_LANG); + $smarty->display('user_transaction.dwt'); +} +elseif ($action == 'act_transform_points') +{ + $rule_index = empty($_POST['rule_index']) ? '' : trim($_POST['rule_index']); + $num = empty($_POST['num']) ? 0 : intval($_POST['num']); + + + if ($num <= 0 || $num != floor($num)) + { + show_message($_LANG['invalid_points'], $_LANG['transform_points'], 'user.php?act=transform_points'); + } + + $num = floor($num); //格式化为整数 + + $bbs_key = substr($rule_index, 1); + $rule_key = substr($rule_index, 0, 1); + + $max_num = 0; + + /* 取出用户数据 */ + $sql = "SELECT user_name, user_id, pay_points, rank_points FROM " . $ecs->table('users') . " WHERE user_id='$user_id'"; + $row = $db->getRow($sql); + $bbs_points = $user->get_points($row['user_name']); + $points_name = $user->get_points_name(); + + $rule = array(); + if ($_CFG['points_rule']) + { + $rule = unserialize($_CFG['points_rule']); + } + list($from, $to) = explode(':', $rule[$rule_index]); + + $max_points = 0; + switch ($rule_key) + { + case TO_P : + $max_points = $bbs_points[$bbs_key]; + break; + case TO_R : + $max_points = $bbs_points[$bbs_key]; + break; + case FROM_P : + $max_points = $row['pay_points']; + break; + case FROM_R : + $max_points = $row['rank_points']; + } + + /* 检查积分是否超过最大值 */ + if ($max_points <=0 || $num > $max_points) + { + show_message($_LANG['overflow_points'], $_LANG['transform_points'], 'user.php?act=transform_points' ); + } + + switch ($rule_key) + { + case TO_P : + $result_points = floor($num * $to / $from); + $user->set_points($row['user_name'], array($bbs_key=>0 - $num)); //调整论坛积分 + log_account_change($row['user_id'], 0, 0, 0, $result_points, $_LANG['transform_points'], ACT_OTHER); + show_message(sprintf($_LANG['to_pay_points'], $num, $points_name[$bbs_key]['title'], $result_points), $_LANG['transform_points'], 'user.php?act=transform_points'); + + case TO_R : + $result_points = floor($num * $to / $from); + $user->set_points($row['user_name'], array($bbs_key=>0 - $num)); //调整论坛积分 + log_account_change($row['user_id'], 0, 0, $result_points, 0, $_LANG['transform_points'], ACT_OTHER); + show_message(sprintf($_LANG['to_rank_points'], $num, $points_name[$bbs_key]['title'], $result_points), $_LANG['transform_points'], 'user.php?act=transform_points'); + + case FROM_P : + $result_points = floor($num * $to / $from); + log_account_change($row['user_id'], 0, 0, 0, 0-$num, $_LANG['transform_points'], ACT_OTHER); //调整商城积分 + $user->set_points($row['user_name'], array($bbs_key=>$result_points)); //调整论坛积分 + show_message(sprintf($_LANG['from_pay_points'], $num, $result_points, $points_name[$bbs_key]['title']), $_LANG['transform_points'], 'user.php?act=transform_points'); + + case FROM_R : + $result_points = floor($num * $to / $from); + log_account_change($row['user_id'], 0, 0, 0-$num, 0, $_LANG['transform_points'], ACT_OTHER); //调整商城积分 + $user->set_points($row['user_name'], array($bbs_key=>$result_points)); //调整论坛积分 + show_message(sprintf($_LANG['from_rank_points'], $num, $result_points, $points_name[$bbs_key]['title']), $_LANG['transform_points'], 'user.php?act=transform_points'); + } +} +elseif ($action == 'act_transform_ucenter_points') +{ + $rule = array(); + if ($_CFG['points_rule']) + { + $rule = unserialize($_CFG['points_rule']); + } + $shop_points = array(0 => 'rank_points', 1 => 'pay_points'); + $sql = "SELECT user_id, user_name, pay_points, rank_points FROM " . $ecs->table('users') . " WHERE user_id='$user_id'"; + $row = $db->getRow($sql); + $exchange_amount = intval($_POST['amount']); + $fromcredits = intval($_POST['fromcredits']); + $tocredits = trim($_POST['tocredits']); + $cfg = unserialize($_CFG['integrate_config']); + if (!empty($cfg)) + { + $_LANG['exchange_points'][0] = empty($cfg['uc_lang']['credits'][0][0])? $_LANG['exchange_points'][0] : $cfg['uc_lang']['credits'][0][0]; + $_LANG['exchange_points'][1] = empty($cfg['uc_lang']['credits'][1][0])? $_LANG['exchange_points'][1] : $cfg['uc_lang']['credits'][1][0]; + } + list($appiddesc, $creditdesc) = explode('|', $tocredits); + $ratio = 0; + + if ($exchange_amount <= 0) + { + show_message($_LANG['invalid_points'], $_LANG['transform_points'], 'user.php?act=transform_points'); + } + if ($exchange_amount > $row[$shop_points[$fromcredits]]) + { + show_message($_LANG['overflow_points'], $_LANG['transform_points'], 'user.php?act=transform_points'); + } + foreach ($rule as $credit) + { + if ($credit['appiddesc'] == $appiddesc && $credit['creditdesc'] == $creditdesc && $credit['creditsrc'] == $fromcredits) + { + $ratio = $credit['ratio']; + break; + } + } + if ($ratio == 0) + { + show_message($_LANG['exchange_deny'], $_LANG['transform_points'], 'user.php?act=transform_points'); + } + $netamount = floor($exchange_amount / $ratio); + include_once(ROOT_PATH . './includes/lib_uc.php'); + $result = exchange_points($row['user_id'], $fromcredits, $creditdesc, $appiddesc, $netamount); + if ($result === true) + { + $sql = "UPDATE " . $ecs->table('users') . " SET {$shop_points[$fromcredits]}={$shop_points[$fromcredits]}-'$exchange_amount' WHERE user_id='{$row['user_id']}'"; + $db->query($sql); + $sql = "INSERT INTO " . $ecs->table('account_log') . "(user_id, {$shop_points[$fromcredits]}, change_time, change_desc, change_type)" . " VALUES ('{$row['user_id']}', '-$exchange_amount', '". gmtime() ."', '" . $cfg['uc_lang']['exchange'] . "', '98')"; + $db->query($sql); + show_message(sprintf($_LANG['exchange_success'], $exchange_amount, $_LANG['exchange_points'][$fromcredits], $netamount, $credit['title']), $_LANG['transform_points'], 'user.php?act=transform_points'); + } + else + { + show_message($_LANG['exchange_error_1'], $_LANG['transform_points'], 'user.php?act=transform_points'); + } +} +/* 清除商品浏览历史 */ +elseif ($action == 'clear_history') +{ + setcookie('ECS[history]', '', 1); +} +?> \ No newline at end of file diff --git a/vote.php b/vote.php new file mode 100644 index 0000000..e5282b7 --- /dev/null +++ b/vote.php @@ -0,0 +1,113 @@ + 0, 'message' => '', 'content' => ''); + +$vote_id = intval($_POST['vote']); +$options = trim($_POST['options']); +$type = intval($_POST['type']); +$ip_address = real_ip(); + +if (vote_already_submited($vote_id, $ip_address)) +{ + $res['error'] = 1; + $res['message'] = $_LANG['vote_ip_same']; +} +else +{ + save_vote($vote_id, $ip_address, $options); + + $vote = get_vote($vote_id); + if (!empty($vote)) + { + $smarty->assign('vote_id', $vote['id']); + $smarty->assign('vote', $vote['content']); + } + + $str = $smarty->fetch("library/vote.lbi"); + + $pattern = '/(?:<(\w+)[^>]*> .*?)?(.*)<\/div>(?:.*?<\/\1>)?/is'; + + if (preg_match($pattern, $str, $match)) + { + $res['content'] = $match[2]; + } + $res['message'] = $_LANG['vote_success']; +} + +$json = new JSON; + +echo $json->encode($res); + +/*------------------------------------------------------ */ +//-- PRIVATE FUNCTION +/*------------------------------------------------------ */ + +/** + * 检查是否已经提交过投票 + * + * @access private + * @param integer $vote_id + * @param string $ip_address + * @return boolean + */ +function vote_already_submited($vote_id, $ip_address) +{ + $sql = "SELECT COUNT(*) FROM ".$GLOBALS['ecs']->table('vote_log')." ". + "WHERE ip_address = '$ip_address' AND vote_id = '$vote_id' "; + + return ($GLOBALS['db']->GetOne($sql) > 0); +} + +/** + * 保存投票结果信息 + * + * @access public + * @param integer $vote_id + * @param string $ip_address + * @param string $option_id + * @return void + */ +function save_vote($vote_id, $ip_address, $option_id) +{ + $sql = "INSERT INTO " . $GLOBALS['ecs']->table('vote_log') . " (vote_id, ip_address, vote_time) " . + "VALUES ('$vote_id', '$ip_address', " . gmtime() .")"; + $res = $GLOBALS['db']->query($sql); + + /* 更新投票主题的数量 */ + $sql = "UPDATE " .$GLOBALS['ecs']->table('vote'). " SET ". + "vote_count = vote_count + 1 ". + "WHERE vote_id = '$vote_id'"; + $GLOBALS['db']->query($sql); + + /* 更新投票选项的数量 */ + $sql = "UPDATE " . $GLOBALS['ecs']->table('vote_option') . " SET " . + "option_count = option_count + 1 " . + "WHERE " . db_create_in($option_id, 'option_id'); + $GLOBALS['db']->query($sql); +} + +?> \ No newline at end of file diff --git a/weather.htm b/weather.htm new file mode 100644 index 0000000..55c15fa --- /dev/null +++ b/weather.htm @@ -0,0 +1,122 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/wholesale.php b/wholesale.php new file mode 100644 index 0000000..8c81416 --- /dev/null +++ b/wholesale.php @@ -0,0 +1,593 @@ + + * @version: v2.x + * --------------------------------------------- + * $Author: yehuaixiao $ + * $Id: wholesale.php 17218 2011-01-24 04:10:41Z yehuaixiao $ + */ + +define('IN_ECS', true); + +require(dirname(__FILE__) . '/includes/init.php'); + +/* 如果没登录,提示登录 */ +if ($_SESSION['user_rank'] <= 0) +{ + show_message($_LANG['ws_user_rank'], $_LANG['ws_return_home'], 'index.php'); +} + +/*------------------------------------------------------ */ +//-- act 操作项的初始化 +/*------------------------------------------------------ */ +if (empty($_REQUEST['act'])) +{ + $_REQUEST['act'] = 'list'; +} + +/*------------------------------------------------------ */ +//-- 批发活动列表 +/*------------------------------------------------------ */ +if ($_REQUEST['act'] == 'list') +{ + $search_category = empty($_REQUEST['search_category']) ? 0 : intval($_REQUEST['search_category']); + $search_keywords = isset($_REQUEST['search_keywords']) ? trim($_REQUEST['search_keywords']) : ''; + $param = array(); // 翻页链接所带参数列表 + + /* 查询条件:当前用户的会员等级(搜索关键字) */ + $where = " WHERE g.goods_id = w.goods_id + AND w.enabled = 1 + AND CONCAT(',', w.rank_ids, ',') LIKE '" . '%,' . $_SESSION['user_rank'] . ',%' . "' "; + + /* 搜索 */ + /* 搜索类别 */ + if ($search_category) + { + $where .= " AND g.cat_id = '$search_category' "; + $param['search_category'] = $search_category; + $smarty->assign('search_category', $search_category); + } + /* 搜索商品名称和关键字 */ + if ($search_keywords) + { + $where .= " AND (g.keywords LIKE '%$search_keywords%' + OR g.goods_name LIKE '%$search_keywords%') "; + $param['search_keywords'] = $search_keywords; + $smarty->assign('search_keywords', $search_keywords); + } + + /* 取得批发商品总数 */ + $sql = "SELECT COUNT(*) FROM " . $ecs->table('wholesale') . " AS w, " . $ecs->table('goods') . " AS g " . $where; + $count = $db->getOne($sql); + + if ($count > 0) + { + $default_display_type = $_CFG['show_order_type'] == '0' ? 'list' : 'text'; + $display = (isset($_REQUEST['display']) && in_array(trim(strtolower($_REQUEST['display'])), array('list', 'text'))) ? trim($_REQUEST['display']) : (isset($_COOKIE['ECS']['display']) ? $_COOKIE['ECS']['display'] : $default_display_type); + $display = in_array($display, array('list', 'text')) ? $display : 'text'; + setcookie('ECS[display]', $display, gmtime() + 86400 * 7); + + /* 取得每页记录数 */ + $size = isset($_CFG['page_size']) && intval($_CFG['page_size']) > 0 ? intval($_CFG['page_size']) : 10; + + /* 计算总页数 */ + $page_count = ceil($count / $size); + + /* 取得当前页 */ + $page = isset($_REQUEST['page']) && intval($_REQUEST['page']) > 0 ? intval($_REQUEST['page']) : 1; + $page = $page > $page_count ? $page_count : $page; + + /* 取得当前页的批发商品 */ + $wholesale_list = wholesale_list($size, $page, $where); + $smarty->assign('wholesale_list', $wholesale_list); + + $param['act'] = 'list'; + $pager = get_pager('wholesale.php', array_reverse ($param, TRUE), $count, $page, $size); + $pager['display'] = $display; + $smarty->assign('pager', $pager); + + /* 批发商品购物车 */ + $smarty->assign('cart_goods', isset($_SESSION['wholesale_goods']) ? $_SESSION['wholesale_goods'] : array()); + } + + /* 模板赋值 */ + assign_template(); + $position = assign_ur_here(); + $smarty->assign('page_title', $position['title']); // 页面标题 + $smarty->assign('ur_here', $position['ur_here']); // 当前位置 + $smarty->assign('categories', get_categories_tree()); // 分类树 + $smarty->assign('helps', get_shop_help()); // 网店帮助 + $smarty->assign('top_goods', get_top10()); // 销售排行 + + assign_dynamic('wholesale'); + + /* 显示模板 */ + $smarty->display('wholesale_list.dwt'); +} + +/*------------------------------------------------------ */ +//-- 下载价格单 +/*------------------------------------------------------ */ +elseif ($_REQUEST['act'] == 'price_list') +{ + $data = $_LANG['goods_name'] . "\t" . $_LANG['goods_attr'] . "\t" . $_LANG['number'] . "\t" . $_LANG['ws_price'] . "\t\n"; + $sql = "SELECT * FROM " . $ecs->table('wholesale') . + "WHERE enabled = 1 AND CONCAT(',', rank_ids, ',') LIKE '" . '%,' . $_SESSION['user_rank'] . ',%' . "'"; + $res = $db->query($sql); + while ($row = $db->fetchRow($res)) + { + $price_list = unserialize($row['prices']); + foreach ($price_list as $attr_price) + { + if ($attr_price['attr']) + { + $sql = "SELECT attr_value FROM " . $ecs->table('goods_attr') . + " WHERE goods_attr_id " . db_create_in($attr_price['attr']); + $goods_attr = join(',', $db->getCol($sql)); + } + else + { + $goods_attr = ''; + } + foreach ($attr_price['qp_list'] as $qp) + { + $data .= $row['goods_name'] . "\t" . $goods_attr . "\t" . $qp['quantity'] . "\t" . $qp['price'] . "\t\n"; + } + } + } + + header("Content-type: application/vnd.ms-excel; charset=utf-8"); + header("Content-Disposition: attachment; filename=price_list.xls"); + if (EC_CHARSET == 'utf-8') + { + echo ecs_iconv('UTF8', 'GB2312', $data); + } + else + { + echo $data; + } +} + +/*------------------------------------------------------ */ +//-- 加入购物车 +/*------------------------------------------------------ */ +elseif ($_REQUEST['act'] == 'add_to_cart') +{ + /* 取得参数 */ + $act_id = intval($_POST['act_id']); + $goods_number = $_POST['goods_number'][$act_id]; + $attr_id = isset($_POST['attr_id']) ? $_POST['attr_id'] : array(); + if(isset($attr_id[$act_id])) + { + $goods_attr = $attr_id[$act_id]; + } + + /* 用户提交必须全部通过检查,才能视为完成操作 */ + + /* 检查数量 */ + if (empty($goods_number) || (is_array($goods_number) && array_sum($goods_number) <= 0)) + { + show_message($_LANG['ws_invalid_goods_number']); + } + + /* 确定购买商品列表 */ + $goods_list = array(); + if (is_array($goods_number)) + { + foreach ($goods_number as $key => $value) + { + if (!$value) + { + unset($goods_number[$key], $goods_attr[$key]); + continue; + } + + $goods_list[] = array('number' => $goods_number[$key], 'goods_attr' => $goods_attr[$key]); + } + } + else + { + $goods_list[0] = array('number' => $goods_number, 'goods_attr' => ''); + } + + /* 取批发相关数据 */ + $wholesale = wholesale_info($act_id); + + /* 检查session中该商品,该属性是否存在 */ + if (isset($_SESSION['wholesale_goods'])) + { + foreach ($_SESSION['wholesale_goods'] as $goods) + { + if ($goods['goods_id'] == $wholesale['goods_id']) + { + if (empty($goods_attr)) + { + show_message($_LANG['ws_goods_attr_exists']); + } + elseif (in_array($goods['goods_attr_id'], $goods_attr)) + { + show_message($_LANG['ws_goods_attr_exists']); + } + } + } + } + + /* 获取购买商品的批发方案的价格阶梯 (一个方案多个属性组合、一个属性组合、一个属性、无属性) */ + $attr_matching = false; + foreach ($wholesale['price_list'] as $attr_price) + { + // 没有属性 + if (empty($attr_price['attr'])) + { + $attr_matching = true; + $goods_list[0]['qp_list'] = $attr_price['qp_list']; + break; + } + // 有属性 + elseif (($key = is_attr_matching($goods_list, $attr_price['attr'])) !== false) + { + $attr_matching = true; + $goods_list[$key]['qp_list'] = $attr_price['qp_list']; + } + } + if (!$attr_matching) + { + show_message($_LANG['ws_attr_not_matching']); + } + + /* 检查数量是否达到最低要求 */ + foreach ($goods_list as $goods_key => $goods) + { + if ($goods['number'] < $goods['qp_list'][0]['quantity']) + { + show_message($_LANG['ws_goods_number_not_enough']); + } + else + { + $goods_price = 0; + foreach ($goods['qp_list'] as $qp) + { + if ($goods['number'] >= $qp['quantity']) + { + $goods_list[$goods_key]['goods_price'] = $qp['price']; + } + else + { + break; + } + } + } + } + + /* 写入session */ + foreach ($goods_list as $goods_key => $goods) + { + // 属性名称 + $goods_attr_name = ''; + if (!empty($goods['goods_attr'])) + { + foreach ($goods['goods_attr'] as $attr) + { + $goods_attr_name .= $attr['attr_name'] . ':' . $attr['attr_val'] . ' '; + } + } + + // 总价 + $total = $goods['number'] * $goods['goods_price']; + + $_SESSION['wholesale_goods'][] = array( + 'goods_id' => $wholesale['goods_id'], + 'goods_name' => $wholesale['goods_name'], + 'goods_attr_id' => $goods['goods_attr'], + 'goods_attr' => $goods_attr_name, + 'goods_number' => $goods['number'], + 'goods_price' => $goods['goods_price'], + 'subtotal' => $total, + 'formated_goods_price' => price_format($goods['goods_price'], false), + 'formated_subtotal' => price_format($total, false), + 'goods_url' => build_uri('goods', array('gid' => $wholesale['goods_id']), $wholesale['goods_name']), + ); + } + + unset($goods_attr, $attr_id, $goods_list, $wholesale, $goods_attr_name); + + /* 刷新页面 */ + ecs_header("Location: ./wholesale.php\n"); + exit; +} + +/*------------------------------------------------------ */ +//-- 从购物车删除 +/*------------------------------------------------------ */ +elseif ($_REQUEST['act'] == 'drop_goods') +{ + $key = intval($_REQUEST['key']); + if (isset($_SESSION['wholesale_goods'][$key])) + { + unset($_SESSION['wholesale_goods'][$key]); + } + + /* 刷新页面 */ + ecs_header("Location: ./wholesale.php\n"); + exit; +} + +/*------------------------------------------------------ */ +//-- 提交订单 +/*------------------------------------------------------ */ +elseif ($_REQUEST['act'] == 'submit_order') +{ + include_once(ROOT_PATH . 'includes/lib_order.php'); + + /* 检查购物车中是否有商品 */ + if (count($_SESSION['wholesale_goods']) == 0) + { + show_message($_LANG['no_goods_in_cart']); + } + + /* 检查备注信息 */ + if (empty($_POST['remark'])) + { + show_message($_LANG['ws_remark']); + } + + /* 计算商品总额 */ + $goods_amount = 0; + foreach ($_SESSION['wholesale_goods'] as $goods) + { + $goods_amount += $goods['subtotal']; + } + + $order = array( + 'postscript' => htmlspecialchars($_POST['remark']), + 'user_id' => $_SESSION['user_id'], + 'add_time' => gmtime(), + 'order_status' => OS_UNCONFIRMED, + 'shipping_status' => SS_UNSHIPPED, + 'pay_status' => PS_UNPAYED, + 'goods_amount' => $goods_amount, + 'order_amount' => $goods_amount, + ); + + /* 插入订单表 */ + $error_no = 0; + do + { + $order['order_sn'] = get_order_sn(); //获取新订单号 + $GLOBALS['db']->autoExecute($GLOBALS['ecs']->table('order_info'), $order, 'INSERT'); + + $error_no = $GLOBALS['db']->errno(); + + if ($error_no > 0 && $error_no != 1062) + { + die($GLOBALS['db']->errorMsg()); + } + } + while ($error_no == 1062); //如果是订单号重复则重新提交数据 + + $new_order_id = $db->insert_id(); + $order['order_id'] = $new_order_id; + + /* 插入订单商品 */ + foreach ($_SESSION['wholesale_goods'] as $goods) + { + //如果存在货品 + $product_id = 0; + if (!empty($goods['goods_attr_id'])) + { + $goods_attr_id = array(); + foreach ($goods['goods_attr_id'] as $value) + { + $goods_attr_id[$value['attr_id']] = $value['attr_val_id']; + } + + ksort($goods_attr_id); + $goods_attr = implode('|', $goods_attr_id); + + $sql = "SELECT product_id FROM " . $ecs->table('products') . " WHERE goods_attr = '$goods_attr' AND goods_id = '" . $goods['goods_id'] . "'"; + $product_id = $db->getOne($sql); + } + + $sql = "INSERT INTO " . $ecs->table('order_goods') . "( " . + "order_id, goods_id, goods_name, goods_sn, product_id, goods_number, market_price, ". + "goods_price, goods_attr, is_real, extension_code, parent_id, is_gift) ". + " SELECT '$new_order_id', goods_id, goods_name, goods_sn, '$product_id','$goods[goods_number]', market_price, ". + "'$goods[goods_price]', '$goods[goods_attr]', is_real, extension_code, 0, 0 ". + " FROM " .$ecs->table('goods') . + " WHERE goods_id = '$goods[goods_id]'"; + $db->query($sql); + } + + /* 给商家发邮件 */ + if ($_CFG['service_email'] != '') + { + $tpl = get_mail_template('remind_of_new_order'); + $smarty->assign('order', $order); + $smarty->assign('shop_name', $_CFG['shop_name']); + $smarty->assign('send_date', date($_CFG['time_format'])); + $content = $smarty->fetch('str:' . $tpl['template_content']); + send_mail($_CFG['shop_name'], $_CFG['service_email'], $tpl['template_subject'], $content, $tpl['is_html']); + } + + /* 如果需要,发短信 */ + if ($_CFG['sms_order_placed'] == '1' && $_CFG['sms_shop_mobile'] != '') + { + include_once('includes/cls_sms.php'); + $sms = new sms(); + $msg = $_LANG['order_placed_sms']; + $sms->send($_CFG['sms_shop_mobile'], sprintf($msg, $order['consignee'], $order['tel']),'', 13,1); + } + + /* 清空购物车 */ + unset($_SESSION['wholesale_goods']); + + /* 提示 */ + show_message(sprintf($_LANG['ws_order_submitted'], $order['order_sn']), $_LANG['ws_return_home'], 'index.php'); +} + +/** + * 取得某页的批发商品 + * @param int $size 每页记录数 + * @param int $page 当前页 + * @param string $where 查询条件 + * @return array + */ +function wholesale_list($size, $page, $where) +{ + $list = array(); + $sql = "SELECT w.*, g.goods_thumb, g.goods_name as goods_name " . + "FROM " . $GLOBALS['ecs']->table('wholesale') . " AS w, " . + $GLOBALS['ecs']->table('goods') . " AS g " . $where . + " AND w.goods_id = g.goods_id "; + $res = $GLOBALS['db']->selectLimit($sql, $size, ($page - 1) * $size); + while ($row = $GLOBALS['db']->fetchRow($res)) + { + if (empty($row['goods_thumb'])) + { + $row['goods_thumb'] = $GLOBALS['_CFG']['no_picture']; + } + $row['goods_url'] = build_uri('goods', array('gid'=>$row['goods_id']), $row['goods_name']); + + $properties = get_goods_properties($row['goods_id']); + $row['goods_attr'] = $properties['pro']; + + $price_ladder = get_price_ladder($row['goods_id']); + $row['price_ladder'] = $price_ladder; + + $list[] = $row; + } + + return $list; +} + +/** + * 商品价格阶梯 + * @param int $goods_id 商品ID + * @return array + */ +function get_price_ladder($goods_id) +{ + /* 显示商品规格 */ + $goods_attr_list = array_values(get_goods_attr($goods_id)); + $sql = "SELECT prices FROM " . $GLOBALS['ecs']->table('wholesale') . + "WHERE goods_id = " . $goods_id; + $row = $GLOBALS['db']->getRow($sql); + + $arr = array(); + $_arr = unserialize($row['prices']); + if (is_array($_arr)) + { + foreach(unserialize($row['prices']) as $key => $val) + { + // 显示属性 + if (!empty($val['attr'])) + { + foreach ($val['attr'] as $attr_key => $attr_val) + { + // 获取当前属性 $attr_key 的信息 + $goods_attr = array(); + foreach ($goods_attr_list as $goods_attr_val) + { + if ($goods_attr_val['attr_id'] == $attr_key) + { + $goods_attr = $goods_attr_val; + break; + } + } + + // 重写商品规格的价格阶梯信息 + if (!empty($goods_attr)) + { + $arr[$key]['attr'][] = array( + 'attr_id' => $goods_attr['attr_id'], + 'attr_name' => $goods_attr['attr_name'], + 'attr_val' => (isset($goods_attr['goods_attr_list'][$attr_val]) ? $goods_attr['goods_attr_list'][$attr_val] : ''), + 'attr_val_id' => $attr_val + ); + } + } + } + + // 显示数量与价格 + foreach($val['qp_list'] as $index => $qp) + { + $arr[$key]['qp_list'][$qp['quantity']] = price_format($qp['price']); + } + } + } + + return $arr; +} + +/** + * 商品属性是否匹配 + * @param array $goods_list 用户选择的商品 + * @param array $reference 参照的商品属性 + * @return bool + */ +function is_attr_matching(&$goods_list, $reference) +{ + foreach ($goods_list as $key => $goods) + { + // 需要相同的元素个数 + if (count($goods['goods_attr']) != count($reference)) + { + break; + } + + // 判断用户提交与批发属性是否相同 + $is_check = true; + if (is_array($goods['goods_attr'])) + { + foreach ($goods['goods_attr'] as $attr) + { + if (!(array_key_exists($attr['attr_id'], $reference) && $attr['attr_val_id'] == $reference[$attr['attr_id']])) + { + $is_check = false; + break; + } + } + } + if ($is_check) + { + return $key; + break; + } + } + + +// foreach ($goods_attr as $attr_id => $goods_attr_id) +// { +// if (isset($reference[$attr_id]) && $reference[$attr_id] != 0 && $reference[$attr_id] != $goods_attr_id) +// { +// return false; +// } +// } + + return false; +} + +///** +// * 购物车中的商品属性与当前购买的商品属性是否匹配 +// * @param array $goods_attr 用户选择的商品属性 +// * @param array $reference 参照的商品属性 +// * @return bool +// */ +//function is_attr_same($goods_attr, $reference) +//{ +// /* 比较元素个数是否相同 */ +// if (count($goods_attr) == count($reference)) { +// } +// +// return true; +//} +?> diff --git "a/\345\256\211\350\243\205\345\277\205\347\234\213.txt" "b/\345\256\211\350\243\205\345\277\205\347\234\213.txt" new file mode 100644 index 0000000..6f45dce --- /dev/null +++ "b/\345\256\211\350\243\205\345\277\205\347\234\213.txt" @@ -0,0 +1,13 @@ + +װ˵ +1.diguoĿ¼ָݿ ۹admin 123456 + +2.޸dataĿ¼config.phpݿϢ + + +3.½̨޸ԼϢ ַ̨admin ֻmobile/admin + + ʺadmin admin888 + +http://www.zuimoban.com + diff --git "a/\346\234\200\346\250\241\346\235\277 - \344\270\223\346\263\250\347\275\221\345\272\227\345\225\206\345\237\216\346\250\241\346\235\277\345\210\266\344\275\234\344\270\216\345\256\232\345\210\266\345\274\200\345\217\221.url" "b/\346\234\200\346\250\241\346\235\277 - \344\270\223\346\263\250\347\275\221\345\272\227\345\225\206\345\237\216\346\250\241\346\235\277\345\210\266\344\275\234\344\270\216\345\256\232\345\210\266\345\274\200\345\217\221.url" new file mode 100644 index 0000000..f60bd51 --- /dev/null +++ "b/\346\234\200\346\250\241\346\235\277 - \344\270\223\346\263\250\347\275\221\345\272\227\345\225\206\345\237\216\346\250\241\346\235\277\345\210\266\344\275\234\344\270\216\345\256\232\345\210\266\345\274\200\345\217\221.url" @@ -0,0 +1,9 @@ +[DEFAULT] +BASEURL=http://www.zuimoban.com/ +[{000214A0-0000-0000-C000-000000000046}] +Prop3=19,2 +[InternetShortcut] +URL=http://www.zuimoban.com/ +IDList= +IconFile=http://www.zuimoban.com/favicon.ico +IconIndex=1