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 = '' .
+ '
';
+ 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.=''.$root.'>';
+ 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.=''.$k.'>';
+ }
+ }
+ }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 .= '' . 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 .= '' . $this->unicode_table[hexdec(bin2hex($this->SourceText{0} . $this->SourceText{1})) - 0x8080] . ';';
+ }
+ elseif ($this->config['source_lang'] == 'BIG-5')
+ {
+ $utf .= '' . $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 "
error_message[2]['error']) . "' target='_blank'>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 D=B.search('');if ((C!=-1&&D!=-1&&C0){if (FCKSelection.GetType()=='Control'){var D=this.EditorDocument.createElement('A');D.href=A;var E=FCKSelection.GetSelectedElement();E.parentNode.insertBefore(D,E);E.parentNode.removeChild(E);D.appendChild(E);return [D];};var F='javascript:void(0);/*'+(new Date().getTime())+'*/';FCK.ExecuteNamedCommand('CreateLink',F,false,!!B);var G=this.EditorDocument.links;for (i=0;i0&&!isNaN(E)) this.PageConfig[D]=parseInt(E,10);else this.PageConfig[D]=E;}};function FCKConfig_LoadPageConfig(){var A=FCKConfig.PageConfig;for (var B in A) FCKConfig[B]=A[B];};function FCKConfig_PreProcess(){var A=FCKConfig;if (A.AllowQueryStringDebug){try{if ((/fckdebug=true/i).test(window.top.location.search)) A.Debug=true;}catch (e) { }};if (!A.PluginsPath.EndsWith('/')) A.PluginsPath+='/';var B=A.ToolbarComboPreviewCSS;if (!B||B.length==0) A.ToolbarComboPreviewCSS=A.EditorAreaCSS;A.RemoveAttributesArray=(A.RemoveAttributes||'').split(',');if (!FCKConfig.SkinEditorCSS||FCKConfig.SkinEditorCSS.length==0) FCKConfig.SkinEditorCSS=FCKConfig.SkinPath+'fck_editor.css';if (!FCKConfig.SkinDialogCSS||FCKConfig.SkinDialogCSS.length==0) FCKConfig.SkinDialogCSS=FCKConfig.SkinPath+'fck_dialog.css';};FCKConfig.ToolbarSets={};FCKConfig.Plugins={};FCKConfig.Plugins.Items=[];FCKConfig.Plugins.Add=function(A,B,C){FCKConfig.Plugins.Items.AddItem([A,B,C]);};FCKConfig.ProtectedSource={};FCKConfig.ProtectedSource._CodeTag=(new Date()).valueOf();FCKConfig.ProtectedSource.RegexEntries=[//g,/'+A;if (FCKBrowserInfo.IsIE) A=A.replace(/(]*?)\s*\/?>(?!\s*<\/base>)/gi,'$1>');else if (!B){var E=A.match(FCKRegexLib.BeforeBody);var F=A.match(FCKRegexLib.AfterBody);if (E&&F){var G=A.substr(E[1].length,A.length-E[1].length-F[1].length);A=E[1]+' '+F[1];if (FCKBrowserInfo.IsGecko&&(G.length==0||FCKRegexLib.EmptyParagraph.test(G))) G='
';this._BodyHTML=G;}else this._BodyHTML=A;};var H=this.IFrame=D.createElement('iframe');var I='';H.frameBorder=0;H.style.width=H.style.height='100%';if (FCK_IS_CUSTOM_DOMAIN&&FCKBrowserInfo.IsIE){window._FCKHtmlToLoad=A.replace(//i,''+I);H.src='javascript:void( (function(){document.open() ;document.domain="'+document.domain+'" ;document.write( window.parent._FCKHtmlToLoad );document.close() ;window.parent._FCKHtmlToLoad = null ;})() )';}else if (!FCKBrowserInfo.IsGecko){H.src='javascript:void(0)';};C.appendChild(H);this.Window=H.contentWindow;if (!FCK_IS_CUSTOM_DOMAIN||!FCKBrowserInfo.IsIE){var J=this.Window.document;J.open();J.write(A.replace(//i,''+I));J.close();};if (FCKBrowserInfo.IsAIR) FCKAdobeAIR.EditingArea_Start(J,A);if (FCKBrowserInfo.IsGecko10&&!B){this.Start(A,true);return;};if (H.readyState&&H.readyState!='completed'){var K=this;setTimeout(function(){try{K.Window.document.documentElement.doScroll("left");}catch(e){setTimeout(arguments.callee,0);return;};K.Window._FCKEditingArea=K;FCKEditingArea_CompleteStart.call(K.Window);},0);}else{this.Window._FCKEditingArea=this;if (FCKBrowserInfo.IsGecko10) this.Window.setTimeout(FCKEditingArea_CompleteStart,500);else FCKEditingArea_CompleteStart.call(this.Window);}}else{var L=this.Textarea=D.createElement('textarea');L.className='SourceField';L.dir='ltr';FCKDomTools.SetElementStyles(L,{width:'100%',height:'100%',border:'none',resize:'none',outline:'none'});C.appendChild(L);L.value=A;FCKTools.RunFunction(this.OnLoad);}};function FCKEditingArea_CompleteStart(){if (!this.document.body){this.setTimeout(FCKEditingArea_CompleteStart,50);return;};var A=this._FCKEditingArea;A.Document=A.Window.document;A.MakeEditable();FCKTools.RunFunction(A.OnLoad);};FCKEditingArea.prototype.MakeEditable=function(){var A=this.Document;if (FCKBrowserInfo.IsIE){A.body.disabled=true;A.body.contentEditable=true;A.body.removeAttribute("disabled");}else{try{A.body.spellcheck=(this.FFSpellChecker!==false);if (this._BodyHTML){A.body.innerHTML=this._BodyHTML;A.body.offsetLeft;this._BodyHTML=null;};A.designMode='on';A.execCommand('enableObjectResizing',false,!FCKConfig.DisableObjectResizing);A.execCommand('enableInlineTableEditing',false,!FCKConfig.DisableFFTableHandles);}catch (e){FCKTools.AddEventListener(this.Window.frameElement,'DOMAttrModified',FCKEditingArea_Document_AttributeNodeModified);}}};function FCKEditingArea_Document_AttributeNodeModified(A){var B=A.currentTarget.contentWindow._FCKEditingArea;if (B._timer) window.clearTimeout(B._timer);B._timer=FCKTools.SetTimeout(FCKEditingArea_MakeEditableByMutation,1000,B);};function FCKEditingArea_MakeEditableByMutation(){delete this._timer;FCKTools.RemoveEventListener(this.Window.frameElement,'DOMAttrModified',FCKEditingArea_Document_AttributeNodeModified);this.MakeEditable();};FCKEditingArea.prototype.Focus=function(){try{if (this.Mode==0){if (FCKBrowserInfo.IsIE) this._FocusIE();else this.Window.focus();}else{var A=FCKTools.GetElementDocument(this.Textarea);if ((!A.hasFocus||A.hasFocus())&&A.activeElement==this.Textarea) return;this.Textarea.focus();}}catch(e) {}};FCKEditingArea.prototype._FocusIE=function(){this.Document.body.setActive();this.Window.focus();var A=this.Document.selection.createRange();var B=A.parentElement();var C=B.nodeName.toLowerCase();if (B.childNodes.length>0||!(FCKListsLib.BlockElements[C]||FCKListsLib.NonEmptyBlockElements[C])){return;};A=new FCKDomRange(this.Window);A.MoveToElementEditStart(B);A.Select();};function FCKEditingArea_Cleanup(){if (this.Document) this.Document.body.innerHTML="";this.TargetElement=null;this.IFrame=null;this.Document=null;this.Textarea=null;if (this.Window){this.Window._FCKEditingArea=null;this.Window=null;}};
+var FCKKeystrokeHandler=function(A){this.Keystrokes={};this.CancelCtrlDefaults=(A!==false);};FCKKeystrokeHandler.prototype.AttachToElement=function(A){FCKTools.AddEventListenerEx(A,'keydown',_FCKKeystrokeHandler_OnKeyDown,this);if (FCKBrowserInfo.IsGecko10||FCKBrowserInfo.IsOpera||(FCKBrowserInfo.IsGecko&&FCKBrowserInfo.IsMac)) FCKTools.AddEventListenerEx(A,'keypress',_FCKKeystrokeHandler_OnKeyPress,this);};FCKKeystrokeHandler.prototype.SetKeystrokes=function(){for (var i=0;i40))){B._CancelIt=true;if (A.preventDefault) return A.preventDefault();A.returnValue=false;A.cancelBubble=true;return false;};return true;};function _FCKKeystrokeHandler_OnKeyPress(A,B){if (B._CancelIt){if (A.preventDefault) return A.preventDefault();return false;};return true;};
+FCK.DTD=(function(){var X=FCKTools.Merge;var A,L,J,M,N,O,D,H,P,K,Q,F,G,C,B,E,I;A={isindex:1,fieldset:1};B={input:1,button:1,select:1,textarea:1,label:1};C=X({a:1},B);D=X({iframe:1},C);E={hr:1,ul:1,menu:1,div:1,blockquote:1,noscript:1,table:1,center:1,address:1,dir:1,pre:1,h5:1,dl:1,h4:1,noframes:1,h6:1,ol:1,h1:1,h3:1,h2:1};F={ins:1,del:1,script:1};G=X({b:1,acronym:1,bdo:1,'var':1,'#':1,abbr:1,code:1,br:1,i:1,cite:1,kbd:1,u:1,strike:1,s:1,tt:1,strong:1,q:1,samp:1,em:1,dfn:1,span:1},F);H=X({sub:1,img:1,object:1,sup:1,basefont:1,map:1,applet:1,font:1,big:1,small:1},G);I=X({p:1},H);J=X({iframe:1},H,B);K={img:1,noscript:1,br:1,kbd:1,center:1,button:1,basefont:1,h5:1,h4:1,samp:1,h6:1,ol:1,h1:1,h3:1,h2:1,form:1,font:1,'#':1,select:1,menu:1,ins:1,abbr:1,label:1,code:1,table:1,script:1,cite:1,input:1,iframe:1,strong:1,textarea:1,noframes:1,big:1,small:1,span:1,hr:1,sub:1,bdo:1,'var':1,div:1,object:1,sup:1,strike:1,dir:1,map:1,dl:1,applet:1,del:1,isindex:1,fieldset:1,ul:1,b:1,acronym:1,a:1,blockquote:1,i:1,u:1,s:1,tt:1,address:1,q:1,pre:1,p:1,em:1,dfn:1};L=X({a:1},J);M={tr:1};N={'#':1};O=X({param:1},K);P=X({form:1},A,D,E,I);Q={li:1};return {col:{},tr:{td:1,th:1},img:{},colgroup:{col:1},noscript:P,td:P,br:{},th:P,center:P,kbd:L,button:X(I,E),basefont:{},h5:L,h4:L,samp:L,h6:L,ol:Q,h1:L,h3:L,option:N,h2:L,form:X(A,D,E,I),select:{optgroup:1,option:1},font:J,ins:P,menu:Q,abbr:L,label:L,table:{thead:1,col:1,tbody:1,tr:1,colgroup:1,caption:1,tfoot:1},code:L,script:N,tfoot:M,cite:L,li:P,input:{},iframe:P,strong:J,textarea:N,noframes:P,big:J,small:J,span:J,hr:{},dt:L,sub:J,optgroup:{option:1},param:{},bdo:L,'var':J,div:P,object:O,sup:J,dd:P,strike:J,area:{},dir:Q,map:X({area:1,form:1,p:1},A,F,E),applet:O,dl:{dt:1,dd:1},del:P,isindex:{},fieldset:X({legend:1},K),thead:M,ul:Q,acronym:L,b:J,a:J,blockquote:P,caption:L,i:J,u:J,tbody:M,s:L,address:X(D,I),tt:J,legend:L,q:L,pre:X(G,C),p:L,em:J,dfn:L};})();
+var FCKStyle=function(A){this.Element=(A.Element||'span').toLowerCase();this._StyleDesc=A;};FCKStyle.prototype={GetType:function(){var A=this.GetType_$;if (A!=undefined) return A;var B=this.Element;if (B=='#'||FCKListsLib.StyleBlockElements[B]) A=0;else if (FCKListsLib.StyleObjectElements[B]) A=2;else A=1;return (this.GetType_$=A);},ApplyToSelection:function(A){var B=new FCKDomRange(A);B.MoveToSelection();this.ApplyToRange(B,true);},ApplyToRange:function(A,B,C){switch (this.GetType()){case 0:this.ApplyToRange=this._ApplyBlockStyle;break;case 1:this.ApplyToRange=this._ApplyInlineStyle;break;default:return;};this.ApplyToRange(A,B,C);},ApplyToObject:function(A){if (!A) return;this.BuildElement(null,A);},RemoveFromSelection:function(A){var B=new FCKDomRange(A);B.MoveToSelection();this.RemoveFromRange(B,true);},RemoveFromRange:function(A,B,C){var D;var E=this._GetAttribsForComparison();var F=this._GetOverridesForComparison();if (A.CheckIsCollapsed()){var D=A.CreateBookmark(true);var H=A.GetBookmarkNode(D,true);var I=new FCKElementPath(H.parentNode);var J=[];var K=!FCKDomTools.GetNextSibling(H);var L=K||!FCKDomTools.GetPreviousSibling(H);var M;var N=-1;for (var i=0;i=0;i--){var E=D[i];for (var F in B){if (FCKDomTools.HasAttribute(E,F)){switch (F){case 'style':this._RemoveStylesFromElement(E);break;case 'class':if (FCKDomTools.GetAttributeValue(E,F)!=this.GetFinalAttributeValue(F)) continue;default:FCKDomTools.RemoveAttribute(E,F);}}};this._RemoveOverrides(E,C[this.Element]);this._RemoveNoAttribElement(E);};for (var G in C){if (G!=this.Element){D=A.getElementsByTagName(G);for (var i=D.length-1;i>=0;i--){var E=D[i];this._RemoveOverrides(E,C[G]);this._RemoveNoAttribElement(E);}}}},_RemoveStylesFromElement:function(A){var B=A.style.cssText;var C=this.GetFinalStyleValue();if (B.length>0&&C.length==0) return;C='(^|;)\\s*('+C.replace(/\s*([^ ]+):.*?(;|$)/g,'$1|').replace(/\|$/,'')+'):[^;]+';var D=new RegExp(C,'gi');B=B.replace(D,'').Trim();if (B.length==0||B==';') FCKDomTools.RemoveAttribute(A,'style');else A.style.cssText=B.replace(D,'');},_RemoveOverrides:function(A,B){var C=B&&B.Attributes;if (C){for (var i=0;i0) C.style.cssText=this.GetFinalStyleValue();return C;},_CompareAttributeValues:function(A,B,C){if (A=='style'&&B&&C){B=B.replace(/;$/,'').toLowerCase();C=C.replace(/;$/,'').toLowerCase();};return (B==C||((B===null||B==='')&&(C===null||C==='')))},GetFinalAttributeValue:function(A){var B=this._StyleDesc.Attributes;var B=B?B[A]:null;if (!B&&A=='style') return this.GetFinalStyleValue();if (B&&this._Variables) B=B.Replace(FCKRegexLib.StyleVariableAttName,this._GetVariableReplace,this);return B;},GetFinalStyleValue:function(){var A=this._GetStyleText();if (A.length>0&&this._Variables){A=A.Replace(FCKRegexLib.StyleVariableAttName,this._GetVariableReplace,this);A=FCKTools.NormalizeCssText(A);};return A;},_GetVariableReplace:function(){return this._Variables[arguments[2]]||arguments[0];},SetVariable:function(A,B){var C=this._Variables;if (!C) C=this._Variables={};this._Variables[A]=B;},_FromPre:function(A,B,C){var D=B.innerHTML;D=D.replace(/(\r\n|\r)/g,'\n');D=D.replace(/^[ \t]*\n/,'');D=D.replace(/\n$/,'');D=D.replace(/^[ \t]+|[ \t]+$/g,function(match,offset,s){if (match.length==1) return ' ';else if (offset==0) return new Array(match.length).join(' ')+' ';else return ' '+new Array(match.length).join(' ');});var E=new FCKHtmlIterator(D);var F=[];E.Each(function(isTag,value){if (!isTag){value=value.replace(/\n/g,'
');value=value.replace(/[ \t]{2,}/g,function (match){return new Array(match.length).join(' ')+' ';});};F.push(value);});C.innerHTML=F.join('');return C;},_ToPre:function(A,B,C){var D=B.innerHTML.Trim();D=D.replace(/[ \t\r\n]*(
]*>)[ \t\r\n]*/gi,'
');var E=new FCKHtmlIterator(D);var F=[];E.Each(function(isTag,value){if (!isTag) value=value.replace(/([ \t\n\r]+| )/g,' ');else if (isTag&&value=='
') value='\n';F.push(value);});if (FCKBrowserInfo.IsIE){var G=A.createElement('div');G.appendChild(C);C.outerHTML='\n'+F.join('')+'
';C=G.removeChild(G.firstChild);}else C.innerHTML=F.join('');return C;},_CheckAndMergePre:function(A,B){if (A!=FCKDomTools.GetPreviousSourceElement(B,true)) return;var C=A.innerHTML.replace(/\n$/,'')+'\n\n'+B.innerHTML.replace(/^\n/,'');if (FCKBrowserInfo.IsIE) B.outerHTML=''+C+'
';else B.innerHTML=C;FCKDomTools.RemoveNode(A);},_CheckAndSplitPre:function(A){var B;var C=A.firstChild;C=C&&C.nextSibling;while (C){var D=C.nextSibling;if (D&&D.nextSibling&&C.nodeName.IEquals('br')&&D.nodeName.IEquals('br')){FCKDomTools.RemoveNode(C);C=D.nextSibling;FCKDomTools.RemoveNode(D);B=FCKDomTools.InsertAfterNode(B||A,FCKDomTools.CloneElement(A));continue;};if (B){C=C.previousSibling;FCKDomTools.MoveNode(C.nextSibling,B);};C=C.nextSibling;}},_ApplyBlockStyle:function(A,B,C){var D;if (B) D=A.CreateBookmark();var E=new FCKDomRangeIterator(A);E.EnforceRealBlocks=true;var F;var G=A.Window.document;var H;while((F=E.GetNextParagraph())){var I=this.BuildElement(G);var J=I.nodeName.IEquals('pre');var K=F.nodeName.IEquals('pre');var L=J&&!K;var M=!J&&K;if (L) I=this._ToPre(G,F,I);else if (M) I=this._FromPre(G,F,I);else FCKDomTools.MoveChildren(F,I);F.parentNode.insertBefore(I,F);FCKDomTools.RemoveNode(F);if (J){if (H) this._CheckAndMergePre(H,I);H=I;}else if (M) this._CheckAndSplitPre(I);};if (B) A.SelectBookmark(D);if (C) A.MoveToBookmark(D);},_ApplyInlineStyle:function(A,B,C){var D=A.Window.document;if (A.CheckIsCollapsed()){var E=this.BuildElement(D);A.InsertNode(E);A.MoveToPosition(E,2);A.Select();return;};var F=this.Element;var G=FCK.DTD[F]||FCK.DTD.span;var H=this._GetAttribsForComparison();var I;A.Expand('inline_elements');var J=A.CreateBookmark(true);var K=A.GetBookmarkNode(J,true);var L=A.GetBookmarkNode(J,false);A.Release(true);var M=FCKDomTools.GetNextSourceNode(K,true);while (M){var N=false;var O=M.nodeType;var P=O==1?M.nodeName.toLowerCase():null;if (!P||G[P]){if ((FCK.DTD[M.parentNode.nodeName.toLowerCase()]||FCK.DTD.span)[F]||!FCK.DTD[F]){if (!A.CheckHasRange()) A.SetStart(M,3);if (O!=1||M.childNodes.length==0){var Q=M;var R=Q.parentNode;while (Q==R.lastChild&&G[R.nodeName.toLowerCase()]){Q=R;};A.SetEnd(Q,4);if (Q==Q.parentNode.lastChild&&!G[Q.parentNode.nodeName.toLowerCase()]) N=true;}else{A.SetEnd(M,3);}}else N=true;}else N=true;M=FCKDomTools.GetNextSourceNode(M);if (M==L){M=null;N=true;};if (N&&A.CheckHasRange()&&!A.CheckIsCollapsed()){I=this.BuildElement(D);A.ExtractContents().AppendTo(I);if (I.innerHTML.RTrim().length>0){A.InsertNode(I);this.RemoveFromElement(I);this._MergeSiblings(I,this._GetAttribsForComparison());if (!FCKBrowserInfo.IsIE) I.normalize();};A.Release(true);}};this._FixBookmarkStart(K);if (B) A.SelectBookmark(J);if (C) A.MoveToBookmark(J);},_FixBookmarkStart:function(A){var B;while ((B=A.nextSibling)){if (B.nodeType==1&&FCKListsLib.InlineNonEmptyElements[B.nodeName.toLowerCase()]){if (!B.firstChild) FCKDomTools.RemoveNode(B);else FCKDomTools.MoveNode(A,B,true);continue;};if (B.nodeType==3&&B.length==0){FCKDomTools.RemoveNode(B);continue;};break;}},_MergeSiblings:function(A,B){if (!A||A.nodeType!=1||!FCKListsLib.InlineNonEmptyElements[A.nodeName.toLowerCase()]) return;this._MergeNextSibling(A,B);this._MergePreviousSibling(A,B);},_MergeNextSibling:function(A,B){var C=A.nextSibling;var D=(C&&C.nodeType==1&&C.getAttribute('_fck_bookmark'));if (D) C=C.nextSibling;if (C&&C.nodeType==1&&C.nodeName==A.nodeName){if (!B) B=this._CreateElementAttribsForComparison(A);if (this._CheckAttributesMatch(C,B)){var E=A.lastChild;if (D) FCKDomTools.MoveNode(A.nextSibling,A);FCKDomTools.MoveChildren(C,A);FCKDomTools.RemoveNode(C);if (E) this._MergeNextSibling(E);}}},_MergePreviousSibling:function(A,B){var C=A.previousSibling;var D=(C&&C.nodeType==1&&C.getAttribute('_fck_bookmark'));if (D) C=C.previousSibling;if (C&&C.nodeType==1&&C.nodeName==A.nodeName){if (!B) B=this._CreateElementAttribsForComparison(A);if (this._CheckAttributesMatch(C,B)){var E=A.firstChild;if (D) FCKDomTools.MoveNode(A.previousSibling,A,true);FCKDomTools.MoveChildren(C,A,true);FCKDomTools.RemoveNode(C);if (E) this._MergePreviousSibling(E);}}},_GetStyleText:function(){var A=this._StyleDesc.Styles;var B=(this._StyleDesc.Attributes?this._StyleDesc.Attributes['style']||'':'');if (B.length>0) B+=';';for (var C in A) B+=C+':'+A[C]+';';if (B.length>0&&!(/#\(/.test(B))){B=FCKTools.NormalizeCssText(B);};return (this._GetStyleText=function() { return B;})();},_GetAttribsForComparison:function(){var A=this._GetAttribsForComparison_$;if (A) return A;A={};var B=this._StyleDesc.Attributes;if (B){for (var C in B){A[C.toLowerCase()]=B[C].toLowerCase();}};if (this._GetStyleText().length>0){A['style']=this._GetStyleText().toLowerCase();};FCKTools.AppendLengthProperty(A,'_length');return (this._GetAttribsForComparison_$=A);},_GetOverridesForComparison:function(){var A=this._GetOverridesForComparison_$;if (A) return A;A={};var B=this._StyleDesc.Overrides;if (B){if (!FCKTools.IsArray(B)) B=[B];for (var i=0;i0) return true;};B=B.nextSibling;};return false;}};
+var FCKElementPath=function(A){var B=null;var C=null;var D=[];var e=A;while (e){if (e.nodeType==1){if (!this.LastElement) this.LastElement=e;var E=e.nodeName.toLowerCase();if (FCKBrowserInfo.IsIE&&e.scopeName!='HTML') E=e.scopeName.toLowerCase()+':'+E;if (!C){if (!B&&FCKListsLib.PathBlockElements[E]!=null) B=e;if (FCKListsLib.PathBlockLimitElements[E]!=null){if (!B&&E=='div'&&!FCKElementPath._CheckHasBlock(e)) B=e;else C=e;}};D.push(e);if (E=='body') break;};e=e.parentNode;};this.Block=B;this.BlockLimit=C;this.Elements=D;};FCKElementPath._CheckHasBlock=function(A){var B=A.childNodes;for (var i=0,count=B.length;i0){if (D.nodeType==3){var G=D.nodeValue.substr(0,E).Trim();if (G.length!=0) return A.IsStartOfBlock=false;}else F=D.childNodes[E-1];};if (!F) F=FCKDomTools.GetPreviousSourceNode(D,true,null,C);while (F){switch (F.nodeType){case 1:if (!FCKListsLib.InlineChildReqElements[F.nodeName.toLowerCase()]) return A.IsStartOfBlock=false;break;case 3:if (F.nodeValue.Trim().length>0) return A.IsStartOfBlock=false;};F=FCKDomTools.GetPreviousSourceNode(F,false,null,C);};return A.IsStartOfBlock=true;},CheckEndOfBlock:function(A){var B=this._Cache.IsEndOfBlock;if (B!=undefined) return B;var C=this.EndBlock||this.EndBlockLimit;var D=this._Range.endContainer;var E=this._Range.endOffset;var F;if (D.nodeType==3){var G=D.nodeValue;if (E0) return this._Cache.IsEndOfBlock=false;};F=FCKDomTools.GetNextSourceNode(F,false,null,C);};if (A) this.Select();return this._Cache.IsEndOfBlock=true;},CreateBookmark:function(A){var B={StartId:(new Date()).valueOf()+Math.floor(Math.random()*1000)+'S',EndId:(new Date()).valueOf()+Math.floor(Math.random()*1000)+'E'};var C=this.Window.document;var D;var E;var F;if (!this.CheckIsCollapsed()){E=C.createElement('span');E.style.display='none';E.id=B.EndId;E.setAttribute('_fck_bookmark',true);E.innerHTML=' ';F=this.Clone();F.Collapse(false);F.InsertNode(E);};D=C.createElement('span');D.style.display='none';D.id=B.StartId;D.setAttribute('_fck_bookmark',true);D.innerHTML=' ';F=this.Clone();F.Collapse(true);F.InsertNode(D);if (A){B.StartNode=D;B.EndNode=E;};if (E){this.SetStart(D,4);this.SetEnd(E,3);}else this.MoveToPosition(D,4);return B;},GetBookmarkNode:function(A,B){var C=this.Window.document;if (B) return A.StartNode||C.getElementById(A.StartId);else return A.EndNode||C.getElementById(A.EndId);},MoveToBookmark:function(A,B){var C=this.GetBookmarkNode(A,true);var D=this.GetBookmarkNode(A,false);this.SetStart(C,3);if (!B) FCKDomTools.RemoveNode(C);if (D){this.SetEnd(D,3);if (!B) FCKDomTools.RemoveNode(D);}else this.Collapse(true);this._UpdateElementInfo();},CreateBookmark2:function(){if (!this._Range) return { "Start":0,"End":0 };var A={"Start":[this._Range.startOffset],"End":[this._Range.endOffset]};var B=this._Range.startContainer.previousSibling;var C=this._Range.endContainer.previousSibling;var D=this._Range.startContainer;var E=this._Range.endContainer;while (B&&D.nodeType==3){A.Start[0]+=B.length;D=B;B=B.previousSibling;}while (C&&E.nodeType==3){A.End[0]+=C.length;E=C;C=C.previousSibling;};if (D.nodeType==1&&D.childNodes[A.Start[0]]&&D.childNodes[A.Start[0]].nodeType==3){var F=D.childNodes[A.Start[0]];var G=0;while (F.previousSibling&&F.previousSibling.nodeType==3){F=F.previousSibling;G+=F.length;};D=F;A.Start[0]=G;};if (E.nodeType==1&&E.childNodes[A.End[0]]&&E.childNodes[A.End[0]].nodeType==3){var F=E.childNodes[A.End[0]];var G=0;while (F.previousSibling&&F.previousSibling.nodeType==3){F=F.previousSibling;G+=F.length;};E=F;A.End[0]=G;};A.Start=FCKDomTools.GetNodeAddress(D,true).concat(A.Start);A.End=FCKDomTools.GetNodeAddress(E,true).concat(A.End);return A;},MoveToBookmark2:function(A){var B=FCKDomTools.GetNodeFromAddress(this.Window.document,A.Start.slice(0,-1),true);var C=FCKDomTools.GetNodeFromAddress(this.Window.document,A.End.slice(0,-1),true);this.Release(true);this._Range=new FCKW3CRange(this.Window.document);var D=A.Start[A.Start.length-1];var E=A.End[A.End.length-1];while (B.nodeType==3&&D>B.length){if (!B.nextSibling||B.nextSibling.nodeType!=3) break;D-=B.length;B=B.nextSibling;}while (C.nodeType==3&&E>C.length){if (!C.nextSibling||C.nextSibling.nodeType!=3) break;E-=C.length;C=C.nextSibling;};this._Range.setStart(B,D);this._Range.setEnd(C,E);this._UpdateElementInfo();},MoveToPosition:function(A,B){this.SetStart(A,B);this.Collapse(true);},SetStart:function(A,B,C){var D=this._Range;if (!D) D=this._Range=this.CreateRange();switch(B){case 1:D.setStart(A,0);break;case 2:D.setStart(A,A.childNodes.length);break;case 3:D.setStartBefore(A);break;case 4:D.setStartAfter(A);};if (!C) this._UpdateElementInfo();},SetEnd:function(A,B,C){var D=this._Range;if (!D) D=this._Range=this.CreateRange();switch(B){case 1:D.setEnd(A,0);break;case 2:D.setEnd(A,A.childNodes.length);break;case 3:D.setEndBefore(A);break;case 4:D.setEndAfter(A);};if (!C) this._UpdateElementInfo();},Expand:function(A){var B,oSibling;switch (A){case 'inline_elements':if (this._Range.startOffset==0){B=this._Range.startContainer;if (B.nodeType!=1) B=B.previousSibling?null:B.parentNode;if (B){while (FCKListsLib.InlineNonEmptyElements[B.nodeName.toLowerCase()]){this._Range.setStartBefore(B);if (B!=B.parentNode.firstChild) break;B=B.parentNode;}}};B=this._Range.endContainer;var C=this._Range.endOffset;if ((B.nodeType==3&&C>=B.nodeValue.length)||(B.nodeType==1&&C>=B.childNodes.length)||(B.nodeType!=1&&B.nodeType!=3)){if (B.nodeType!=1) B=B.nextSibling?null:B.parentNode;if (B){while (FCKListsLib.InlineNonEmptyElements[B.nodeName.toLowerCase()]){this._Range.setEndAfter(B);if (B!=B.parentNode.lastChild) break;B=B.parentNode;}}};break;case 'block_contents':case 'list_contents':var D=FCKListsLib.BlockBoundaries;if (A=='list_contents'||FCKConfig.EnterMode=='br') D=FCKListsLib.ListBoundaries;if (this.StartBlock&&FCKConfig.EnterMode!='br'&&A=='block_contents') this.SetStart(this.StartBlock,1);else{B=this._Range.startContainer;if (B.nodeType==1){var E=B.childNodes[this._Range.startOffset];if (E) B=FCKDomTools.GetPreviousSourceNode(E,true);else B=B.lastChild||B;}while (B&&(B.nodeType!=1||(B!=this.StartBlockLimit&&!D[B.nodeName.toLowerCase()]))){this._Range.setStartBefore(B);B=B.previousSibling||B.parentNode;}};if (this.EndBlock&&FCKConfig.EnterMode!='br'&&A=='block_contents'&&this.EndBlock.nodeName.toLowerCase()!='li') this.SetEnd(this.EndBlock,2);else{B=this._Range.endContainer;if (B.nodeType==1) B=B.childNodes[this._Range.endOffset]||B.lastChild;while (B&&(B.nodeType!=1||(B!=this.StartBlockLimit&&!D[B.nodeName.toLowerCase()]))){this._Range.setEndAfter(B);B=B.nextSibling||B.parentNode;};if (B&&B.nodeName.toLowerCase()=='br') this._Range.setEndAfter(B);};this._UpdateElementInfo();}},SplitBlock:function(A){var B=A||FCKConfig.EnterMode;if (!this._Range) this.MoveToSelection();if (this.StartBlockLimit==this.EndBlockLimit){var C=this.StartBlock;var D=this.EndBlock;var E=null;if (B!='br'){if (!C){C=this.FixBlock(true,B);D=this.EndBlock;};if (!D) D=this.FixBlock(false,B);};var F=(C!=null&&this.CheckStartOfBlock());var G=(D!=null&&this.CheckEndOfBlock());if (!this.CheckIsEmpty()) this.DeleteContents();if (C&&D&&C==D){if (G){E=new FCKElementPath(this.StartContainer);this.MoveToPosition(D,4);D=null;}else if (F){E=new FCKElementPath(this.StartContainer);this.MoveToPosition(C,3);C=null;}else{this.SetEnd(C,2);var H=this.ExtractContents();D=C.cloneNode(false);D.removeAttribute('id',false);H.AppendTo(D);FCKDomTools.InsertAfterNode(C,D);this.MoveToPosition(C,4);if (FCKBrowserInfo.IsGecko&&!C.nodeName.IEquals(['ul','ol'])) FCKTools.AppendBogusBr(C);}};return {PreviousBlock:C,NextBlock:D,WasStartOfBlock:F,WasEndOfBlock:G,ElementPath:E};};return null;},FixBlock:function(A,B){var C=this.CreateBookmark();this.Collapse(A);this.Expand('block_contents');var D=this.Window.document.createElement(B);this.ExtractContents().AppendTo(D);FCKDomTools.TrimNode(D);if (FCKDomTools.CheckIsEmptyElement(D,function(element) { return element.getAttribute('_fck_bookmark')!='true';})&&FCKBrowserInfo.IsGeckoLike) FCKTools.AppendBogusBr(D);this.InsertNode(D);this.MoveToBookmark(C);return D;},Release:function(A){if (!A) this.Window=null;this.StartNode=null;this.StartContainer=null;this.StartBlock=null;this.StartBlockLimit=null;this.EndNode=null;this.EndContainer=null;this.EndBlock=null;this.EndBlockLimit=null;this._Range=null;this._Cache=null;},CheckHasRange:function(){return!!this._Range;},GetTouchedStartNode:function(){var A=this._Range;var B=A.startContainer;if (A.collapsed||B.nodeType!=1) return B;return B.childNodes[A.startOffset]||B;},GetTouchedEndNode:function(){var A=this._Range;var B=A.endContainer;if (A.collapsed||B.nodeType!=1) return B;return B.childNodes[A.endOffset-1]||B;}};
+FCKDomRange.prototype.MoveToSelection=function(){this.Release(true);this._Range=new FCKW3CRange(this.Window.document);var A=this.Window.document.selection;if (A.type!='Control'){var B=this._GetSelectionMarkerTag(true);var C=this._GetSelectionMarkerTag(false);if (!B&&!C){this._Range.setStart(this.Window.document.body,0);this._UpdateElementInfo();return;};this._Range.setStart(B.parentNode,FCKDomTools.GetIndexOf(B));B.parentNode.removeChild(B);this._Range.setEnd(C.parentNode,FCKDomTools.GetIndexOf(C));C.parentNode.removeChild(C);this._UpdateElementInfo();}else{var D=A.createRange().item(0);if (D){this._Range.setStartBefore(D);this._Range.setEndAfter(D);this._UpdateElementInfo();}}};FCKDomRange.prototype.Select=function(A){if (this._Range) this.SelectBookmark(this.CreateBookmark(true),A);};FCKDomRange.prototype.SelectBookmark=function(A,B){var C=this.CheckIsCollapsed();var D;var E;var F=this.GetBookmarkNode(A,true);if (!F) return;var G;if (!C) G=this.GetBookmarkNode(A,false);var H=this.Window.document.body.createTextRange();H.moveToElementText(F);H.moveStart('character',1);if (G){var I=this.Window.document.body.createTextRange();I.moveToElementText(G);H.setEndPoint('EndToEnd',I);H.moveEnd('character',-1);}else{D=(B||!F.previousSibling||F.previousSibling.nodeName.toLowerCase()=='br')&&!F.nextSibing;E=this.Window.document.createElement('span');E.innerHTML='';F.parentNode.insertBefore(E,F);if (D){F.parentNode.insertBefore(this.Window.document.createTextNode('\ufeff'),F);}};if (!this._Range) this._Range=this.CreateRange();this._Range.setStartBefore(F);F.parentNode.removeChild(F);if (C){if (D){H.moveStart('character',-1);H.select();this.Window.document.selection.clear();}else H.select();FCKDomTools.RemoveNode(E);}else{this._Range.setEndBefore(G);G.parentNode.removeChild(G);H.select();}};FCKDomRange.prototype._GetSelectionMarkerTag=function(A){var B=this.Window.document;var C=B.selection;var D;try{D=C.createRange();}catch (e){return null;};if (D.parentElement().document!=B) return null;D.collapse(A===true);var E='fck_dom_range_temp_'+(new Date()).valueOf()+'_'+Math.floor(Math.random()*1000);D.pasteHTML('');return B.getElementById(E);};
+var FCKDomRangeIterator=function(A){this.Range=A;this.ForceBrBreak=false;this.EnforceRealBlocks=false;};FCKDomRangeIterator.CreateFromSelection=function(A){var B=new FCKDomRange(A);B.MoveToSelection();return new FCKDomRangeIterator(B);};FCKDomRangeIterator.prototype={GetNextParagraph:function(){var A;var B;var C;var D;var E;var F=this.ForceBrBreak?FCKListsLib.ListBoundaries:FCKListsLib.BlockBoundaries;if (!this._LastNode){var B=this.Range.Clone();B.Expand(this.ForceBrBreak?'list_contents':'block_contents');this._NextNode=B.GetTouchedStartNode();this._LastNode=B.GetTouchedEndNode();B=null;};var H=this._NextNode;var I=this._LastNode;this._NextNode=null;while (H){var J=false;var K=(H.nodeType!=1);var L=false;if (!K){var M=H.nodeName.toLowerCase();if (F[M]&&(!FCKBrowserInfo.IsIE||H.scopeName=='HTML')){if (M=='br') K=true;else if (!B&&H.childNodes.length==0&&M!='hr'){A=H;C=H==I;break;};if (B){B.SetEnd(H,3,true);if (M!='br') this._NextNode=FCKDomTools.GetNextSourceNode(H,true,null,I);};J=true;}else{if (H.firstChild){if (!B){B=new FCKDomRange(this.Range.Window);B.SetStart(H,3,true);};H=H.firstChild;continue;};K=true;}}else if (H.nodeType==3){if (/^[\r\n\t ]+$/.test(H.nodeValue)) K=false;};if (K&&!B){B=new FCKDomRange(this.Range.Window);B.SetStart(H,3,true);};C=((!J||K)&&H==I);if (B&&!J){while (!H.nextSibling&&!C){var N=H.parentNode;if (F[N.nodeName.toLowerCase()]){J=true;C=C||(N==I);break;};H=N;K=true;C=(H==I);L=true;}};if (K) B.SetEnd(H,4,true);if ((J||C)&&B){B._UpdateElementInfo();if (B.StartNode==B.EndNode&&B.StartNode.parentNode==B.StartBlockLimit&&B.StartNode.getAttribute&&B.StartNode.getAttribute('_fck_bookmark')) B=null;else break;};if (C) break;H=FCKDomTools.GetNextSourceNode(H,L,null,I);};if (!A){if (!B){this._NextNode=null;return null;};A=B.StartBlock;if (!A&&!this.EnforceRealBlocks&&B.StartBlockLimit.nodeName.IEquals('DIV','TH','TD')&&B.CheckStartOfBlock()&&B.CheckEndOfBlock()){A=B.StartBlockLimit;}else if (!A||(this.EnforceRealBlocks&&A.nodeName.toLowerCase()=='li')){A=this.Range.Window.document.createElement(FCKConfig.EnterMode=='p'?'p':'div');B.ExtractContents().AppendTo(A);FCKDomTools.TrimNode(A);B.InsertNode(A);D=true;E=true;}else if (A.nodeName.toLowerCase()!='li'){if (!B.CheckStartOfBlock()||!B.CheckEndOfBlock()){A=A.cloneNode(false);B.ExtractContents().AppendTo(A);FCKDomTools.TrimNode(A);var O=B.SplitBlock();D=!O.WasStartOfBlock;E=!O.WasEndOfBlock;B.InsertNode(A);}}else if (!C){this._NextNode=A==I?null:FCKDomTools.GetNextSourceNode(B.EndNode,true,null,I);return A;}};if (D){var P=A.previousSibling;if (P&&P.nodeType==1){if (P.nodeName.toLowerCase()=='br') P.parentNode.removeChild(P);else if (P.lastChild&&P.lastChild.nodeName.IEquals('br')) P.removeChild(P.lastChild);}};if (E){var Q=A.lastChild;if (Q&&Q.nodeType==1&&Q.nodeName.toLowerCase()=='br') A.removeChild(Q);};if (!this._NextNode) this._NextNode=(C||A==I)?null:FCKDomTools.GetNextSourceNode(A,true,null,I);return A;}};
+var FCKDocumentFragment=function(A){this._Document=A;this.RootNode=A.createElement('div');};FCKDocumentFragment.prototype={AppendTo:function(A){FCKDomTools.MoveChildren(this.RootNode,A);},AppendHtml:function(A){var B=this._Document.createElement('div');B.innerHTML=A;FCKDomTools.MoveChildren(B,this.RootNode);},InsertAfterNode:function(A){var B=this.RootNode;var C;while((C=B.lastChild)) FCKDomTools.InsertAfterNode(A,B.removeChild(C));}};
+var FCKW3CRange=function(A){this._Document=A;this.startContainer=null;this.startOffset=null;this.endContainer=null;this.endOffset=null;this.collapsed=true;};FCKW3CRange.CreateRange=function(A){return new FCKW3CRange(A);};FCKW3CRange.CreateFromRange=function(A,B){var C=FCKW3CRange.CreateRange(A);C.setStart(B.startContainer,B.startOffset);C.setEnd(B.endContainer,B.endOffset);return C;};FCKW3CRange.prototype={_UpdateCollapsed:function(){this.collapsed=(this.startContainer==this.endContainer&&this.startOffset==this.endOffset);},setStart:function(A,B){this.startContainer=A;this.startOffset=B;if (!this.endContainer){this.endContainer=A;this.endOffset=B;};this._UpdateCollapsed();},setEnd:function(A,B){this.endContainer=A;this.endOffset=B;if (!this.startContainer){this.startContainer=A;this.startOffset=B;};this._UpdateCollapsed();},setStartAfter:function(A){this.setStart(A.parentNode,FCKDomTools.GetIndexOf(A)+1);},setStartBefore:function(A){this.setStart(A.parentNode,FCKDomTools.GetIndexOf(A));},setEndAfter:function(A){this.setEnd(A.parentNode,FCKDomTools.GetIndexOf(A)+1);},setEndBefore:function(A){this.setEnd(A.parentNode,FCKDomTools.GetIndexOf(A));},collapse:function(A){if (A){this.endContainer=this.startContainer;this.endOffset=this.startOffset;}else{this.startContainer=this.endContainer;this.startOffset=this.endOffset;};this.collapsed=true;},selectNodeContents:function(A){this.setStart(A,0);this.setEnd(A,A.nodeType==3?A.data.length:A.childNodes.length);},insertNode:function(A){var B=this.startContainer;var C=this.startOffset;if (B.nodeType==3){B.splitText(C);if (B==this.endContainer) this.setEnd(B.nextSibling,this.endOffset-this.startOffset);FCKDomTools.InsertAfterNode(B,A);return;}else{B.insertBefore(A,B.childNodes[C]||null);if (B==this.endContainer){this.endOffset++;this.collapsed=false;}}},deleteContents:function(){if (this.collapsed) return;this._ExecContentsAction(0);},extractContents:function(){var A=new FCKDocumentFragment(this._Document);if (!this.collapsed) this._ExecContentsAction(1,A);return A;},cloneContents:function(){var A=new FCKDocumentFragment(this._Document);if (!this.collapsed) this._ExecContentsAction(2,A);return A;},_ExecContentsAction:function(A,B){var C=this.startContainer;var D=this.endContainer;var E=this.startOffset;var F=this.endOffset;var G=false;var H=false;if (D.nodeType==3) D=D.splitText(F);else{if (D.childNodes.length>0){if (F>D.childNodes.length-1){D=FCKDomTools.InsertAfterNode(D.lastChild,this._Document.createTextNode(''));H=true;}else D=D.childNodes[F];}};if (C.nodeType==3){C.splitText(E);if (C==D) D=C.nextSibling;}else{if (E==0){C=C.insertBefore(this._Document.createTextNode(''),C.firstChild);G=true;}else if (E>C.childNodes.length-1){C=C.appendChild(this._Document.createTextNode(''));G=true;}else C=C.childNodes[E].previousSibling;};var I=FCKDomTools.GetParents(C);var J=FCKDomTools.GetParents(D);var i,topStart,topEnd;for (i=0;i0&&levelStartNode!=D) levelClone=K.appendChild(levelStartNode.cloneNode(levelStartNode==D));if (!I[k]||levelStartNode.parentNode!=I[k].parentNode){currentNode=levelStartNode.previousSibling;while(currentNode){if (currentNode==I[k]||currentNode==C) break;currentSibling=currentNode.previousSibling;if (A==2) K.insertBefore(currentNode.cloneNode(true),K.firstChild);else{currentNode.parentNode.removeChild(currentNode);if (A==1) K.insertBefore(currentNode,K.firstChild);};currentNode=currentSibling;}};if (K) K=levelClone;};if (A==2){var L=this.startContainer;if (L.nodeType==3){L.data+=L.nextSibling.data;L.parentNode.removeChild(L.nextSibling);};var M=this.endContainer;if (M.nodeType==3&&M.nextSibling){M.data+=M.nextSibling.data;M.parentNode.removeChild(M.nextSibling);}}else{if (topStart&&topEnd&&(C.parentNode!=topStart.parentNode||D.parentNode!=topEnd.parentNode)){var N=FCKDomTools.GetIndexOf(topEnd);if (G&&topEnd.parentNode==C.parentNode) N--;this.setStart(topEnd.parentNode,N);};this.collapse(true);};if(G) C.parentNode.removeChild(C);if(H&&D.parentNode) D.parentNode.removeChild(D);},cloneRange:function(){return FCKW3CRange.CreateFromRange(this._Document,this);}};
+var FCKEnterKey=function(A,B,C,D){this.Window=A;this.EnterMode=B||'p';this.ShiftEnterMode=C||'br';var E=new FCKKeystrokeHandler(false);E._EnterKey=this;E.OnKeystroke=FCKEnterKey_OnKeystroke;E.SetKeystrokes([[13,'Enter'],[SHIFT+13,'ShiftEnter'],[8,'Backspace'],[CTRL+8,'CtrlBackspace'],[46,'Delete']]);this.TabText='';if (D>0||FCKBrowserInfo.IsSafari){while (D--) this.TabText+='\xa0';E.SetKeystrokes([9,'Tab']);};E.AttachToElement(A.document);};function FCKEnterKey_OnKeystroke(A,B){var C=this._EnterKey;try{switch (B){case 'Enter':return C.DoEnter();break;case 'ShiftEnter':return C.DoShiftEnter();break;case 'Backspace':return C.DoBackspace();break;case 'Delete':return C.DoDelete();break;case 'Tab':return C.DoTab();break;case 'CtrlBackspace':return C.DoCtrlBackspace();break;}}catch (e){};return false;};FCKEnterKey.prototype.DoEnter=function(A,B){FCKUndo.SaveUndoStep();this._HasShift=(B===true);var C=FCKSelection.GetParentElement();var D=new FCKElementPath(C);var E=A||this.EnterMode;if (E=='br'||D.Block&&D.Block.tagName.toLowerCase()=='pre') return this._ExecuteEnterBr();else return this._ExecuteEnterBlock(E);};FCKEnterKey.prototype.DoShiftEnter=function(){return this.DoEnter(this.ShiftEnterMode,true);};FCKEnterKey.prototype.DoBackspace=function(){var A=false;var B=new FCKDomRange(this.Window);B.MoveToSelection();if (FCKBrowserInfo.IsIE&&this._CheckIsAllContentsIncluded(B,this.Window.document.body)){this._FixIESelectAllBug(B);return true;};var C=B.CheckIsCollapsed();if (!C){if (FCKBrowserInfo.IsIE&&this.Window.document.selection.type.toLowerCase()=="control"){var D=this.Window.document.selection.createRange();for (var i=D.length-1;i>=0;i--){var E=D.item(i);E.parentNode.removeChild(E);};return true;};return false;};if (FCKBrowserInfo.IsIE){var F=FCKDomTools.GetPreviousSourceElement(B.StartNode,true);if (F&&F.nodeName.toLowerCase()=='br'){var G=B.Clone();G.SetStart(F,4);if (G.CheckIsEmpty()){F.parentNode.removeChild(F);return true;}}};var H=B.StartBlock;var I=B.EndBlock;if (B.StartBlockLimit==B.EndBlockLimit&&H&&I){if (!C){var J=B.CheckEndOfBlock();B.DeleteContents();if (H!=I){B.SetStart(I,1);B.SetEnd(I,1);};B.Select();A=(H==I);};if (B.CheckStartOfBlock()){var K=B.StartBlock;var L=FCKDomTools.GetPreviousSourceElement(K,true,['BODY',B.StartBlockLimit.nodeName],['UL','OL']);A=this._ExecuteBackspace(B,L,K);}else if (FCKBrowserInfo.IsGeckoLike){B.Select();}};B.Release();return A;};FCKEnterKey.prototype.DoCtrlBackspace=function(){FCKUndo.SaveUndoStep();var A=new FCKDomRange(this.Window);A.MoveToSelection();if (FCKBrowserInfo.IsIE&&this._CheckIsAllContentsIncluded(A,this.Window.document.body)){this._FixIESelectAllBug(A);return true;};return false;};FCKEnterKey.prototype._ExecuteBackspace=function(A,B,C){var D=false;if (!B&&C&&C.nodeName.IEquals('LI')&&C.parentNode.parentNode.nodeName.IEquals('LI')){this._OutdentWithSelection(C,A);return true;};if (B&&B.nodeName.IEquals('LI')){var E=FCKDomTools.GetLastChild(B,['UL','OL']);while (E){B=FCKDomTools.GetLastChild(E,'LI');E=FCKDomTools.GetLastChild(B,['UL','OL']);}};if (B&&C){if (C.nodeName.IEquals('LI')&&!B.nodeName.IEquals('LI')){this._OutdentWithSelection(C,A);return true;};var F=C.parentNode;var G=B.nodeName.toLowerCase();if (FCKListsLib.EmptyElements[G]!=null||G=='table'){FCKDomTools.RemoveNode(B);D=true;}else{FCKDomTools.RemoveNode(C);while (F.innerHTML.Trim().length==0){var H=F.parentNode;H.removeChild(F);F=H;};FCKDomTools.LTrimNode(C);FCKDomTools.RTrimNode(B);A.SetStart(B,2,true);A.Collapse(true);var I=A.CreateBookmark(true);if (!C.tagName.IEquals(['TABLE'])) FCKDomTools.MoveChildren(C,B);A.SelectBookmark(I);D=true;}};return D;};FCKEnterKey.prototype.DoDelete=function(){FCKUndo.SaveUndoStep();var A=false;var B=new FCKDomRange(this.Window);B.MoveToSelection();if (FCKBrowserInfo.IsIE&&this._CheckIsAllContentsIncluded(B,this.Window.document.body)){this._FixIESelectAllBug(B);return true;};if (B.CheckIsCollapsed()&&B.CheckEndOfBlock(FCKBrowserInfo.IsGeckoLike)){var C=B.StartBlock;var D=FCKTools.GetElementAscensor(C,'td');var E=FCKDomTools.GetNextSourceElement(C,true,[B.StartBlockLimit.nodeName],['UL','OL','TR'],true);if (D){var F=FCKTools.GetElementAscensor(E,'td');if (F!=D) return true;};A=this._ExecuteBackspace(B,C,E);};B.Release();return A;};FCKEnterKey.prototype.DoTab=function(){var A=new FCKDomRange(this.Window);A.MoveToSelection();var B=A._Range.startContainer;while (B){if (B.nodeType==1){var C=B.tagName.toLowerCase();if (C=="tr"||C=="td"||C=="th"||C=="tbody"||C=="table") return false;else break;};B=B.parentNode;};if (this.TabText){A.DeleteContents();A.InsertNode(this.Window.document.createTextNode(this.TabText));A.Collapse(false);A.Select();};return true;};FCKEnterKey.prototype._ExecuteEnterBlock=function(A,B){var C=B||new FCKDomRange(this.Window);var D=C.SplitBlock(A);if (D){var E=D.PreviousBlock;var F=D.NextBlock;var G=D.WasStartOfBlock;var H=D.WasEndOfBlock;if (F){if (F.parentNode.nodeName.IEquals('li')){FCKDomTools.BreakParent(F,F.parentNode);FCKDomTools.MoveNode(F,F.nextSibling,true);}}else if (E&&E.parentNode.nodeName.IEquals('li')){FCKDomTools.BreakParent(E,E.parentNode);C.MoveToElementEditStart(E.nextSibling);FCKDomTools.MoveNode(E,E.previousSibling);};if (!G&&!H){if (F.nodeName.IEquals('li')&&F.firstChild&&F.firstChild.nodeName.IEquals(['ul','ol'])) F.insertBefore(FCKTools.GetElementDocument(F).createTextNode('\xa0'),F.firstChild);if (F) C.MoveToElementEditStart(F);}else{if (G&&H&&E.tagName.toUpperCase()=='LI'){C.MoveToElementStart(E);this._OutdentWithSelection(E,C);C.Release();return true;};var I;if (E){var J=E.tagName.toUpperCase();if (!this._HasShift&&!(/^H[1-6]$/).test(J)){I=FCKDomTools.CloneElement(E);}}else if (F) I=FCKDomTools.CloneElement(F);if (!I) I=this.Window.document.createElement(A);var K=D.ElementPath;if (K){for (var i=0,len=K.Elements.length;i=0&&(C=B[i--])){if (C.name.length>0){if (C.innerHTML!==''){if (FCKBrowserInfo.IsIE) C.className+=' FCK__AnchorC';}else{var D=FCKDocumentProcessor_CreateFakeImage('FCK__Anchor',C.cloneNode(true));D.setAttribute('_fckanchor','true',0);C.parentNode.insertBefore(D,C);C.parentNode.removeChild(C);}}}}};var FCKPageBreaksProcessor=FCKDocumentProcessor.AppendNew();FCKPageBreaksProcessor.ProcessDocument=function(A){var B=A.getElementsByTagName('DIV');var C;var i=B.length-1;while (i>=0&&(C=B[i--])){if (C.style.pageBreakAfter=='always'&&C.childNodes.length==1&&C.childNodes[0].style&&C.childNodes[0].style.display=='none'){var D=FCKDocumentProcessor_CreateFakeImage('FCK__PageBreak',C.cloneNode(true));C.parentNode.insertBefore(D,C);C.parentNode.removeChild(C);}}};FCKEmbedAndObjectProcessor=(function(){var A=[];var B=function(el){var C=el.cloneNode(true);var D;var E=D=FCKDocumentProcessor_CreateFakeImage('FCK__UnknownObject',C);FCKEmbedAndObjectProcessor.RefreshView(E,el);for (var i=0;i=0;i--) B(G[i]);};var H=function(doc){F('object',doc);F('embed',doc);};return FCKTools.Merge(FCKDocumentProcessor.AppendNew(),{ProcessDocument:function(doc){if (FCKBrowserInfo.IsGecko) FCKTools.RunFunction(H,this,[doc]);else H(doc);},RefreshView:function(placeHolder,original){if (original.getAttribute('width')>0) placeHolder.style.width=FCKTools.ConvertHtmlSizeToStyle(original.getAttribute('width'));if (original.getAttribute('height')>0) placeHolder.style.height=FCKTools.ConvertHtmlSizeToStyle(original.getAttribute('height'));},AddCustomHandler:function(func){A.push(func);}});})();FCK.GetRealElement=function(A){var e=FCKTempBin.Elements[A.getAttribute('_fckrealelement')];if (A.getAttribute('_fckflash')){if (A.style.width.length>0) e.width=FCKTools.ConvertStyleSizeToHtml(A.style.width);if (A.style.height.length>0) e.height=FCKTools.ConvertStyleSizeToHtml(A.style.height);};return e;};if (FCKBrowserInfo.IsIE){FCKDocumentProcessor.AppendNew().ProcessDocument=function(A){var B=A.getElementsByTagName('HR');var C;var i=B.length-1;while (i>=0&&(C=B[i--])){var D=A.createElement('hr');D.mergeAttributes(C,true);FCKDomTools.InsertAfterNode(C,D);C.parentNode.removeChild(C);}}};FCKDocumentProcessor.AppendNew().ProcessDocument=function(A){var B=A.getElementsByTagName('INPUT');var C;var i=B.length-1;while (i>=0&&(C=B[i--])){if (C.type=='hidden'){var D=FCKDocumentProcessor_CreateFakeImage('FCK__InputHidden',C.cloneNode(true));D.setAttribute('_fckinputhidden','true',0);C.parentNode.insertBefore(D,C);C.parentNode.removeChild(C);}}};FCKEmbedAndObjectProcessor.AddCustomHandler(function(A,B){if (!(A.nodeName.IEquals('embed')&&(A.type=='application/x-shockwave-flash'||/\.swf($|#|\?)/i.test(A.src)))) return;B.className='FCK__Flash';B.setAttribute('_fckflash','true',0);});if (FCKBrowserInfo.IsSafari){FCKDocumentProcessor.AppendNew().ProcessDocument=function(A){var B=A.getElementsByClassName?A.getElementsByClassName('Apple-style-span'):Array.prototype.filter.call(A.getElementsByTagName('span'),function(item){ return item.className=='Apple-style-span';});for (var i=B.length-1;i>=0;i--) FCKDomTools.RemoveNode(B[i],true);}};
+var FCKSelection=FCK.Selection={GetParentBlock:function(){var A=this.GetParentElement();while (A){if (FCKListsLib.BlockBoundaries[A.nodeName.toLowerCase()]) break;A=A.parentNode;};return A;},ApplyStyle:function(A){FCKStyles.ApplyStyle(new FCKStyle(A));}};
+FCKSelection.GetType=function(){try{var A=FCKSelection.GetSelection().type;if (A=='Control'||A=='Text') return A;if (this.GetSelection().createRange().parentElement) return 'Text';}catch(e){};return 'None';};FCKSelection.GetSelectedElement=function(){if (this.GetType()=='Control'){var A=this.GetSelection().createRange();if (A&&A.item) return this.GetSelection().createRange().item(0);};return null;};FCKSelection.GetParentElement=function(){switch (this.GetType()){case 'Control':var A=FCKSelection.GetSelectedElement();return A?A.parentElement:null;case 'None':return null;default:return this.GetSelection().createRange().parentElement();}};FCKSelection.GetBoundaryParentElement=function(A){switch (this.GetType()){case 'Control':var B=FCKSelection.GetSelectedElement();return B?B.parentElement:null;case 'None':return null;default:var C=FCK.EditorDocument;var D=C.selection.createRange();D.collapse(A!==false);var B=D.parentElement();return FCKTools.GetElementDocument(B)==C?B:null;}};FCKSelection.SelectNode=function(A){FCK.Focus();this.GetSelection().empty();var B;try{B=FCK.EditorDocument.body.createControlRange();B.addElement(A);}catch(e){B=FCK.EditorDocument.body.createTextRange();B.moveToElementText(A);};B.select();};FCKSelection.Collapse=function(A){FCK.Focus();if (this.GetType()=='Text'){var B=this.GetSelection().createRange();B.collapse(A==null||A===true);B.select();}};FCKSelection.HasAncestorNode=function(A){var B;if (this.GetSelection().type=="Control"){B=this.GetSelectedElement();}else{var C=this.GetSelection().createRange();B=C.parentElement();}while (B){if (B.nodeName.IEquals(A)) return true;B=B.parentNode;};return false;};FCKSelection.MoveToAncestorNode=function(A){var B,oRange;if (!FCK.EditorDocument) return null;if (this.GetSelection().type=="Control"){oRange=this.GetSelection().createRange();for (i=0;i=0;i--){if (C[i]) FCKTableHandler.DeleteRows(C[i]);};return;};var E=FCKTools.GetElementAscensor(A,'TABLE');if (E.rows.length==1){FCKTableHandler.DeleteTable(E);return;};A.parentNode.removeChild(A);};FCKTableHandler.DeleteTable=function(A){if (!A){A=FCKSelection.GetSelectedElement();if (!A||A.tagName!='TABLE') A=FCKSelection.MoveToAncestorNode('TABLE');};if (!A) return;FCKSelection.SelectNode(A);FCKSelection.Collapse();if (A.parentNode.childNodes.length==1) A.parentNode.parentNode.removeChild(A.parentNode);else A.parentNode.removeChild(A);};FCKTableHandler.InsertColumn=function(A){var B=null;var C=this.GetSelectedCells();if (C&&C.length) B=C[A?0:(C.length-1)];if (!B) return;var D=FCKTools.GetElementAscensor(B,'TABLE');var E=B.cellIndex;for (var i=0;i=0;i--){if (B[i]) FCKTableHandler.DeleteColumns(B[i]);};return;};if (!A) return;var C=FCKTools.GetElementAscensor(A,'TABLE');var D=A.cellIndex;for (var i=C.rows.length-1;i>=0;i--){var E=C.rows[i];if (D==0&&E.cells.length==1){FCKTableHandler.DeleteRows(E);continue;};if (E.cells[D]) E.removeChild(E.cells[D]);}};FCKTableHandler.InsertCell=function(A,B){var C=null;var D=this.GetSelectedCells();if (D&&D.length) C=D[B?0:(D.length-1)];if (!C) return null;var E=FCK.EditorDocument.createElement('TD');if (FCKBrowserInfo.IsGeckoLike) FCKTools.AppendBogusBr(E);if (!B&&C.cellIndex==C.parentNode.cells.length-1) C.parentNode.appendChild(E);else C.parentNode.insertBefore(E,B?C:C.nextSibling);return E;};FCKTableHandler.DeleteCell=function(A){if (A.parentNode.cells.length==1){FCKTableHandler.DeleteRows(FCKTools.GetElementAscensor(A,'TR'));return;};A.parentNode.removeChild(A);};FCKTableHandler.DeleteCells=function(){var A=FCKTableHandler.GetSelectedCells();for (var i=A.length-1;i>=0;i--){FCKTableHandler.DeleteCell(A[i]);}};FCKTableHandler._MarkCells=function(A,B){for (var i=0;i=E.height){for (D=F;D0){var L=K.removeChild(K.firstChild);if (L.nodeType!=1||(L.getAttribute('type',2)!='_moz'&&L.getAttribute('_moz_dirty')!=null)){I.appendChild(L);J++;}}};if (J>0) I.appendChild(FCKTools.GetElementDocument(B).createElement('br'));};this._ReplaceCellsByMarker(C,'_SelectedCells',B);this._UnmarkCells(A,'_SelectedCells');this._InstallTableMap(C,B.parentNode.parentNode);B.appendChild(I);if (FCKBrowserInfo.IsGeckoLike&&(!B.firstChild)) FCKTools.AppendBogusBr(B);this._MoveCaretToCell(B,false);};FCKTableHandler.MergeRight=function(){var A=this.GetMergeRightTarget();if (A==null) return;var B=A.refCell;var C=A.tableMap;var D=A.nextCell;var E=FCK.EditorDocument.createDocumentFragment();while (D&&D.childNodes&&D.childNodes.length>0) E.appendChild(D.removeChild(D.firstChild));D.parentNode.removeChild(D);B.appendChild(E);this._MarkCells([D],'_Replace');this._ReplaceCellsByMarker(C,'_Replace',B);this._InstallTableMap(C,B.parentNode.parentNode);this._MoveCaretToCell(B,false);};FCKTableHandler.MergeDown=function(){var A=this.GetMergeDownTarget();if (A==null) return;var B=A.refCell;var C=A.tableMap;var D=A.nextCell;var E=FCKTools.GetElementDocument(B).createDocumentFragment();while (D&&D.childNodes&&D.childNodes.length>0) E.appendChild(D.removeChild(D.firstChild));if (E.firstChild) E.insertBefore(FCKTools.GetElementDocument(D).createElement('br'),E.firstChild);B.appendChild(E);this._MarkCells([D],'_Replace');this._ReplaceCellsByMarker(C,'_Replace',B);this._InstallTableMap(C,B.parentNode.parentNode);this._MoveCaretToCell(B,false);};FCKTableHandler.HorizontalSplitCell=function(){var A=FCKTableHandler.GetSelectedCells();if (A.length!=1) return;var B=A[0];var C=this._CreateTableMap(B.parentNode.parentNode);var D=B.parentNode.rowIndex;var E=FCKTableHandler._GetCellIndexSpan(C,D,B);var F=isNaN(B.colSpan)?1:B.colSpan;if (F>1){var G=Math.ceil(F/2);var H=FCKTools.GetElementDocument(B).createElement('td');if (FCKBrowserInfo.IsGeckoLike) FCKTools.AppendBogusBr(H);var I=E+G;var J=E+F;var K=isNaN(B.rowSpan)?1:B.rowSpan;for (var r=D;r1){B.rowSpan=Math.ceil(E/2);var G=F+Math.ceil(E/2);var H=null;for (var i=D+1;iG) L.insertBefore(K,L.rows[G]);else L.appendChild(K);for (var i=0;i0){var D=B.rows[0];D.parentNode.removeChild(D);};for (var i=0;iF) F=j;if (E._colScanned===true) continue;if (A[i][j-1]==E) E.colSpan++;if (A[i][j+1]!=E) E._colScanned=true;}};for (var i=0;i<=F;i++){for (var j=0;j=0&&C.compareEndPoints('StartToEnd',E)<=0)||(C.compareEndPoints('EndToStart',E)>=0&&C.compareEndPoints('EndToEnd',E)<=0)){B[B.length]=D.cells[i];}}}};return B;};
+var FCKXml=function(){this.Error=false;};FCKXml.GetAttribute=function(A,B,C){var D=A.attributes.getNamedItem(B);return D?D.value:C;};FCKXml.TransformToObject=function(A){if (!A) return null;var B={};var C=A.attributes;for (var i=0;i ';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='';};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,'',E,'>');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 += '