Pārlūkot izejas kodu

创建kmall中网商城项目

project 7 gadi atpakaļ
revīzija
d43195222e
100 mainītis faili ar 27410 papildinājumiem un 0 dzēšanām
  1. 1 0
      README.md
  2. 2 0
      src/backup/.htaccess
  3. 0 0
      src/backup/index.html
  4. 2 0
      src/classes/.htaccess
  5. 333 0
      src/classes/accountlog.php
  6. 382 0
      src/classes/active.php
  7. 227 0
      src/classes/ad.php
  8. 177 0
      src/classes/api.php
  9. 594 0
      src/classes/api/api_resource.php
  10. 39 0
      src/classes/api/article.php
  11. 45 0
      src/classes/api/brand.php
  12. 31 0
      src/classes/api/comment.php
  13. 43 0
      src/classes/api/goods.php
  14. 33 0
      src/classes/api/help.php
  15. 21 0
      src/classes/api/notice.php
  16. 138 0
      src/classes/api/other.php
  17. 30 0
      src/classes/api/seller.php
  18. 179 0
      src/classes/api/ucenter.php
  19. 43 0
      src/classes/area.php
  20. 38 0
      src/classes/article.php
  21. 450 0
      src/classes/cart.php
  22. 128 0
      src/classes/comment_class.php
  23. 123 0
      src/classes/common.php
  24. 212 0
      src/classes/config.php
  25. 655 0
      src/classes/countsum.php
  26. 388 0
      src/classes/dbbackup.php
  27. 231 0
      src/classes/delivery.php
  28. 129 0
      src/classes/expresswaybill.php
  29. 73 0
      src/classes/freight_facade.php
  30. 1079 0
      src/classes/goods_class.php
  31. 126 0
      src/classes/hsms.php
  32. 74 0
      src/classes/keywords.php
  33. 37 0
      src/classes/layoutroute.php
  34. 46 0
      src/classes/log.php
  35. 46 0
      src/classes/mailtemplate.php
  36. 321 0
      src/classes/menu.php
  37. 60 0
      src/classes/menuSeller.php
  38. 73 0
      src/classes/menuUcenter.php
  39. 177 0
      src/classes/mess.php
  40. 163 0
      src/classes/model.php
  41. 29 0
      src/classes/oauthbase.php
  42. 92 0
      src/classes/oauthcore.php
  43. 1747 0
      src/classes/order_class.php
  44. 322 0
      src/classes/payment.php
  45. 156 0
      src/classes/paymentplugin.php
  46. 283 0
      src/classes/photoupload.php
  47. 412 0
      src/classes/plugin.php
  48. 89 0
      src/classes/point.php
  49. 400 0
      src/classes/prorule.php
  50. 87 0
      src/classes/report.php
  51. 42 0
      src/classes/safestrategy.php
  52. 355 0
      src/classes/search_goods.php
  53. 166 0
      src/classes/seller_mess.php
  54. 148 0
      src/classes/sendmail.php
  55. 152 0
      src/classes/sitehelp.php
  56. 74 0
      src/classes/sitemaps.php
  57. 120 0
      src/classes/smstemplate.php
  58. 353 0
      src/classes/statistics.php
  59. 139 0
      src/classes/themeroute.php
  60. 88 0
      src/classes/thumb.php
  61. 52 0
      src/classes/ticket.php
  62. 594 0
      src/classes/util.php
  63. 2 0
      src/config/.htaccess
  64. 67 0
      src/config/config.php
  65. 35 0
      src/config/config_default.php
  66. 44 0
      src/config/site_config.php
  67. 2 0
      src/controllers/.htaccess
  68. 700 0
      src/controllers/block.php
  69. 220 0
      src/controllers/brand.php
  70. 434 0
      src/controllers/comment.php
  71. 34 0
      src/controllers/errors.php
  72. 927 0
      src/controllers/goods.php
  73. 1118 0
      src/controllers/market.php
  74. 914 0
      src/controllers/member.php
  75. 400 0
      src/controllers/message.php
  76. 1535 0
      src/controllers/order.php
  77. 154 0
      src/controllers/pic.php
  78. 140 0
      src/controllers/plugins.php
  79. 1345 0
      src/controllers/seller.php
  80. 1390 0
      src/controllers/simple.php
  81. 837 0
      src/controllers/site.php
  82. 1425 0
      src/controllers/system.php
  83. 83 0
      src/controllers/systemadmin.php
  84. 68 0
      src/controllers/systemseller.php
  85. 996 0
      src/controllers/tools.php
  86. 920 0
      src/controllers/ucenter.php
  87. 45 0
      src/controllers/update.php
  88. 2 0
      src/docs/.htaccess
  89. 1 0
      src/docs/version.php
  90. BIN
      src/favicon.ico
  91. 6 0
      src/index.php
  92. 5 0
      src/language/zh_sc/config.php
  93. 13 0
      src/language/zh_sc/form_validation_lang.php
  94. 12 0
      src/language/zh_sc/goods_edit_lang.php
  95. 2 0
      src/lib/.htaccess
  96. 187 0
      src/lib/core/application_class.php
  97. 112 0
      src/lib/core/cache/cache_class.php
  98. 46 0
      src/lib/core/cache/cache_inte.php
  99. 144 0
      src/lib/core/cache/filecache_class.php
  100. 196 0
      src/lib/core/interceptor_class.php

+ 1 - 0
README.md

@@ -0,0 +1 @@
+# 中网商城系统 kmall

+ 2 - 0
src/backup/.htaccess

@@ -0,0 +1,2 @@
+Order deny,allow
+Deny from all

+ 0 - 0
src/backup/index.html


+ 2 - 0
src/classes/.htaccess

@@ -0,0 +1,2 @@
+Order deny,allow
+Deny from all

+ 333 - 0
src/classes/accountlog.php

@@ -0,0 +1,333 @@
+<?php
+/**
+ * @copyright (c) 2015 www.aircheng.com
+ * @file accountlog.php
+ * @brief 账户日志管理
+ * @author nswe
+ * @date 2015/1/26 11:11:50
+ * @version 3.0.0
+ */
+
+/**
+ * 将对用户余额进行的操作记入account_log表
+ *
+ * $user_id = 用户id
+ *
+ * $log = new AccountLog();
+ * $config=array(
+ *      'user_id'   => 用户ID
+ *      'seller_id' => 商户ID
+ *		'admin_id'  => 管理员ID
+ *		'event'     => 操作类别 withdraw:提现,pay:余额支付,recharge:充值,drawback:退款到余额,commission_withdraw:佣金提现到余额
+ *		'note'      => 备注信息 如果不设置的话则根据event类型自动生成,如果设置了则不再对数据完整性进行检测,比如是否设置了管理员id、订单信息等
+ *		'num'       => 金额     整形或者浮点,正为增加,负为减少
+ * 		'order_no'  => 订单号   drawback类型的log需要这个值
+ * 		'commission_order_id' => 关联订单ID commission_withdraw类型的log需要这个值
+ * 	);
+ * $re = $log->write($config);
+ *
+ * 如果$re是字符串表示错误信息
+ *
+ * @author nswe
+ */
+class AccountLog
+{
+	private $user     = null;
+	private $admin    = null;
+	private $seller   = null;
+	private $config   = null;
+	private $event    = null;
+	private $amount   = 0;
+	private $noteData = "";
+	public  $error    = "";//错误信息
+
+	private $allow_event = array(
+		'recharge'=> 1,//充值到余额
+		'withdraw'=> 2,//从余额提现
+		'pay'     => 3,//从余额支付
+		'drawback'=> 4,//退款到余额
+		'commission_withdraw'=> 5,//佣金提现到余额
+	);
+
+	/**
+	 * 写入日志并且更新账户余额
+	 * @param array $config config数据类型
+	 * @return string|bool
+	 */
+	public function write($config)
+	{
+		if(isset($config['user_id']))
+		{
+			$this->setUser($config['user_id']);
+		}
+		else
+		{
+			$this->error = "用户信息不存在";
+			return false;
+		}
+
+		isset($config['seller_id']) ? $this->setSeller($config['seller_id']) : "";
+		isset($config['admin_id'])  ? $this->setAdmin($config['admin_id'])   : "";
+		isset($config['event'])     ? $this->setEvent($config['event'])      : "";
+
+		if( isset($config['num']) && is_numeric($config['num']) )
+		{
+			$this->amount = abs(round($config['num'],2));
+
+			//金额正负值处理
+			if(in_array($this->allow_event[$this->event],array(2,3)))
+			{
+				$this->amount = '-'.abs($this->amount);
+			}
+		}
+		else
+		{
+			$this->error = "金额必须大于0元";
+			return false;
+		}
+
+		$this->config   = $config;
+		$this->noteData = isset($config['note']) ? $config['note'] : $this->note();
+
+		//写入数据库
+		$finnalAmount = $this->user['balance'] + $this->amount;
+		if($finnalAmount < 0)
+		{
+			$this->error = "用户余额不足";
+			return false;
+		}
+
+		//对用户余额进行更新
+		$memberDB    = new IModel('member');
+		$memberDB->setData(array("balance" => $finnalAmount));
+		$isChBalance = $memberDB->update("user_id = ".$this->user['id']);
+		if(!$isChBalance)
+		{
+			$this->error = "用户余额数据更新失败";
+			return false;
+		}
+
+		$tb_account_log = new IModel("account_log");
+		$insertData = array(
+			'admin_id'  => $this->admin ? $this->admin['id'] : 0,
+			'user_id'   => $this->user['id'],
+			'event'     => $this->allow_event[$this->event],
+			'note'      => $this->noteData,
+			'amount'    => $this->amount,
+			'amount_log'=> $finnalAmount,
+			'type'      => $this->amount >= 0 ? 0 : 1,
+			'time'      => ITime::getDateTime(),
+		);
+		$tb_account_log->setData($insertData);
+		$result = $tb_account_log->add();
+
+		//后台管理员操作记录
+		if($insertData['admin_id'])
+		{
+			$logObj = new log('db');
+			$logObj->write('operation',array("管理员:".$this->admin['admin_name'],"对账户金额进行了修改",$insertData['note']));
+		}
+		return $result;
+	}
+
+	//设置用户信息
+	private function setUser($user_id)
+	{
+		$user_id = intval($user_id);
+		$query = new IQuery("user AS u");
+		$query->join = "left join member AS m ON u.id = m.user_id";
+		$query->where = "u.id = {$user_id} ";
+
+		$user = $query->find();
+		if(!$user)
+		{
+			throw new IException("用户信息不存在");
+		}
+		else
+		{
+			$this->user = current($user);
+		}
+		return $this;
+	}
+
+	/**
+	 * 设置管理员信息
+	 *
+	 * @param int $admin_id
+	 * @return Object
+	 */
+	private function setAdmin($admin_id)
+	{
+		$admin_id = intval($admin_id);
+		$tb_admin = new IModel("admin");
+		$admin = $tb_admin->getObj(" id = {$admin_id} ");
+		if(!$admin)
+		{
+			throw new IException("管理员信息不存在");
+		}
+		else
+		{
+			$this->admin = $admin;
+		}
+		return $this;
+	}
+
+	/**
+	 * 设置商户信息
+	 *
+	 * @param int $admin_id
+	 * @return Object
+	 */
+	private function setSeller($seller_id)
+	{
+		$admin_id  = intval($seller_id);
+		$sellerDB  = new IModel("seller");
+		$sellerRow = $sellerDB->getObj(" id = {$seller_id} ");
+		if(!$sellerRow)
+		{
+			throw new IException("商家信息不存在");
+		}
+		else
+		{
+			$this->seller = $sellerRow;
+		}
+		return $this;
+	}
+
+	/**
+	 * 设置操作类别
+	 *
+	 * @param string $event_key
+	 * @return Object
+	 */
+	private function setEvent($event_key)
+	{
+		if(!isset($this->allow_event[$event_key]))
+		{
+			throw new IException("事件未定义");
+		}
+		else
+		{
+			$this->event = $event_key;
+		}
+		return $this;
+	}
+
+	/**
+	 * 生成note信息
+	 */
+	private function note()
+	{
+		$note = "";
+		switch($this->event)
+		{
+			//提现
+			case 'withdraw':
+			{
+				if($this->admin == null)
+				{
+					throw new IException("管理员信息不存在,无法提现");
+				}
+				$note .= "管理员[{$this->admin['admin_name']}]给用户[{$this->user['username']}]提现,金额:{$this->amount}元";
+			}
+			break;
+
+			//支付
+			case 'pay':
+			{
+				$note .= "用户[{$this->user['username']}]使用余额支付购买,订单[{$this->config['order_no']}],金额:{$this->amount}元";
+			}
+			break;
+
+			//充值
+			case 'recharge':
+			{
+				if($this->admin)
+				{
+					$note .= "管理员[{$this->admin['admin_name']}]给";
+				}
+				$note .= "用户[{$this->user['username']}]充值,金额:{$this->amount}元";
+			}
+			break;
+
+			//退款
+			case 'drawback':
+			{
+				if(!isset($this->config['order_no']))
+				{
+					throw new IException("退款操作未设置订单号");
+				}
+
+				if($this->seller)
+				{
+					$note .= "商户[{$this->seller['seller_name']}]操作";
+				}
+
+				if($this->admin)
+				{
+					$note .= "管理员[{$this->admin['admin_name']}]操作";
+				}
+				$note .= "订单[{$this->config['order_no']}]退款到用户[{$this->user['username']}]余额,金额:{$this->amount}元";
+			}
+			break;
+
+			//佣金提现到余额
+			case 'commission_withdraw':
+			{
+				if (is_null($this->admin))
+				{
+					throw new IException("管理员信息不存在,无法进行佣金提现操作");
+				}
+				elseif($this->admin)
+				{
+					$note .= "管理员[{$this->admin['admin_name']}]";
+				}
+				$note .= "给用户[{$this->user['username']}]佣金提现,金额:{$this->amount}元,关联订单ID[{$this->config['commission_order_id']}]";
+			}
+			break;
+
+			default:
+			{
+				throw new IException("未定义事件类型");
+			}
+		}
+		return $note;
+	}
+
+	/**
+	 * @brief 商户结算单模板
+	 * @param array $countData 替换的数据
+	 */
+	public static function sellerBillTemplate($countData = null)
+	{
+		$replaceData = array(
+			'{startTime}'        => $countData['start_time'],
+			'{endTime}'          => $countData['end_time'],
+			'{orderAmountPrice}' => $countData['orderAmountPrice'],
+			'{refundFee}'        => $countData['refundFee'],
+			'{commissionFee}'    => $countData['commissionFee'],
+			'{countFee}'         => $countData['countFee'],
+			'{orgCountFee}'      => $countData['orgCountFee'],
+			'{orderNum}'         => $countData['orderNum'],
+			'{platformFee}'      => $countData['platformFee'],
+			'{orderNoList}'      => join(",",$countData['orderNoList']),
+			'{commissionPer}'    => $countData['commissionPer'],
+			'{commission}'       => $countData['commission'],
+		);
+
+		$templateString = "结算起止时间:【{startTime}】到【{endTime}】,订单号:【{orderNoList}】,订单数量共计:【{orderNum}单】,商家实际结算金额:【¥{countFee}】,结算金额计算明细:【订单总金额:¥{orderAmountPrice}】-【退款总金额:¥{refundFee}】-【分销佣金总金额:¥{commissionFee}】+【平台促销活动金额:¥{platformFee}】-【结算手续费:¥{commission}】";
+		return strtr($templateString,$replaceData);
+	}
+
+    //[账户余额] 提现状态判定
+    public static function getWithdrawStatus($status)
+    {
+    	$data = array(
+    		'0'  => '未处理',
+    		'-1' => '提现失败',
+    		'1'  => '处理中',
+    		'2'  => '提现成功',
+    	);
+    	return isset($data[$status]) ? $data[$status] : '未知状态';
+    }
+}

+ 382 - 0
src/classes/active.php

@@ -0,0 +1,382 @@
+<?php
+/**
+ * @copyright Copyright(c) 2015-2016 aircheng.com
+ * @file active.php
+ * @brief 促销活动处理类
+ * @author nswe
+ * @date 2016/6/20 14:59:38
+ * @version 4.5
+ */
+class Active
+{
+	//活动的类型,groupon(团购),time(限时抢购)
+	private $promo;
+
+	//参加活动的用户ID
+	private $user_id;
+
+	//活动的ID编号
+	private $active_id;
+
+	//商品ID 或 货品ID
+	private $id;
+
+	//goods 或 product
+	private $type;
+
+	//购买数量
+	private $buy_num;
+
+	//原始的商品或者货品数据
+	public $originalGoodsInfo;
+
+	//活动价格
+	public $activePrice;
+
+	//活动类型和入库ID的对应关系
+	public static $typeToIdMapping = array('groupon' => 1,'time' => 2);
+
+	/**
+	 * @brief 构造函数创建活动
+	 * @param $promo string 活动的类型,groupon(团购),time(限时抢购)
+	 * @param $activeId int 活动的ID编号
+	 * @param $user_id int 用户的ID编号
+	 * @param $id  int 根据$type的不同而表示:商品id,货品id
+	 * @param $type string 商品:goods; 货品:product
+	 * @param $buy_num int 购买的数量;默认1
+	 */
+	public function __construct($promo,$active_id,$user_id = 0,$id,$type = "goods",$buy_num = 1)
+	{
+		$this->promo     = $promo;
+		$this->active_id = $active_id;
+		$this->user_id   = $user_id;
+		$this->id        = $id;
+		$this->type      = $type;
+		$this->buy_num   = $buy_num;
+	}
+
+	/**
+	 * @brief 检查活动的合法性
+	 * @param int $order_id 订单ID
+	 * @return string(有错误) or true(处理正确)
+	 */
+	public function checkValid($order_id = '')
+	{
+		if(!$this->id)
+		{
+			return "商品ID不存在";
+		}
+		$goodsData = ($this->type == 'product') ? Api::run('getProductInfo',array('#id#',$this->id)) : Api::run('getGoodsInfo',array('#id#',$this->id));
+
+		//库存判断
+		if(!$goodsData || $this->buy_num <= 0 || $this->buy_num > $goodsData['store_nums'])
+		{
+			return "购买的数量不正确或大于商品的库存量";
+		}
+
+		$this->originalGoodsInfo = $goodsData;
+		$this->activePrice       = $goodsData['sell_price'];
+		$goods_id                = $goodsData['goods_id'];
+
+		//具体促销活动的合法性判断
+		switch($this->promo)
+		{
+			//团购
+			case "groupon":
+			{
+				if(!$this->user_id)
+				{
+					return "参加团购活动请您先登录";
+				}
+
+				$regimentRow = Api::run('getRegimentRowById',array("#id#",$this->active_id));
+				if($regimentRow)
+				{
+					if($regimentRow['goods_id'] != $goodsData['goods_id'])
+					{
+						return "该商品没有参与团购活动";
+					}
+
+					if($regimentRow['store_nums'] <= $regimentRow['sum_count'])
+					{
+						return "团购商品已经销售一空";
+					}
+
+					if($this->buy_num + $regimentRow['sum_count'] > $regimentRow['store_nums'])
+					{
+						return "当前团购库存不足,无法购买";
+					}
+
+					//检查团购订单
+					$orderDB   = new IModel('order as o,order_goods as og');
+					$orderData = $orderDB->query('o.user_id = '.$this->user_id.' and o.type = 1 and o.id = og.order_id and active_id = '.$this->active_id);
+					$hasBugNum = 0;
+					foreach($orderData as $key => $val)
+					{
+						//此ID的订单不作为统计判断,用于已下单后支付时候的判断情况
+						if($order_id && $val['order_id'] == $order_id)
+						{
+							continue;
+						}
+						$orderStatus = Order_class::getOrderStatus($val);
+						if(in_array($orderStatus,array(2,1,11)))
+						{
+							return "您参与的该团购订单还没有完成";
+						}
+
+						if(in_array($orderStatus,array(3,4,6)))
+						{
+							$hasBugNum += $val['goods_nums'];
+						}
+					}
+
+					//批量购买(薄利多销)
+					if($regimentRow['limit_min_count'] > 0)
+					{
+						if($this->buy_num < $regimentRow['limit_min_count'])
+						{
+							return "购买数量必须超过 ".$regimentRow['limit_min_count']." 件才能下单";
+						}
+					}
+
+					//限制购买(限购,要多人参与)
+					if($regimentRow['limit_max_count'] > 0)
+					{
+						if($this->buy_num > $regimentRow['limit_max_count'])
+						{
+							return "购买数量不能超过 ".$regimentRow['limit_max_count']." 件";
+						}
+
+						if(($hasBugNum + $this->buy_num) > $regimentRow['limit_max_count'])
+						{
+							return "此团购为限购活动,您累计购买数量不能超过".$regimentRow['limit_max_count'];
+						}
+					}
+
+					if($this->buy_num > $regimentRow['store_nums'])
+					{
+						return "购买数量超过了团购剩余量";
+					}
+
+					$this->activePrice = $regimentRow['regiment_price'];
+				}
+				else
+				{
+					return "当前时间段内不存在此团购活动";
+				}
+				return true;
+			}
+			break;
+
+			//抢购
+			case "time":
+			{
+				$promotionRow = Api::run('getPromotionRowById',array("#id#",$this->active_id));
+				if($promotionRow)
+				{
+					if($promotionRow['condition'] != $goodsData['goods_id'])
+					{
+						return "该商品没有参与抢购活动";
+					}
+
+					$memberObj = new IModel('member');
+					$memberRow = $memberObj->getObj('user_id = '.$this->user_id,'group_id');
+					if($promotionRow['user_group'] == 'all' || (isset($memberRow['group_id']) && stripos(','.$promotionRow['user_group'].',',$memberRow['group_id'])!==false))
+					{
+						$this->activePrice = $promotionRow['award_value'];
+					}
+					else
+					{
+						return "此活动仅限指定的用户组";
+					}
+				}
+				else
+				{
+					return "不存在此限时抢购活动";
+				}
+				return true;
+			}
+			break;
+		}
+		return "未知促销活动";
+	}
+
+	/**
+	 * @brief 促销活动对应order_type的值
+	 */
+	public function getOrderType()
+	{
+		$result = self::$typeToIdMapping;
+		return isset($result[$this->promo]) ? $result[$this->promo] : 0;
+	}
+
+	/**
+	 * @brief 订单付款后的回调
+	 * @param $orderNo string 订单号
+	 * @param $orderType 订单类型 1:团购; 2:抢购;
+	 */
+	public static function payCallback($orderNo,$orderType)
+	{
+		switch($orderType)
+		{
+			//团购
+			case "1":
+			{
+				$tableModel = new IModel('order as o,order_goods as og');
+				$orderRow   = $tableModel->getObj("o.order_no = '{$orderNo}' and o.id = og.order_id and o.type = 1","og.goods_nums,o.active_id");
+				if($orderRow)
+				{
+					$regimentModel = new IModel('regiment');
+					$regimentModel->setData(array('sum_count' => 'sum_count + '.$orderRow['goods_nums']));
+					$regimentModel->update('id = '.$orderRow['active_id'],array('sum_count'));
+				}
+			}
+			break;
+
+			//抢购
+			case "2":
+			{
+
+			}
+			break;
+		}
+	}
+
+	//获取活动数据
+	public function data()
+	{
+		switch($this->promo)
+		{
+			case "groupon":
+			{
+				$data = Api::run("getRegimentRowById",array("#id#",$this->active_id));
+				if($data && $data['goods_id'] ==  $this->id)
+				{
+					return $data;
+				}
+				return "团购活动不存在";
+			}
+			break;
+
+			case "time":
+			{
+				$data = Api::run("getPromotionRowById",array("#id#",$this->active_id));
+				if($data && $data['condition'] == $this->id)
+				{
+					return $data;
+				}
+				return "限时抢购活动不存在";
+			}
+			break;
+		}
+	}
+
+	/**
+	 * @brief 订单退款后的回调
+	 * @param $orderNo string 订单号
+	 * @param $orderType 订单类型 1:团购; 2:抢购;
+	 */
+	public static function refundCallback($orderNo,$orderType)
+	{
+		switch($orderType)
+		{
+			//团购
+			case "1":
+			{
+				$tableModel = new IModel('order as o,order_goods as og');
+				$orderRow   = $tableModel->getObj("o.order_no = '{$orderNo}' and o.id = og.order_id and o.type = 1","og.goods_nums,o.active_id");
+				if($orderRow)
+				{
+					$regimentModel = new IModel('regiment');
+					$regimentModel->setData(array('sum_count' => 'sum_count - '.$orderRow['goods_nums']));
+					$regimentModel->update('id = '.$orderRow['active_id'],array('sum_count'));
+				}
+			}
+			break;
+
+			//抢购
+			case "2":
+			{
+
+			}
+			break;
+		}
+	}
+
+	/**
+	 * @brief 团购活动的状态
+	 * @param array $row 表数据
+	 * @param string
+	 */
+	public static function statusRegiment($row)
+	{
+		if($row['is_close'] == 1)
+		{
+			return '关闭';
+		}
+
+		if($row['is_close'] == 2)
+		{
+			return '待审核';
+		}
+
+		$nowTime = time();
+		if($nowTime < strtotime($row['start_time']))
+		{
+			return '未开始';
+		}
+
+		if($nowTime > strtotime($row['end_time']))
+		{
+			return '已过期';
+		}
+
+		$goodsRow = Api::run('getGoodsInfo',array('#id#',$row['goods_id']));
+		if(!$goodsRow)
+		{
+			return '商品不存在';
+		}
+
+		if($goodsRow['is_del'] != 0)
+		{
+			return '商品未上架';
+		}
+		return '正常';
+	}
+
+	/**
+	 * @brief 抢购活动的状态
+	 * @param array $row 表数据
+	 * @param string
+	 */
+	public static function statusTime($row)
+	{
+		if($row['is_close'] == 1)
+		{
+			return '关闭';
+		}
+
+		$nowTime = time();
+		if($nowTime < strtotime($row['start_time']))
+		{
+			return '未开始';
+		}
+
+		if($nowTime > strtotime($row['end_time']))
+		{
+			return '已过期';
+		}
+
+		$goodsRow = Api::run('getGoodsInfo',array('#id#',$row['condition']));
+		if(!$goodsRow)
+		{
+			return '商品不存在';
+		}
+
+		if($goodsRow['is_del'] != 0)
+		{
+			return '商品未上架';
+		}
+		return '正常';
+	}
+}

+ 227 - 0
src/classes/ad.php

@@ -0,0 +1,227 @@
+<?php
+/**
+ * @copyright (c) 2011 aircheng.com
+ * @file ad.php
+ * @brief 关于广告管理
+ * @author chendeshan
+ * @date 2011-02-14
+ * @version 0.6
+ */
+
+/**
+ * @class article
+ * @brief 广告管理模块
+ */
+class Ad
+{
+	//是否加载过js
+	private static $isLoadJs = false;
+
+	//当广告无数据时,是否加载默认的广告位数据
+	private static $isDefault = false;
+
+	/**
+	 * @brief 广告类型展示解析
+	 * @param $type int 类型
+	 * @return string 类型字符串
+	 */
+	public static function showType($type)
+	{
+		switch($type)
+		{
+			case "1":
+			$str = '图片';
+			break;
+
+			case "2":
+			$str = 'flash';
+			break;
+
+			case "3":
+			$str = '文字';
+			break;
+
+			case "4":
+			$str = '代码';
+			break;
+
+			case "5":
+			$str = '幻灯片';
+			break;
+		}
+		return $str;
+	}
+
+	/**
+	 * @brief 展示制定广告位的广告内容
+	 * @param $position mixed 广告位ID 或者 广告位名称
+	 * @param $goods_cat_id 商品分类ID
+	 * @return string
+	 */
+	public static function show($position,$goods_cat_id = 0)
+	{
+		$positionObject = array();
+		$adArray        = array();
+
+		$positionObject = self::getPositionInfo($position);
+		if($positionObject)
+		{
+			$adList = self::getAdList($positionObject['id'],$goods_cat_id);
+			foreach($adList as $key => $val)
+			{
+				$val['width']  = $positionObject['width'];
+				$val['height'] = $positionObject['height'];
+				$adArray[] = self::display($val);
+			}
+		}
+
+		//有广告内容数据
+		if($adArray)
+		{
+			$positionJson = JSON::encode($positionObject);
+			$adJson       = JSON::encode($adArray);
+
+			//引入 adloader js类库
+			$loadJs = '';
+			if(self::$isLoadJs == false)
+			{
+				$loadJs = IJSPackage::load('admanage');
+				self::$isLoadJs = true;
+			}
+
+			$adPositionJsId = md5("AD_{$position}_{$goods_cat_id}");
+			//生成HTML代码
+			$htmlOutput =
+<<< OEF
+			{$loadJs}
+			<div id='{$adPositionJsId}' class='admanage'></div>
+			<script type='text/javascript'>
+				(new adLoader()).load({$positionJson},{$adJson},"{$adPositionJsId}");
+			</script>
+OEF;
+			echo $htmlOutput;
+		}
+		//获取默认广告数据
+		else if(self::$isDefault == true)
+		{
+			$thumbImg = Api::run('getAdRow',$position.$goods_cat_id);
+			if($thumbImg)
+			{
+				preg_match("/([\d%]+)\*(\d+)/",$position,$match);
+				if(isset($match[2]))
+				{
+					$width  = stripos($match[1],"%") ? $match[1] : $match[1].'px';
+					$height = stripos($match[2],"%") ? $match[2] : $match[2].'px';
+					echo '<div class="admanage"><img src="'.$thumbImg.'" style="width:'.$width.';height:'.$height.'" /></div>';
+				}
+			}
+		}
+	}
+
+	/**
+	 * @brief 展示广告位数据
+	 * @param $adData array 广告数据
+	 * @return string
+	 */
+	private static function display($adData)
+	{
+		$result = array();
+		$linkHtml = $adData['link'] ? "onclick=window.open('".IUrl::creatUrl($adData['link'])."')" : "";
+
+		$size       = array();
+		$configSize = array("width" => self::getSize($adData['width']),"height" => self::getSize($adData['height']));
+		$configSize = array_filter($configSize);
+		foreach($configSize as $key => $val)
+		{
+			$size[] = $key.":".$val;
+		}
+		switch($adData['type'])
+		{
+			//图片
+			case 1:
+			{
+				$result = array
+				(
+					'type' => 1,
+					'data' => '<img src="'.IUrl::creatUrl("").$adData['content'].'" style="cursor:pointer;'.join(";",$size).'" '.$linkHtml.' />'
+				);
+			}
+			break;
+
+			//flash
+			case 2:
+			{
+				$result = array
+				(
+					'type' => 2,
+					'data' => '<object style="cursor:pointer;" '.$linkHtml.' classid="clsid:D27CDB6E-AE6D-11CF-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0" '.join(";",$size).' hspace="0" vspace="0" border="0" align="left"><param name="movie" value="'.IUrl::creatUrl("").$adData['content'].'"><param name="quality" value="high"><param name="wmode" value="transparent"><param name="scale" value="noborder"><embed src="'.IUrl::creatUrl("").$adData['content'].'" quality="high" wmode="transparent" scale="noborder" '.$size.' hspace="0" vspace="0" border="0" align="left" type="application/x-shockwave-flash" luginspage="http://www.macromedia.com/go/getflashplayer"></embed></object>'
+				);
+			}
+			break;
+
+			//文字
+			case 3:
+			{
+				$result = array
+				(
+					'type' => 3,
+					'data' => '<label style="cursor:pointer;'.join(";",$size).'" '.$linkHtml.'>'.$adData['content'].'</label>'
+				);
+			}
+			break;
+
+			//代码
+			case 4:
+			{
+				$result = array
+				(
+					'type' => 4,
+					'data' => '<label style="cursor:pointer;'.join(";",$size).'" '.$linkHtml.'>'.$adData['content'].'</label>'
+				);
+			}
+			break;
+		}
+		return $result;
+	}
+
+	/**
+	 * @brief 获取广告位置的信息
+	 * @param $position mixed 广告位ID 或者 广告位名称
+	 * @return array
+	 */
+	public static function getPositionInfo($position)
+	{
+		$adPositionDB = new IModel("ad_position");
+		if(is_int($position))
+		{
+			return $adPositionDB->getObj("id={$position} AND `status`=1");
+		}
+		else
+		{
+			return $adPositionDB->getObj("name='{$position}' AND `status`=1");
+		}
+	}
+
+	/**
+	 * @brief 获取当前时间段正在使用的广告数据
+	 * @param $position int 广告位ID
+	 * @param $goods_cat_id 商品分类ID
+	 * @return array
+	 */
+	public static function getAdList($position,$goods_cat_id = 0)
+	{
+		$now    = date("Y-m-d H:i:s",ITime::getNow());
+		$adDB   = new IModel("ad_manage");
+		return $adDB->query("position_id={$position} and goods_cat_id = {$goods_cat_id} and start_time < '{$now}' AND end_time > '{$now}' ORDER BY `order` ASC ");
+	}
+
+	//获取尺寸
+	public static function getSize($value)
+	{
+		if(is_numeric($value) && $value > 0)
+		{
+			return $value."px";
+		}
+		return $value;
+	}
+}

+ 177 - 0
src/classes/api.php

@@ -0,0 +1,177 @@
+<?php
+/**
+ * @copyright (c) 2011 aircheng.com
+ * @file api.php
+ * @brief api入口类
+ * @author chendeshan
+ * @date 2011-9-29
+ * @version 0.6
+ */
+define('API_PATH',dirname(__FILE__).'/api/');
+/**
+ * @class Api
+ * @brief api处理类
+ *
+ * $data = Api::run(接口名字,参数...) 接口名字定义于 api_resource.php 文件中,有2种方式即:query标签式 和 class 自定义式
+ * 其中的参数是以匿名的方式传送到接口里面的,在query标签式里面可以传入int类型,表示显示的数量如10;除此之外则是排序字段如 'id+'或'id-'
+ * 在class自定义式里面则是根据
+ * 具体的函数定义去传递参数
+ */
+class Api
+{
+	//已经存在的api对象集[单例]
+	private static $apiInstance = array();
+
+	//api资源配置信息[单例]
+	private static $apiResource = array();
+
+    /**
+     * @brief api调用接口
+     * @param string $apiName API名称
+     * @return mixed
+     */
+	public static function run($apiName)
+	{
+		//载入api资源配置信息
+		if(empty(self::$apiResource))
+		{
+			self::$apiResource = include(API_PATH.'api_resource.php');
+
+			//载入主题config中定义的api
+			$themeConfig = IWeb::$app->getController()->getViewPath()."config.php";
+			if(is_file($themeConfig) && ($themeApi = include($themeConfig)) && isset($themeApi['api']) && is_array($themeApi['api']) && $themeApi['api'])
+			{
+				self::$apiResource = array_merge(self::$apiResource,$themeApi['api']);
+			}
+		}
+
+		//资源配置信息中不存在当前调用的API
+		if(!isset(self::$apiResource[$apiName]))
+		{
+			self::error($apiName,'api is undefined');
+		}
+
+		//匿名参数处理
+		$agumentsArray = func_get_args();
+		array_shift($agumentsArray);
+
+		$apiConf = self::$apiResource[$apiName];
+
+		//1,单纯的数据库读取方式
+		if(isset($apiConf['query']) && !empty($apiConf['query']))
+		{
+			return self::query($apiConf['query'],$agumentsArray);
+		}
+		//2,自定义处理方式
+		else
+		{
+			$fileName   = isset($apiConf['file'])  ? $apiConf['file']  : '';
+			$className  = isset($apiConf['class']) ? $apiConf['class'] : '';
+			$methodName = $apiName;
+
+			if(!$fileName || !$className)
+			{
+				self::error($apiName,'param is lack');
+			}
+
+			//如果当前API中的自定义处理对象已经存在,则直接调用 [缓存]
+			if(isset(self::$apiInstance[$className]) && (self::$apiInstance[$className] instanceof $className))
+			{
+				return call_user_func_array(array(self::$apiInstance[$className],$methodName),$agumentsArray);
+			}
+			//自定义对象不存在则需要创建
+			else
+			{
+				if(file_exists(API_PATH.$fileName))
+				{
+					include(API_PATH.$fileName);
+					if(!class_exists($className))
+					{
+						self::error($apiName,'class is not exists');
+					}
+
+					$apiObj = new $className;
+					self::$apiInstance[$className] = $apiObj;
+					return call_user_func_array(array($apiObj,$methodName),$agumentsArray);
+				}
+				else
+				{
+					self::error($apiName,'file is not exists');
+				}
+			}
+		}
+	}
+
+    /**
+     * @brief 单纯数据库查询api统一处理方法
+     * @param array $queryInfo 数据查询配置信息
+     * @param array $aguments  排序和限制条数(order,limit)
+     * @return array
+     */
+	private static function query($queryInfo,$aguments)
+	{
+		//参数重置order,limit参数
+		if($aguments)
+		{
+			foreach($aguments as $param)
+			{
+				if(is_numeric($param))
+				{
+					$queryInfo['limit'] = $param;
+				}
+				else if(is_array($param))
+				{
+					//分页模式
+					if($param[0] == 'page')
+					{
+						unset($queryInfo['limit']);
+						$queryInfo['page']  = $param[1];
+					}
+					else
+					{
+						$queryInfo['where'] = strtr($queryInfo['where'],array($param[0] => $param[1]));
+					}
+				}
+				else
+				{
+					$queryInfo['order'] = str_replace(array('+','-'),array(' asc',' desc'),$param);
+				}
+			}
+		}
+
+		$tableObj = new IQuery($queryInfo['name']);
+		unset($queryInfo['name']);
+
+		foreach($queryInfo as $key => $val)
+		{
+			$tableObj->$key = $val;
+		}
+
+		//存在分页
+		if(isset($queryInfo['page']) && $queryInfo['page'])
+		{
+			return $tableObj;
+		}
+		//没有分页
+		else
+		{
+			$dataResult = $tableObj->find();
+			if(isset($queryInfo['type']) && $queryInfo['type'] == 'row' && $dataResult)
+			{
+				$dataResult = current($dataResult);
+			}
+			return $dataResult;
+		}
+	}
+
+    /**
+     * @brief api错误处理
+     * @param string $apiName api名称
+     * @param string $message 错误信息
+     * @return Error
+     */
+	private static function error($apiName,$message)
+	{
+		IError::show(403,"API of ".$apiName." is called error , ".$message);
+	}
+}

+ 594 - 0
src/classes/api/api_resource.php

@@ -0,0 +1,594 @@
+<?php
+return array(
+	//取商品数据
+	'getGoodsInfo' => array(
+		'query' => array(
+			'name'   => 'goods as go',
+			'where'  => 'go.id = #id# and go.is_del = 0',
+			'fields' => 'go.name,go.id as goods_id,go.img,go.sell_price,go.point,go.weight,go.store_nums,go.exp,go.goods_no,0 as product_id,go.seller_id,go.is_delivery_fee,go.is_del',
+			'type'   => 'row',
+		)
+	),
+	//取货品数据
+	'getProductInfo' => array(
+		'query' => array(
+			'name'   => 'goods as go,products as pro',
+			'where'  => 'pro.id = #id# and pro.goods_id = go.id and go.is_del = 0',
+			'fields' => 'pro.sell_price,pro.weight,pro.id as product_id,pro.spec_array,pro.goods_id,pro.store_nums,pro.products_no as goods_no,go.name,go.point,go.exp,go.img,go.seller_id,go.is_delivery_fee,go.is_del',
+			'type'   => 'row',
+		)
+	),
+	//取文章置顶列表
+	'getArtList' => array(
+		'query' => array(
+			'name' => 'article',
+			'where' => 'visibility = 1 and top = 1',
+			'order' => 'sort ASC',
+			'fields'=> 'title,id,style,color,create_time',
+			'limit' => '10'
+		)
+	),
+	//团购列表
+	'getRegimentList' => array(
+		'query' => array(
+			'name'  => 'regiment as r',
+			'join'  => 'left join goods as go on r.goods_id = go.id',
+			'where' => 'r.is_close = 0 and NOW() between r.start_time and r.end_time and go.is_del = 0',
+			'order' => 'r.sort asc',
+			'fields'=> 'r.*',
+		)
+	),
+	//团购列表
+	'getEverRegimentList' => array(
+		'query' => array(
+			'name' => 'regiment',
+			'where' => 'is_close = 0 and NOW() > end_time',
+			'order' => 'sort asc',
+		)
+	),
+	 //椐据ID团购
+	'getRegimentRowById' => array(
+		'query' => array(
+			'name'  => 'regiment',
+			'where' => 'id = #id# and NOW() between start_time and end_time and is_close = 0',
+			'type'  => 'row',
+		)
+	),
+	//限时抢购列表
+	'getPromotionList'=> array(
+		'query' => array(
+			'name' => 'promotion as p',
+			'join' => 'left join goods as go on go.id = p.condition',
+			'fields'=>'p.end_time,go.img as img,p.name as name,p.award_value as award_value,go.id as goods_id,p.id as p_id,p.start_time',
+			'where'=>'p.type = 1 and p.is_close = 0 and go.is_del = 0 and NOW() between start_time and end_time AND go.id is not null',
+			'order'=>'p.sort asc',
+			'limit'=>'10'
+		)
+	),
+	//根据ID限时抢购
+	'getPromotionRowById'=> array(
+		'query' => array(
+			'name'  => 'promotion',
+			'fields'=> 'award_value,end_time,user_group,`condition`',
+			'where' => 'type = 1 and `id` = #id# and NOW() between start_time and end_time and is_close = 0',
+			'type'  => 'row',
+		)
+	),
+	//新品列表
+	'getCommendNew' => array(
+		'query' => array(
+			'name' => 'commend_goods as co',
+			'join' => 'left join goods as go on co.goods_id = go.id',
+			'where' => 'co.commend_id = 1 and go.is_del = 0 AND go.id is not null',
+			'fields' => 'go.img,go.sell_price,go.name,go.id,go.market_price',
+			'limit'=>'10',
+			'order'=>'sort asc'
+		)
+	),
+	//特价商品列表
+	'getCommendPrice' => array(
+		'query' => array(
+			'name' => 'commend_goods as co',
+			'join' => 'left join goods as go on co.goods_id = go.id',
+			'where' => 'co.commend_id = 2 and go.is_del = 0 AND go.id is not null',
+			'fields' => 'go.img,go.sell_price,go.name,go.id,go.market_price',
+			'limit'=>'10',
+			'order'=>'sort asc'
+		)
+	),
+	//热卖商品列表
+	'getCommendHot' => array(
+		'query' => array(
+			'name' => 'commend_goods as co',
+			'join' => 'left join goods as go on co.goods_id = go.id',
+			'where' => 'co.commend_id = 3 and go.is_del = 0 AND go.id is not null',
+			'fields' => 'go.img,go.sell_price,go.name,go.id,go.market_price',
+			'limit'=>'10',
+			'order'=>'sort asc'
+		)
+	),
+	//推荐商品列表
+	'getCommendRecom' => array(
+		'query' => array(
+			'name' => 'commend_goods as co',
+			'join' => 'left join goods as go on co.goods_id = go.id',
+			'where' => 'co.commend_id = 4 and go.is_del = 0 AND go.id is not null',
+			'fields' => 'go.img,go.sell_price,go.name,go.id,go.market_price',
+			'limit'=>'10',
+			'order'=>'sort asc'
+		)
+	),
+	//已配送的订单
+	'getOrderDistributed' => array(
+		'query' => array(
+			'name' => 'order',
+			'where' => 'distribution_status = 1 and if_del = 0',
+			'limit' => '10',
+			'order' => 'id desc'
+		)
+	),
+
+	//根据品牌热卖商品列表
+	'getCommendHotBrand'   => array(
+		'query' => array(
+			'name' => 'commend_goods as co',
+			'join' => 'left join goods as go on co.goods_id = go.id',
+			'where' => 'co.commend_id = 3 and go.is_del = 0 AND go.id is not null and go.brand_id = #brandid#',
+			'fields' => 'go.img,go.sell_price,go.name,go.id',
+			'limit'=>'10',
+			'order'=>'sort asc'
+		)
+	),
+	//导航列表
+	'getGuideList'=>array(
+		'query'=>array('name'=>'guide','limit'=>20)
+	),
+	//公告列表
+	'getAnnouncementList'=>array(
+		'query'=>array('name'=>'announcement','order'=>'id desc','limit'=>10)
+	),
+	//所有关键字列表
+	'getKeywordAllList'=>array(
+		'query'=>array('name'=>'keyword','order'=>'`order` asc','limit'=>50)
+	),
+	//所有商品分类
+	'getcategoryList'=>array(
+		'query'=>array('name'=>'category','order'=>'sort asc')
+	),
+	//根据商品分类取得商品列表
+	'getCategoryExtendList'=>array(
+	    'query'=>array(
+	    	'name'  => 'category_extend as ca',
+	    	'join'  => 'left join goods as go on go.id = ca.goods_id',
+	    	'where' => 'ca.category_id in(#categroy_id#) and go.is_del = 0',
+	    	'order' => 'go.sort asc',
+	    	'fields'=> 'go.id,go.name,go.img,go.sell_price,go.market_price',
+	    	'limit' => 10,
+	    )
+	),
+	//根据分类取销量排名列表
+	'getCategoryExtendListByCategoryid'=>array(
+	    'query'=>array(
+	    	'name'  => 'goods as go',
+	    	'join'  => 'left join category_extend as ca on ca.goods_id = go.id',
+	    	'where' => 'ca.category_id in (#categroy_id#) and go.is_del = 0',
+	    	'fields'=> 'distinct go.id,go.name,go.img,go.sell_price',
+		   	'order' => 'sale desc',
+	    	'limit' => 10,
+	    )
+	),
+	//所有一级分类
+	'getCategoryListTop'=>array(
+	    'query'=>array(
+	    	'name'  => 'category',
+	    	'where' => ' parent_id = 0 and visibility = 1 ',
+	    	'order' => ' sort asc',
+	    	'limit' => 20,
+	    )
+	),
+	//根据一级分类输出二级分类列表
+	'getCategoryByParentid'=>array(
+	    'query'=>array(
+	    	'name'  => 'category',
+	    	'where' => ' parent_id = #parent_id# and visibility = 1 ',
+	    	'order' => ' sort asc',
+	    	'limit' => 10,
+	    )
+	),
+	//所有品牌列表
+	'getBrandList'=>array(
+	    'query'=>array(
+	    	'name'  => 'brand',
+	    	'order' => ' sort asc',
+	    	'limit' => 10,
+	    )
+	),
+	//取得品牌详情
+	'getBrandInfo'=>array(
+	   'file' => 'brand.php','class' => 'APIBrand'
+	),
+	//取得商户详情
+	'getSellerInfo'=>array(
+	   'file' => 'seller.php','class' => 'APISeller'
+	),
+	//取得商户列表
+	'getSellerInfo'=>array(
+	   'file' => 'seller.php','class' => 'APISeller'
+	),
+	//取得VIP商户列表
+	'getVipSellerList'=>array(
+	    'query'=>array(
+	    	'name'  => 'seller',
+	    	'order' => ' sort asc ',
+	    	'limit' => 10,
+	    	'where' => 'is_del = 0 and is_vip = 1 and is_lock = 0',
+	    )
+	),
+	//取得商户列表
+	'getSellerList'=>array(
+	   'file' => 'seller.php','class' => 'APISeller'
+	),
+	//最新评论列表
+	'getCommentList'=>array(
+	    'query'=>array(
+	    	'name'  => 'comment as co',
+	    	'join'  => 'left join goods as go on co.goods_id = go.id',
+	    	'where' => ' co.status = 1 AND go.is_del = 0 AND go.id is not null',
+	    	'fields'=> 'go.img as img,go.name as name,co.point,co.contents,co.goods_id',
+	    	'order' => ' co.id desc',
+	    	'limit' => 10,
+	    )
+	),
+	//热门关键词列表
+	'getKeywordList'=>array(
+	 	 'query'=>array(
+	    	'name'  => 'keyword',
+	    	'where' => ' hot = 1',
+	    	'order' => '`order` asc',
+	    	'limit' => 5,
+	    )
+	),
+	//帮助中心底部列表
+	'getHelpCategoryFoot'=>array(
+	 	 'query'=>array(
+	    	'name'  => 'help_category',
+	    	'where' => ' position_foot = 1',
+	    	'order' => 'sort ASC',
+	    	'limit' => 5,
+	    )
+	),
+	//帮助中心左侧列表
+	'getHelpCategoryLeft'=>array(
+	 	 'query'=>array(
+	    	'name'  => 'help_category',
+	    	'where' => ' position_left = 1',
+	    	'order' => 'sort ASC',
+	    	'limit' => 5,
+	    )
+	),
+	//取帮助中心列表
+	'getHelpListByCatidAll'=>array(
+	 	 'query'=>array(
+	    	'name'  => 'help',
+	    	'where' => ' cat_id =  #cat_id# ',
+	    	'order' => 'sort ASC',
+	    	'limit' => 5,
+	    )
+	),
+	//文章分类
+	'getArticleCategoryList'=>array(
+	 	 'query'=>array(
+	    	'name'  => 'article_category',
+	    	'where' => ' issys = 0 ',
+	    	'order' => 'sort ASC',
+	    	'limit' => 10,
+	    )
+	),
+	//文章详情
+	'getArticleCategoryInfo'=>array(
+		'file' => 'article.php','class' => 'APIArticle'
+	),
+	//文章列表
+	'getArticleList' => array(
+		'file' => 'article.php','class' => 'APIArticle'
+	),
+	//根据分类读列表
+	'getArticleListByCatid' => array(
+		'file' => 'article.php','class' => 'APIArticle'
+	),
+	//公告列表
+	'getNoticeList' => array(
+		'file' => 'notice.php','class' => 'APINotice'
+	),
+	//品牌分类
+	'getBrandCategory'=>array(
+	    'query'=>array(
+	    	'name'  => 'brand_category',
+	    	'order' => ' id desc',
+	    )
+	),
+	//查找相关分类
+	'getBrandListWhere'=>array(
+	    'query'=>array(
+	    	'name'  => 'brand',
+	    	'where' => 'FIND_IN_SET(#id#,category_ids)',
+	    	'order' => ' sort asc',
+	    )
+	),
+	//根据品牌销量排名列表
+	'getGoodsListBrandSum'=>array(
+	    'query'=>array(
+	    	'name'   => 'goods',
+	    	'fields' => 'id,name,img,sell_price',
+	    	'where'  => 'is_del = 0 and brand_id = #brandid#',
+	    	'order'  => 'sale desc',
+	    	'limit'  => 10,
+	    )
+	),
+	//根据商家销量排名列表
+	'getGoodsListBySellerid'=>array(
+	    'query'=>array(
+	    	'name'   => 'goods',
+	    	'fields' => 'id,name,img,sell_price',
+	    	'where'  => "seller_id = #seller_id# and is_del = 0",
+	    	'order'  => 'sale desc',
+	    	'limit'  => 10,
+	    )
+	),
+	//根据商家取商品列表
+	'getGoodsListBySelleridList'=>array(
+	    'query'=>array(
+	    	'name'   => 'goods',
+	    	'fields' => 'id,img,name,sell_price',
+	    	'where'  => "seller_id = #seller_id# AND is_del = 0",
+	    	'order'  => 'sort asc',
+	    	'limit'  => 10,
+	    )
+	),
+	//帮助中心列表
+	'getHelpList' => array(
+		'file' => 'help.php','class' => 'APIHelp'
+	),
+	//根据分类取帮助中心列表
+	'getHelpListByCatId' => array(
+		'file' => 'help.php','class' => 'APIHelp'
+	),
+	//根据分类取推荐商品
+	'getCategoryExtendByCommendid'=>array(
+	    'query'=>array(
+	    	'name'  => 'category_extend as ca',
+	    	'join'  => 'left join goods as go on ca.goods_id = go.id left join commend_goods as co on co.goods_id = go.id',
+	    	'where' => 'ca.category_id in (#childId#) and co.commend_id = 4 and go.is_del = 0',
+	    	'fields'=> 'DISTINCT go.id,go.img,go.sell_price,go.name,go.market_price,go.description',
+		   	'order' => 'go.sort asc',
+	    	'limit' => 6,
+	    )
+	),
+	//根据商品分类获取品牌
+	'getCategoryExtendByBrandid'=>array(
+	    'query'=>array(
+	    	'name'  => 'category_extend as ca',
+	    	'join'  => 'left join goods as go on ca.goods_id = go.id left join brand as b on b.id = go.brand_id',
+	    	'where' => 'ca.category_id in ( #childId# ) and go.is_del = 0 and go.brand_id != 0',
+	    	'fields'=> 'DISTINCT b.id,b.name',
+	    	'limit' => 10,
+	    )
+	),
+
+	//帮助中心内容
+	'getHelpContent'=>array(
+	 	 'query'=>array(
+	    	'name'  => 'help',
+	    	'where' => ' id =  #id# ',
+	    	'fields'=> 'content',
+	    	'limit' => 1,
+	    )
+	),
+	//查找关键字
+	'getKeywordByWord'=>array(
+		'query'=>array(
+			'name'=>'keyword',
+			'where'=>'word like "%#word#%" and word != "#word#"',
+			'limit'=>10
+		)
+	),
+	//查找商品
+	'getGoodsCategoryExtend'=>array(
+		'query'=>array(
+			'name'  => 'goods as go',
+			'join'  => 'left join category_extend as ca on go.id = ca.goods_id left join category as c on c.id = ca.category_id',
+			'where' => 'go.is_del = 0 and go.name like "%#word#%" or FIND_IN_SET("#word#",search_words)',
+			'fields'=> 'c.name,c.id,count(*) as num',
+			'group' => 'ca.category_id',
+			'limit' => 20
+		)
+	),
+	//查找关键字取销量排名
+	'getGoodsListByWordSum'=>array(
+	    'query'=>array(
+	    	'name'   => 'goods',
+	    	'fields' => 'id,name,img,sell_price',
+	    	'where'  => 'name like "%#word#%" or FIND_IN_SET("#word#",search_words)',
+	    	'order'  => 'sale desc',
+	    	'limit'  => 10,
+	    )
+	),
+	//用户中心-账户余额
+	'getUcenterAccoutLog' => array(
+		'file' => 'ucenter.php','class' => 'APIUcenter'
+	),
+	//用户中心-我的建议
+	'getUcenterSuggestion' => array(
+		'file' => 'ucenter.php','class' => 'APIUcenter'
+	),
+	//用户中心-商品讨论
+	'getUcenterConsult' => array(
+		'file' => 'ucenter.php','class' => 'APIUcenter'
+	),
+	//用户中心-商品评价
+	'getUcenterEvaluation' => array(
+		'file' => 'ucenter.php','class' => 'APIUcenter'
+	),
+	//用户中心-收藏夹
+	'getUcenterFavoriteByCatid'=>array(
+		'query'=>array(
+			'name'=>'favorite as f,category as c ',
+			'where'=>'f.user_id = #user_id# and f.cat_id = c.id ',
+			'fields'=> 'count(*) as num,c.name,c.id ',
+			'group'=> 'cat_id',
+		)
+	),
+	//用户中心-个人资料
+	'getMemberInfo' => array(
+		'file' => 'ucenter.php','class' => 'APIUcenter'
+	),
+	//用户中心-个人主页统计
+	'getMemberTongJi' => array(
+		'file' => 'ucenter.php','class' => 'APIUcenter'
+	),
+	//用户中心-代金券统计
+	'getPropTongJi' => array(
+		'file' => 'ucenter.php','class' => 'APIUcenter'
+	),
+	//用户中心-订单列表
+	'getOrderListByUserid'=>array(
+	 	 'query'=>array(
+	    	'name'  => 'order',
+	    	'where' => ' user_id = #user_id# and if_del = 0 ',
+	    	'order'=> 'id desc',
+	    	'limit' => 6,
+	    )
+	),
+	//用户中心-感兴趣的商品
+	'getGoodsByCommendgoods'=>array(
+	 	 'query'=>array(
+	    	'name'  => 'goods',
+	    	'where' => 'is_del = 0',
+	    	'order' => 'grade desc',
+	    	'limit' => 12,
+	    )
+	),
+	//用户中心-积分列表
+	'getUcenterPointLog' => array(
+		'file' => 'ucenter.php','class' => 'APIUcenter'
+	),
+	//用户中心-代金券列表
+	'getTicketList'=>array(
+	 	 'query'=>array(
+	    	'name'  => 'ticket',
+	    	'where' => 'point > 0 and start_time <= "#nowtime#" and end_time > "#nowtime#" ',
+	    	'limit' => 20,
+	    )
+	),
+	//用户中心-信息列表
+	'getUcenterMessageList' => array(
+		'file' => 'ucenter.php','class' => 'APIUcenter'
+	),
+	//用户中心-订单列表
+	'getOrderList' => array(
+		'file' => 'ucenter.php','class' => 'APIUcenter'
+	),
+	//用户中心-订单中商品列表
+	'getOrderGoodsListByGoodsid'=>array(
+	 	 'query'=>array(
+	    	'name'  => 'order_goods as og',
+	    	'join'  => 'left join goods as go on og.goods_id = go.id',
+	    	'where' => 'order_id = #order_id# ',
+	    	'fields'=> 'og.*,go.point',
+	    )
+	),
+	//用户中心-我的代金券
+	'getPropList' => array(
+		'file' => 'ucenter.php','class' => 'APIUcenter'
+	),
+	//用户中心-退款记录
+	'getRefundmentDocList' => array(
+		'file' => 'ucenter.php','class' => 'APIUcenter'
+	),
+	//用户中心-提现记录
+	'getWithdrawList' => array(
+		'file' => 'ucenter.php','class' => 'APIUcenter'
+	),
+	//快捷登录
+	'getOauthList'=>array(
+	 	 'query'=>array(
+	    	'name'  => 'oauth',
+	    	'where' => "is_close=0",
+	    )
+	),
+	//查看大图相册
+	'getGoodsPhotoRelationList'=>array(
+	 	 'query'=>array(
+	    	'name'  => 'goods_photo_relation AS a ',
+	    	'join'  => "left join goods_photo AS b ON a.photo_id = b.id",
+	    	'where' => "a.goods_id = #id# ",
+	    	'fields' => "a.*,b.img",
+	    )
+	),
+	//地区列表
+	'getAreasListTop'=>array(
+	 	 'query'=>array(
+	    	'name'  => 'areas',
+	    	'where' => "parent_id =0 ",
+	    )
+	),
+	//支付列表
+	'getPaymentList'=>array(
+		'file'  => 'other.php','class' => 'APIOther',
+	),
+	//充值支付列表
+	'getPaymentListByOnline'=>array(
+		'file'  => 'other.php','class' => 'APIOther',
+	),
+	//根据分类读品牌
+	'getBrandListByGoodsCategoryId' => array(
+		'file' => 'brand.php','class' => 'APIBrand'
+	),
+	//获取促销规则
+	'getProrule' => array(
+		'file' => 'other.php','class' => 'APIOther'
+	),
+	//获取配送方式
+	'getDeliveryList' => array(
+		'query' => array(
+			'name' => 'delivery',
+			'where'=> 'is_delete = 0 and status = 1',
+		)
+	),
+	//获取文章关联的商品
+	'getArticleGoods' => array(
+		'query' => array(
+			'name'   => 'relation as r',
+			'join'   => 'left join goods as go on r.goods_id = go.id',
+			'where'  => 'r.article_id in (#article_id#) and go.id is not null',
+			'fields' => 'go.id as goods_id,go.img,go.name,go.sell_price',
+		)
+	),
+	//获取全部特价商品活动
+	'getSaleList' => array(
+		'file' => 'goods.php','class' => 'APIGoods'
+	),
+	//获取商家信息
+	'getSaleRow' => array(
+		'file' => 'goods.php','class' => 'APIGoods'
+	),
+	//获取幻灯片数据
+	'getBannerList' => array(
+		'file' => 'other.php','class' => 'APIOther'
+	),
+
+	//获取商品评论数据
+	'getListByGoods' => array(
+		'file' => 'comment.php','class' => 'APIComment'
+	),
+
+	//用户中心-收藏夹信息
+	'getFavorite' => array(
+		'file' => 'ucenter.php','class' => 'APIUcenter'
+	),
+
+	//获取默认广告数据
+	'getAdRow' => array(
+		'file' => 'other.php','class' => 'APIOther'
+	),
+);

+ 39 - 0
src/classes/api/article.php

@@ -0,0 +1,39 @@
+<?php
+/**
+ * @copyright (c) 2011 aircheng.com
+ * @file article.php
+ * @brief 公告api方法
+ * @author chendeshan
+ * @date 2014/10/12 13:59:44
+ * @version 2.7
+ */
+class APIArticle
+{
+	//获取文章分类数据
+	public function getArticleCategoryInfo($catId)
+	{
+		$db = new IModel('article_category');
+		return $db->getObj('id = '.$catId);
+	}
+
+	//文章列表
+	public function getArticleList()
+	{
+		$page = IReq::get('page') ? IFilter::act(IReq::get('page'),'int') : 1;
+		$query = new IQuery('article');
+		$query->where = 'visibility = 1 ';
+		$query->order = 'id desc';
+		$query->page  = $page;
+		return $query;
+	}
+	public function getArticleListByCatid($category_id)
+	{
+		$page = IReq::get('page') ? IFilter::act(IReq::get('page'),'int') : 1;
+		$query = new IQuery('article');
+		$query->where = 'category_id = '.$category_id.' and visibility = 1';
+		$query->order = 'id desc';
+		$query->page  = $page;
+		return $query;
+	}
+
+}

+ 45 - 0
src/classes/api/brand.php

@@ -0,0 +1,45 @@
+<?php
+/**
+ * @copyright (c) 2011 aircheng.com
+ * @file brand.php
+ * @brief 品牌API
+ * @author chendeshan
+ * @date 2014/10/12 13:59:44
+ * @version 2.7
+ */
+class APIBrand
+{
+	//品牌列表
+	public function getBrandInfo($id)
+	{
+		$query = new IModel('brand');
+		$info  = $query->getObj("id=".$id);
+		return $info;
+	}
+
+	//根据商品分类ID获取品牌数据
+	public function getBrandListByGoodsCategoryId($id,$limit = 14)
+	{
+		$result = array();
+		$tb_brand_category = new IModel('brand_category');
+		$info  = $tb_brand_category->query("goods_category_id=".$id);
+		if($info)
+		{
+			$query = new IQuery('brand');
+			foreach($info as $key => $val)
+			{
+				$query->where = " FIND_IN_SET(".$val['id'].",category_ids) ";
+				$query->order = 'sort asc';
+			    $query->limit  = $limit;
+			    $list = $query->find();
+			    $result = array_merge($result,$list);
+			    if(count($result) >= $limit)
+			    {
+			    	$result = array_slice($result, 0, $limit);
+			    	break;
+			    }
+			}
+		}
+		return $result;
+	}
+}

+ 31 - 0
src/classes/api/comment.php

@@ -0,0 +1,31 @@
+<?php
+/**
+ * @copyright (c) 2016 aircheng.com
+ * @file comment.php
+ * @brief 商品评论API
+ * @author nswe
+ * @date 2016/6/13 23:53:59
+ * @version 4.5
+ */
+class APIComment
+{
+	/**
+	 * @brief 获取商品评论列表
+	 * @param $goods_id int 商品id
+	 * @param $point string 评分数支持多个分数逗号间隔,比如:1,2,3
+	 * @return IQuery
+	 */
+	public function getListByGoods($goods_id,$point = "")
+	{
+		$page  = IReq::get('page') ? IFilter::act(IReq::get('page'),'int') : 1;
+		$query = new IQuery("comment AS c");
+		$query->fields = "c.*,u.username,u.head_ico";
+		$query->join   = "left join user AS u ON c.user_id = u.id";
+		$where         = "c.goods_id = {$goods_id} and c.status = 1";
+		$where        .= $point ? " and c.point in (".$point.") " : "";
+		$query->where  = $where;
+		$query->order    = "c.id DESC";
+		$query->page     = $page;
+		return $query;
+	}
+}

+ 43 - 0
src/classes/api/goods.php

@@ -0,0 +1,43 @@
+<?php
+/**
+ * @copyright (c) 2011 aircheng.com
+ * @file goods.php
+ * @author chendeshan
+ * @date 2011-9-30 13:49:22
+ * @version 0.6
+ */
+class APIGoods
+{
+	//获取全部商品特价活动
+	public function getSaleList()
+	{
+		$promoDB   = new IModel('promotion');
+		$promoList = $promoDB->query("is_close = 0 and award_type = 7","*","sort asc");
+		$goodsDB   = new IModel('goods');
+
+		foreach($promoList as $key => $val)
+		{
+			$intro = JSON::decode($val['intro']);
+			$intro = array_keys($intro);
+			$intro = join(",",$intro);
+			$promoList[$key]['goodsList'] = $goodsDB->query("id in (".$intro.") and is_del = 0","id,name,sell_price,sort,img,market_price,sale","sort asc");
+		}
+		return $promoList;
+	}
+
+	//根据id获取单个商品特价活动
+	public function getSaleRow($id)
+	{
+		$promoDB  = new IModel('promotion');
+		$promoRow = $promoDB->getObj("is_close = 0 and award_type = 7 and id = {$id}");
+		if($promoRow)
+		{
+			$intro = JSON::decode($promoRow['intro']);
+			$intro = array_keys($intro);
+			$intro = join(",",$intro);
+			$goodsDB = new IModel('goods');
+			$promoRow['goodsList'] = $goodsDB->query("id in (".$intro.") and is_del = 0","id,name,sell_price,sort,img,market_price","sort asc");
+		}
+		return $promoRow;
+	}
+}

+ 33 - 0
src/classes/api/help.php

@@ -0,0 +1,33 @@
+<?php
+/**
+ * @copyright (c) 2011 aircheng.com
+ * @file notice.php
+ * @brief 公告api方法
+ * @author chendeshan
+ * @date 2014/10/12 13:59:44
+ * @version 2.7
+ */
+class APIHelp
+{
+
+	//帮助中心列表
+	public function getHelpList()
+	{
+		$page = IReq::get('page') ? IFilter::act(IReq::get('page'),'int') : 1;
+		$query = new IQuery('help');
+		$query->order = 'sort desc';
+		$query->page  = $page;
+		return $query;
+	}
+	//根据分类取帮助中心列表
+	public function getHelpListByCatId($catId)
+	{
+		$page = IReq::get('page') ? IFilter::act(IReq::get('page'),'int') : 1;
+		$query = new IQuery('help');
+		$query->where="cat_id = ".$catId;
+		$query->order = 'sort desc';
+		$query->page  = $page;
+		return $query;
+	}
+
+}

+ 21 - 0
src/classes/api/notice.php

@@ -0,0 +1,21 @@
+<?php
+/**
+ * @copyright (c) 2011 aircheng.com
+ * @file notice.php
+ * @brief 公告api方法
+ * @author chendeshan
+ * @date 2014/10/12 13:59:44
+ * @version 2.7
+ */
+class APINotice
+{
+	//公告列表
+	public function getNoticeList()
+	{
+		$page = IReq::get('page') ? IFilter::act(IReq::get('page'),'int') : 1;
+		$query = new IQuery('announcement');
+		$query->order = 'id desc';
+		$query->page  = $page;
+		return $query;
+	}
+}

+ 138 - 0
src/classes/api/other.php

@@ -0,0 +1,138 @@
+<?php
+/**
+ * @copyright (c) 2014 aircheng.com
+ * @file other.php
+ * @brief 其他api方法
+ * @author chendeshan
+ * @date 2016/4/11 12:54:16
+ * @version 4.4
+ */
+class APIOther
+{
+	//获取促销规则
+	public function getProrule($seller_id = 0)
+	{
+		$proRuleObj = new ProRule(999999999,$seller_id);
+		$proRuleObj->isGiftOnce = false;
+		$proRuleObj->isCashOnce = false;
+		return $proRuleObj->getInfo();
+	}
+
+	//获取支付方式
+	public function getPaymentList()
+	{
+		$user_id = IWeb::$app->getController()->user['user_id'];
+		$where = 'status = 0';
+
+		if(!$user_id)
+		{
+			$where .= " and class_name != 'balance'";
+		}
+
+		switch(IClient::getDevice())
+		{
+			//移动支付
+			case IClient::MOBILE:
+			{
+				//如果是微信客户端,必须用微信专用支付
+				if(IClient::isWechat() == true)
+				{
+					$where .= " and (class_name in ( 'wap_wechat','balance' ) or ( type = 2 and client_type in(2,3) )) ";
+				}
+				else
+				{
+					$where .= " and client_type in(2,3) and class_name !=  'wap_wechat' ";
+
+					//如果不是APP客户端,就要屏蔽纯APP支付
+					if(IClient::isApp() == false)
+					{
+						$where .= " and class_name != 'app_wechat' ";
+					}
+				}
+			}
+			break;
+
+			//pc支付
+			case IClient::PC:
+			{
+				$where .= ' and client_type in(1,3) ';
+			}
+			break;
+		}
+		$paymentDB = new IModel('payment');
+		return $paymentDB->query($where,"*","`order` asc");
+	}
+
+	//线上充值的支付方式
+	public function getPaymentListByOnline()
+	{
+		$where = " type = 1 and status = 0 and class_name not in ('balance','offline') ";
+		switch(IClient::getDevice())
+		{
+			//移动支付
+			case IClient::MOBILE:
+			{
+				//如果是微信客户端,必须用微信专用支付
+				if(IClient::isWechat() == true)
+				{
+					$where .= " and (class_name in ( 'wap_wechat','balance' ) or ( type = 2 and client_type in(2,3) )) ";
+				}
+				else
+				{
+					$where .= " and client_type in(2,3) and class_name !=  'wap_wechat' ";
+				}
+			}
+			break;
+
+			//pc支付
+			case IClient::PC:
+			{
+				$where .= ' and client_type in(1,3) ';
+			}
+			break;
+		}
+
+		$paymentDB = new IModel('payment');
+		return $paymentDB->query($where,"*","`order` asc");
+	}
+
+	//获取banner数据
+	public function getBannerList()
+	{
+		$siteConfigObj = new Config("site_config");
+		$site_config   = $siteConfigObj->getInfo();
+
+		//读取本地serialize信息
+		if(isset($site_config['index_slide']) && $site_config['index_slide'])
+		{
+			return unserialize($site_config['index_slide']);
+		}
+		$cacheObj = new ICache();
+		$defaultBanner = $cacheObj->get('defaultBanner');
+		if(!$defaultBanner)
+		{
+			$defaultBanner = file_get_contents("http://product.aircheng.com/proxy/defaultBanner");
+			$cacheObj->set('defaultBanner',$defaultBanner);
+		}
+		return JSON::decode($defaultBanner);
+	}
+
+	//获取默认广告位数据
+	public function getAdRow($adName)
+	{
+		$isCache   = true;
+		$cacheObj  = new ICache();
+		$defaultAd = $cacheObj->get('ad'.$adName);
+		if(!$defaultAd || $isCache == false)
+		{
+			$ch = curl_init("http://product.aircheng.com/proxy/getAdRow");
+			curl_setopt($ch, CURLOPT_POST, 1);
+			curl_setopt($ch, CURLOPT_HEADER, 0);
+			curl_setopt($ch, CURLOPT_POSTFIELDS, "name=".$adName);
+			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
+			$defaultAd = curl_exec($ch);
+			$cacheObj->set('ad'.$adName,$defaultAd);
+		}
+		return $defaultAd;
+	}
+}

+ 30 - 0
src/classes/api/seller.php

@@ -0,0 +1,30 @@
+<?php
+/**
+ * @copyright (c) 2011 aircheng.com
+ * @file seller.php
+ * @brief 商家API
+ * @author chendeshan
+ * @date 2014/10/12 13:59:44
+ * @version 2.7
+ */
+class APISeller
+{
+	//商户信息
+	public function getSellerInfo($id)
+	{
+		$query = new IModel('seller');
+		$info  = $query->getObj("id=".$id." and is_del = 0 and is_lock = 0");
+		return $info;
+	}
+
+	//获取商户列表
+	public function getSellerList()
+	{
+		$page = IReq::get('page') ? IFilter::act(IReq::get('page'),'int') : 1;
+		$query = new IQuery('seller');
+		$query->where = 'is_del = 0 and is_lock = 0';
+		$query->order = 'sort asc';
+		$query->page  = $page;
+		return $query;
+	}
+}

+ 179 - 0
src/classes/api/ucenter.php

@@ -0,0 +1,179 @@
+<?php
+/**
+ * @copyright (c) 2011 aircheng.com
+ * @file notice.php
+ * @brief 用户中心api方法
+ * @author chendeshan
+ * @date 2014/10/12 13:59:44
+ * @version 2.7
+ */
+class APIUcenter
+{
+
+	///用户中心-账户余额
+	public function getUcenterAccoutLog($userid)
+	{
+		$page = IReq::get('page') ? IFilter::act(IReq::get('page'),'int') : 1;
+		$query = new IQuery('account_log');
+		$query->where="user_id = ".$userid;
+		$query->order = 'id desc';
+		$query->page  = $page;
+		return $query;
+	}
+	//用户中心-我的建议
+	public function getUcenterSuggestion($userid)
+	{
+		$page = IReq::get('page') ? IFilter::act(IReq::get('page'),'int') : 1;
+		$query = new IQuery('suggestion');
+		$query->where="user_id = ".$userid;
+		$query->page  = $page;
+		$query->order = 'id desc';
+		return $query;
+	}
+	//用户中心-商品讨论
+	public function getUcenterConsult($userid)
+	{
+		$page = IReq::get('page') ? IFilter::act(IReq::get('page'),'int') : 1;
+		$query = new IQuery('refer as r');
+		$query->join   = "join goods as go on r.goods_id = go.id ";
+		$query->where  = "r.user_id =". $userid;
+		$query->fields = "time,name,question,status,answer,admin_id,go.id as gid,reply_time";
+		$query->page   = $page;
+		$query->order = 'r.id desc';
+		return $query;
+	}
+	//用户中心-商品评价
+	public function getUcenterEvaluation($userid,$status = '')
+	{
+		$page = IReq::get('page') ? IFilter::act(IReq::get('page'),'int') : 1;
+		$where = "go.is_del = 0 and c.user_id = {$userid}";
+		$where.= ($status === '') ? "" : " and c.status = {$status}";
+
+		$query = new IQuery('comment as c');
+		$query->join   = "left join goods as go on go.id = c.goods_id";
+		$query->fields = "c.*";
+		$query->where  = $where;
+		$query->page   = $page;
+		$query->order  = 'c.id desc';
+		$result        = $query->find();
+
+		foreach($result as $key => $val)
+		{
+			$goodsRow = comment_class::goodsInfo($val['id']);
+			$result[$key] = array_merge($val,$goodsRow);
+		}
+		return $query->setData($result);
+	}
+
+	//用户中心-用户信息
+	public function getMemberInfo($userid){
+		$tb_member = new IModel('member as m,user as u');
+		$info = $tb_member->getObj("m.user_id = u.id and m.user_id=".$userid);
+		$info['group_name'] = "";
+		if($info['group_id'])
+		{
+			$userGroup = new IModel('user_group');
+			$groupRow  = $userGroup->getObj('id = '.$info['group_id']);
+			$info['group_name'] = $groupRow ? $groupRow['group_name'] : "";
+		}
+		return $info;
+	}
+	//用户中心-个人主页统计
+	public function getMemberTongJi($userid){
+		$result = array();
+
+		$query = new IQuery('order');
+		$query->fields = "count(id) as num";
+		$query->where  = "user_id = ".$userid." and if_del = 0";
+		$info = $query->find();
+		$result['num'] = $info[0]['num'];
+
+		$query->fields = "sum(order_amount) as amount";
+		$query->where  = "user_id = ".$userid." and status = 5 and if_del = 0";
+		$info = $query->find();
+		$result['amount'] = $info[0]['amount'];
+
+		return $result;
+	}
+	//用户中心-代金券统计
+	public function getPropTongJi($propIds){
+		$query = new IQuery('prop');
+		$query->fields = "count(id) as prop_num";
+		$query->where  = "id in (".$propIds.") and type = 0";
+		$info = $query->find();
+		return $info[0];
+	}
+	//用户中心-积分列表
+	public function getUcenterPointLog($userid,$c_datetime)
+	{
+		$page = IReq::get('page') ? IFilter::act(IReq::get('page'),'int') : 1;
+		$query = new IQuery('point_log');
+		$query->where  = "user_id = ".$userid." and ".$c_datetime;
+		$query->page   = $page;
+		$query->order= "id desc";
+		return $query;
+	}
+	//用户中心-信息列表
+	public function getUcenterMessageList($msgIds){
+		$page = IReq::get('page') ? IFilter::act(IReq::get('page'),'int') : 1;
+		$query = new IQuery('message');
+		$query->where= "id in(".$msgIds.")";
+		$query->order= "id desc";
+		$query->page = $page;
+		return $query;
+	}
+	//用户中心-订单列表
+	public function getOrderList($userid){
+		$page = IReq::get('page') ? IFilter::act(IReq::get('page'),'int') : 1;
+		$query = new IQuery('order');
+		$query->where = "user_id =".$userid." and if_del= 0";
+		$query->order = "id desc";
+		$query->page  = $page;
+		return $query;
+	}
+	//用户中心-我的代金券
+	public function getPropList($ids){
+		$page = IReq::get('page') ? IFilter::act(IReq::get('page'),'int') : 1;
+		$query = new IQuery('prop');
+		$query->where  = "id in(".$ids.") and is_send = 1";
+		$query->page   = $page;
+		return $query;
+	}
+	//用户中心-退款记录
+	public function getRefundmentDocList($userid){
+		$page = IReq::get('page') ? IFilter::act(IReq::get('page'),'int') : 1;
+		$query = new IQuery('refundment_doc');
+		$query->where = "user_id = ".$userid." and if_del = 0";
+		$query->order = "id desc";
+		$query->page  = $page;
+		return $query;
+	}
+	//用户中心-提现记录
+	public function getWithdrawList($userid){
+		$page = IReq::get('page') ? IFilter::act(IReq::get('page'),'int') : 1;
+		$query = new IQuery('withdraw');
+		$query->where = "user_id = ".$userid." and is_del = 0";
+		$query->order = "id desc";
+		$query->page  = $page;
+		return $query;
+	}
+
+    //[收藏夹]获取收藏夹数据
+	public function getFavorite($userid,$cat = '')
+    {
+		//获取收藏夹信息
+	    $page   = IReq::get('page') ? IFilter::act(IReq::get('page'),'int') : 1;
+	    $cat_id = IFilter::act($cat,'int');
+
+		$favoriteObj = new IQuery("favorite as f");
+		$favoriteObj->join  = "left join goods as go on go.id = f.rid";
+		$favoriteObj->fields= " f.*,go.name,go.id as goods_id,go.img,go.store_nums,go.sell_price,go.market_price";
+
+		$where = 'user_id = '.$userid;
+		$where.= $cat_id ? ' and cat_id = '.$cat_id : "";
+
+		$favoriteObj->where = $where;
+		$favoriteObj->page  = $page;
+		return $favoriteObj;
+    }
+}

+ 43 - 0
src/classes/area.php

@@ -0,0 +1,43 @@
+<?php
+/**
+ * @copyright Copyright(c) 2014 aircheng.com
+ * @file area.php
+ * @brief 省市地区调用函数
+ * @author nswe
+ * @date 2014/8/6 20:46:52
+ * @version 2.6
+ * @note
+ */
+
+ /**
+ * @class area
+ * @brief 省市地区调用函数
+ */
+class area
+{
+	/**
+	 * @brief 根据传入的地域ID获取地域名称,获取的名称是根据ID依次获取的
+	 * @param int 地域ID 匿名参数可以多个id
+	 * @return array
+	 */
+	public static function name()
+	{
+		$result     = array();
+		$paramArray = func_get_args();
+
+		//根据参数ID初始化数组值
+		foreach($paramArray as $key => $val)
+		{
+			$result[$val] = "";
+		}
+
+		$areaDB     = new IModel('areas');
+		$areaData   = $areaDB->query("area_id in (".trim(join(',',$paramArray),",").")");
+
+		foreach($areaData as $key => $value)
+		{
+			$result[$value['area_id']] = $value['area_name'];
+		}
+		return $result;
+	}
+}

+ 38 - 0
src/classes/article.php

@@ -0,0 +1,38 @@
+<?php
+/**
+ * @copyright (c) 2011 aircheng.com
+ * @file article.php
+ * @brief 关于文章管理
+ * @author chendeshan
+ * @date 2011-02-14
+ * @version 0.6
+ */
+
+ /**
+ * @class article
+ * @brief 文章管理模块
+ */
+class Article
+{
+	//显示标题
+	public static function showTitle($title,$color=null,$fontStyle=null)
+	{
+		$str='<span style="';
+		if($color!=null) $str.='color:'.$color.';';
+		if($fontStyle!=null)
+		{
+			switch($fontStyle)
+			{
+				case "1":
+				$str.='font-weight:bold;';
+				break;
+
+				case "2":
+				$str.='font-style:oblique;';
+				break;
+			}
+		}
+		$str.='">'.$title.'</span>';
+		return $str;
+	}
+}

+ 450 - 0
src/classes/cart.php

@@ -0,0 +1,450 @@
+<?php
+/**
+ * @copyright (c) 2015 aircheng.com
+ * @file cart.php
+ * @brief 购物车类库
+ * @author chendeshan
+ * @date 2016/1/16 21:58:40
+ * @version 4.3
+ */
+
+/**
+ * @class Cart
+ * @brief 购物车类库
+ */
+class Cart extends IInterceptorBase
+{
+	/*购物车简单cookie存储结构
+	* array [goods]=>array(商品主键=>数量) , [product]=>array( 货品主键=>数量 )
+	*/
+	private $cartStruct = array( 'goods' => array() , 'product' => array() );
+
+	/*购物车复杂存储结构
+	* [id]   :array  商品id值;
+	* [count]:int    商品数量;
+	* [info] :array  商品信息 [goods]=>array( ['id']=>商品ID , ['data'] => array( [商品ID]=>array ( [sell_price]价格, [count]购物车中此商品的数量 ,[type]类型goods,product ,[goods_id]商品ID值 ) ) ) , [product]=>array( 同上 ) , [count]购物车商品和货品数量 , [sum]商品和货品总额 ;
+	* [sum]  :int    商品总价格;
+	*/
+	private $cartExeStruct = array('goods' => array('id' => array(), 'data' => array() ),'product' => array( 'id' => array() , 'data' => array()),'count' => 0,'sum' => 0);
+
+	//购物车名字前缀
+	private $cartName    = 'shoppingcart';
+
+	//购物车中最多容纳的数量
+	private $maxCount    = 100;
+
+	//错误信息
+	private $error       = '';
+
+	//购物车的存储方式
+	private $saveType    = 'cookie';
+
+	/**
+	 * 获取新加入购物车的数据
+	 * @param $cartInfo cartStruct
+	 * @param $gid 商品或者货品ID
+	 * @param $num 数量
+	 * @param $type goods 或者 product
+	 */
+	private function getUpdateCartData($cartInfo,$gid,$num,$type)
+	{
+		$gid = intval($gid);
+		$num = intval($num);
+		if($type != 'goods')
+		{
+			$type = 'product';
+		}
+
+		//获取基本的商品数据
+		$goodsRow = $this->getGoodInfo($gid,$type);
+		if($goodsRow)
+		{
+			//购物车中已经存在此类商品
+			if(isset($cartInfo[$type][$gid]))
+			{
+				$sumStore = $cartInfo[$type][$gid] + $num;
+				if($goodsRow['store_nums'] < $sumStore)
+				{
+					$this->error = '该商品库存不足';
+					return false;
+				}
+
+				if($sumStore <= 0)
+				{
+					$this->error = '购买商品数量不正确';
+					return false;
+				}
+				$cartInfo[$type][$gid] = $sumStore;
+			}
+
+			//购物车中不存在此类商品
+			else
+			{
+				if($goodsRow['store_nums'] < $num)
+				{
+					$this->error = '该商品库存不足';
+					return false;
+				}
+
+				if($num <= 0)
+				{
+					$this->error = '购买商品数量不正确';
+					return false;
+				}
+				$cartInfo[$type][$gid] = $num;
+			}
+
+			return $cartInfo;
+		}
+		else
+		{
+			$this->error = '该商品库存不足';
+			return false;
+		}
+	}
+
+	/**
+	 * @brief 将商品或者货品加入购物车
+	 * @param $gid  商品或者货品ID值
+	 * @param $num  购买数量
+	 * @param $type 加入类型 goods商品; product:货品;
+	 */
+	public function add($gid, $num = 1 ,$type = 'goods')
+	{
+		//规格必填
+		if($type == "goods")
+		{
+			$productsDB = new IModel('products');
+			if($productsDB->getObj('goods_id = '.$gid))
+			{
+				$this->error = '请先选择商品的规格';
+				return false;
+			}
+		}
+
+		//购物车中已经存在此商品
+		$cartInfo = $this->getMyCartStruct();
+
+		if($this->getCartSort($cartInfo) >= $this->maxCount)
+		{
+			$this->error = '加入购物车失败,购物车中最多只能容纳'.$this->maxCount.'种商品';
+			return false;
+		}
+		else
+		{
+			$cartInfo = $this->getUpdateCartData($cartInfo,$gid,$num,$type);
+			if($cartInfo === false)
+			{
+				return false;
+			}
+			else
+			{
+				return $this->setMyCart($cartInfo);
+			}
+		}
+	}
+
+	//计算商品的种类
+	private function getCartSort($mycart)
+	{
+		$sumSort   = 0;
+		$sortArray = array('goods','product');
+		foreach($sortArray as $sort)
+		{
+			if(isset($mycart[$sort]))
+			{
+				$sumSort += count($mycart[$sort]);
+			}
+		}
+		return $sumSort;
+	}
+
+	//删除商品
+	public function del($gid , $type = 'goods')
+	{
+		$cartInfo = $this->getMyCartStruct();
+		if($type != 'goods')
+		{
+			$type = 'product';
+		}
+
+		//删除商品数据
+		if(isset($cartInfo[$type][$gid]))
+		{
+			unset($cartInfo[$type][$gid]);
+			$this->setMyCart($cartInfo);
+		}
+		else
+		{
+			$this->error = '购物车中没有此商品';
+			return false;
+		}
+	}
+
+	//根据 $gid 获取商品信息
+	private function getGoodInfo($gid, $type = 'goods')
+	{
+		$dataArray = array();
+
+		//商品方式
+		if($type == 'goods')
+		{
+			$goodsObj  = new IModel('goods');
+			$dataArray = $goodsObj->getObj('id = '.$gid.' and is_del = 0','id as goods_id,sell_price,store_nums');
+			if($dataArray)
+			{
+				$dataArray['id'] = $dataArray['goods_id'];
+			}
+		}
+		//货品方式
+		else
+		{
+			$productObj = new IQuery('products as pro , goods as go');
+			$productObj->fields = ' go.id as goods_id , pro.sell_price , pro.store_nums ,pro.id ';
+			$productObj->where  = ' pro.id = '.$gid.' and go.is_del = 0 and pro.goods_id = go.id';
+			$productRow = $productObj->find();
+			if($productRow)
+			{
+				$dataArray = $productRow[0];
+			}
+		}
+		return $dataArray;
+	}
+
+	/**
+	 * 获取当前购物车简单信息
+	 * @return 获取cartStruct数据结构
+	 */
+	private function getMyCartStruct()
+	{
+		$cartResult = array();
+
+		//获取临时购物车存储temp策略
+		$cartName     = $this->getCartName();
+		$tempData     = ($this->saveType == 'session') ? ISession::get($cartName) : ICookie::get($cartName);
+		if($tempData)
+		{
+			$cartResult = $this->decode($tempData);
+		}
+
+		//已经登录用户采用db策略
+		$cartDBData = array();
+		$user_id    = IWeb::$app->getController()->user['user_id'];
+		if($user_id)
+		{
+			$cartDB  = new IModel('goods_car');
+			$cartRow = $cartDB->getObj('user_id = '.$user_id);
+
+			//db存在购物车
+			if($cartRow)
+			{
+				if($cartRow['content'])
+				{
+					$cartDBData = $this->decode($cartRow['content']);
+					if($cartResult)
+					{
+						foreach($cartResult as $type => $val)
+						{
+							foreach($val as $idVal => $numVal)
+							{
+								$cartDBData = $this->getUpdateCartData($cartDBData,$idVal,$numVal,$type);
+							}
+						}
+					}
+					$cartResult = $cartDBData;
+				}
+				$cartDB->setData(array('content' => $this->encode($cartResult),'user_id' => $user_id,'create_time' => ITime::getDateTime()));
+				$cartDB->update("user_id = ".$user_id);
+			}
+			//db没有购物车,并且有临时temp购物车
+			else if($cartResult)
+			{
+				$cartDB->setData(array('content' => $tempData,'user_id' => $user_id,'create_time' => ITime::getDateTime()));
+				$cartDB->add();
+			}
+
+			$cartName = $this->getCartName();
+			$this->saveType == 'session' ? ISession::clear($cartName) : ICookie::clear($cartName);
+		}
+		return $cartResult ? $cartResult : $this->cartStruct;
+	}
+
+	/**
+	 * 获取当前购物车完整信息
+	 * @return 获取cartExeStruct数据结构
+	 */
+	public function getMyCart()
+	{
+		$cartValue = $this->getMyCartStruct();
+		return $this->cartFormat($cartValue);
+	}
+
+	//清空购物车
+	public function clear()
+	{
+		//1,清空db
+		$user_id = IWeb::$app->getController()->user['user_id'];
+		if($user_id)
+		{
+			$cartDB  = new IModel('goods_car');
+			$cartRow = $cartDB->getObj('user_id = '.$user_id);
+			if($cartRow)
+			{
+				$cartDB->del('user_id = '.$user_id);
+			}
+		}
+
+		//2,清空临时temp
+		$cartName = $this->getCartName();
+		$this->saveType == 'session' ? ISession::clear($cartName) : ICookie::clear($cartName);
+	}
+
+	//清空购物车拦截器 解决cookie header头延迟发送问题
+	public static function onFinishAction($ctrlObj,$actionObj)
+	{
+		$cartObj = new Cart();
+		$cartObj->clear();
+	}
+
+	//写入购物车
+	private function setMyCart($goodsInfo)
+	{
+		$goodsInfo = $this->encode($goodsInfo);
+
+		//1,用户存在写入db
+		$user_id = IWeb::$app->getController()->user['user_id'];
+		if($user_id)
+		{
+			$cartDB = new IModel('goods_car');
+			$cartDB->setData(array('content' => $goodsInfo,'user_id' => $user_id,'create_time' => ITime::getDateTime()));
+			$result = $cartDB->getObj('user_id = '.$user_id) ? $cartDB->update('user_id = '.$user_id) : $cartDB->add();
+		}
+		//2,访客写入temp临时
+		else
+		{
+			$cartName = $this->getCartName();
+			$result   = ($this->saveType == 'session') ? ISession::set($cartName,$goodsInfo) : ICookie::set($cartName,$goodsInfo,'7200');
+		}
+		return $result;
+	}
+
+	/**
+	 * @brief  把cookie的结构转化成为程序所用的数据结构
+	 * @param  $cartValue 购物车cookie存储结构
+	 * @return array : [goods]=>array( ['id']=>商品ID , ['data'] => array( [商品ID]=>array ([name]商品名称 , [img]图片地址 , [sell_price]价格, [count]购物车中此商品的数量 ,[type]类型goods,product , [goods_id]商品ID值 ) ) ) , [product]=>array( 同上 ) , [count]购物车商品和货品数量 , [sum]商品和货品总额 ;
+	 */
+	public function cartFormat($cartValue)
+	{
+		//初始化结果
+		$result = $this->cartExeStruct;
+
+		$goodsIdArray = array();
+
+		if(isset($cartValue['goods']) && $cartValue['goods'])
+		{
+			$goodsIdArray = array_keys($cartValue['goods']);
+			$result['goods']['id'] = $goodsIdArray;
+			foreach($goodsIdArray as $gid)
+			{
+				$result['goods']['data'][$gid] = array(
+					'id'       => $gid,
+					'type'     => 'goods',
+					'goods_id' => $gid,
+					'count'    => $cartValue['goods'][$gid],
+				);
+
+				//购物车中的种类数量累加
+				$result['count'] += $cartValue['goods'][$gid];
+			}
+		}
+
+		if(isset($cartValue['product']) && $cartValue['product'])
+		{
+			$productIdArray          = array_keys($cartValue['product']);
+			$result['product']['id'] = $productIdArray;
+
+			$productObj     = new IModel('products');
+			$productData    = $productObj->query('id in ('.join(",",$productIdArray).')','id,goods_id,sell_price');
+			foreach($productData as $proVal)
+			{
+				$result['product']['data'][$proVal['id']] = array(
+					'id'         => $proVal['id'],
+					'type'       => 'product',
+					'goods_id'   => $proVal['goods_id'],
+					'count'      => $cartValue['product'][$proVal['id']],
+					'sell_price' => $proVal['sell_price'],
+				);
+
+				if(!in_array($proVal['goods_id'],$goodsIdArray))
+				{
+					$goodsIdArray[] = $proVal['goods_id'];
+				}
+
+				//购物车中的种类数量累加
+				$result['count'] += $cartValue['product'][$proVal['id']];
+			}
+		}
+
+		if($goodsIdArray)
+		{
+			$goodsArray = array();
+
+			$goodsObj   = new IModel('goods');
+			$goodsData  = $goodsObj->query('id in ('.join(",",$goodsIdArray).')','id,name,img,sell_price');
+			foreach($goodsData as $goodsVal)
+			{
+				$goodsArray[$goodsVal['id']] = $goodsVal;
+			}
+
+			foreach($result['goods']['data'] as $key => $val)
+			{
+				if(isset($goodsArray[$val['goods_id']]))
+				{
+					$result['goods']['data'][$key]['img']        = Thumb::get($goodsArray[$val['goods_id']]['img'],120,120);
+					$result['goods']['data'][$key]['name']       = $goodsArray[$val['goods_id']]['name'];
+					$result['goods']['data'][$key]['sell_price'] = $goodsArray[$val['goods_id']]['sell_price'];
+
+					//购物车中的金额累加
+					$result['sum']   += $goodsArray[$val['goods_id']]['sell_price'] * $val['count'];
+				}
+			}
+
+			foreach($result['product']['data'] as $key => $val)
+			{
+				if(isset($goodsArray[$val['goods_id']]))
+				{
+					$result['product']['data'][$key]['img']  = Thumb::get($goodsArray[$val['goods_id']]['img'],120,120);
+					$result['product']['data'][$key]['name'] = $goodsArray[$val['goods_id']]['name'];
+
+					//购物车中的金额累加
+					$result['sum']   += $result['product']['data'][$key]['sell_price'] * $val['count'];
+				}
+			}
+		}
+		return $result;
+	}
+
+	//[私有]获取购物车名字
+	private function getCartName()
+	{
+		return $this->cartName;
+	}
+
+	//获取错误信息
+	public function getError()
+	{
+		return $this->error;
+	}
+
+	//购物车存储数据编码
+	private function encode($data)
+	{
+		return str_replace(array('"',','),array('&','$'),JSON::encode($data));
+	}
+
+	//购物车存储数据解码
+	private function decode($data)
+	{
+		return JSON::decode(str_replace(array('&','$'),array('"',','),$data));
+	}
+}

+ 128 - 0
src/classes/comment_class.php

@@ -0,0 +1,128 @@
+<?php
+/**
+ * 与评论相关的
+ *
+ * @author walu
+ * @packge iwebshop
+ */
+
+class Comment_Class
+{
+	/**
+	 * 检测用户是否能够评论
+	 *
+	 * @param int $comment_id 评论id
+	 * @param int $user_id 用户id
+	 * @return array() array(成功or失败,数据)
+	 */
+	public static function can_comment($comment_id,$user_id)
+	{
+		$comment_id = intval($comment_id);
+		$user_id = intval($user_id);
+
+		$tb_comment = new IModel("comment");
+		$comment = $tb_comment->getObj("id={$comment_id} AND user_id={$user_id}");
+		if(!$comment)
+		{
+			return "没有这条数据";
+		}
+
+		if($comment['status'] != 0)
+		{
+			return "不能重复评论";
+		}
+		return $comment;
+	}
+
+	/**
+	 * 获取某个商品的有关分数的评论数据,根据comment表里面的评价分数做分析
+	 *
+	 * 获取好评、中评、差评数量及平均分
+	 * 返回的值里包含以下几个计算出来的索引
+	 *	<ul>
+	 *		<li>point_total,总分</li>
+	 *		<li>comment_total,评论总数</li>
+	 *		<li>average_point,平均分</li>
+	 *	</ul>
+	 *
+	 * @param int $id 商品ID
+	 * @return array()
+	 */
+	public static function get_comment_info($id)
+	{
+		$data  = array();
+		$query = new IQuery("comment");
+		$query->fields = "COUNT(*) AS num,point";
+		$query->where  = "goods_id = {$id} AND status=1 ";
+		$query->group  = "point";
+
+		$config = array(0=>'none',1=>'bad',2=>'middle',3=>'middle',4=>'middle',5=>'good');
+
+		$data['point_grade'] = array('none'=>0,'good'=>0,'middle'=>0,'bad'=>0);
+		$data['point_total'] = 0;
+
+		foreach( $query->find() AS $value )
+		{
+			if($value['point']>=0 && $value['point']<=5)
+			{
+				$data['point_total']+=$value['point']*$value['num'];
+				$data['point_grade'][$config[$value['point']]] += $value['num'];
+			}
+		}
+		$data['comment_total']=array_sum($data['point_grade']);
+		$data['average_point']=0;
+		if($data['point_total']>0)
+		{
+			$data['average_point'] = round($data['point_total'] / $data['comment_total']);
+		}
+		return $data;
+	}
+
+	/**
+	 * @brief 获取评论商品
+	 * @param int $commentId 评论ID
+	 */
+	public static function goodsInfo($commentId)
+	{
+		$result    = array();
+		$commentDB = new IModel('comment');
+		$commentRow= $commentDB->getObj('id = '.$commentId);
+		if($commentRow)
+		{
+			//先查询订单商品关系表
+			if(isset($commentRow['order_goods_id']) && $commentRow['order_goods_id'])
+			{
+				$orderGoodsDB = new IModel('order_goods');
+				$orderGoodsRow= $orderGoodsDB->getObj('id = '.$commentRow['order_goods_id']);
+				if($orderGoodsRow)
+				{
+					$goodsArray = JSON::decode($orderGoodsRow['goods_array']);
+					$result = array(
+						'goods_id'   => $commentRow['goods_id'],
+						'name'       => $goodsArray['name'],
+						'value'      => $goodsArray['value'],
+						'img'        => $orderGoodsRow['img'],
+						'sell_price' => $orderGoodsRow['real_price'],
+					);
+				}
+			}
+
+			if(!$result)
+			{
+				$goodsDB = new IModel('goods');
+				$goodsRow= $goodsDB->getObj('id = '.$commentRow['goods_id']);
+				if($goodsRow)
+				{
+					$result = array(
+						'goods_id'   => $commentRow['goods_id'],
+						'name'       => $goodsRow['name'],
+						'img'        => $goodsRow['img'],
+						'sell_price' => $goodsRow['sell_price'],
+						'value'      => '',
+					);
+				}
+			}
+		}
+		return $result;
+	}
+}

+ 123 - 0
src/classes/common.php

@@ -0,0 +1,123 @@
+<?php
+/**
+ * @brief 公共方法集合
+ * @class Common
+ * @note  公开方法集合适用于整个系统
+ */
+class Common
+{
+	/**
+	 * @brief 获取评价分数
+	 * @param $grade float 分数
+	 * @param $comments int 评论次数
+	 * @return float
+	 */
+	public static function gradeWidth($grade,$comments = 1)
+	{
+		return $comments == 0 ? 0 : round($grade/$comments);
+	}
+
+	/**
+	 * @brief 获取用户状态
+	 * @param $status int 状态代码
+	 * @return string
+	 */
+	public static function userStatusText($status)
+	{
+		$mapping = array('1' => '正常','2' => '删除','3' => '锁定');
+		return isset($mapping[$status]) ? $mapping[$status] : '';
+	}
+
+	/**
+	 * 获取本地版本信息
+	 * @return String
+	 */
+	public static function getLocalVersion()
+	{
+		return include(IWeb::$app->getBasePath().'docs/version.php');
+	}
+
+	/**
+	 * @brief 重量换算
+	 * @param string $weight 带有重量单位的重量值,如5kg,8t等
+	 * @param string $export 转换的重量单位,默认:g(克)
+	 * @return int           转换后的重量数字
+	 */
+	public static function weight($weight,$export = 'g')
+	{
+		$weight = preg_replace("|\s|","",$weight);
+		preg_match("|^(\d+)([a-z]+)$|",$weight,$result);
+
+		//有单位的重量数据,如:5kg,8t等
+		if(isset($result[2]))
+		{
+			list($wholeMatch,$weightVal,$weightUnit) = $result;
+		}
+		//无单位的重量数据,如:500,默认单位g(克)
+		else
+		{
+			$weightVal  = floatval($weight);
+			$weightUnit = 'g';
+		}
+
+		//单位相同不需要转换,直接返回
+		if($weightUnit == $export)
+		{
+			return $weightVal;
+		}
+
+		//统一转换成g(克)
+		switch($weightUnit)
+		{
+			case "kg":
+			{
+				$weightVal *= 1000;
+			}
+			break;
+
+			case "t":
+			{
+				$weightVal *= 1000000;
+			}
+			break;
+		}
+
+		//从标准g(克)进行转化
+		switch($export)
+		{
+			case "kg":
+			{
+				$weightVal /= 1000;
+			}
+			break;
+
+			case "t":
+			{
+				$weightVal /= 1000000;
+			}
+			break;
+		}
+		return $weightVal;
+	}
+
+	/**
+	 * @brief  格式化重量数据(克)
+	 * @param  int $weightVal 纯重量数字(克)
+	 * @return int            转换后的重量数据包含单位,如:5kg,8t等
+	 */
+	public static function formatWeight($weightVal)
+	{
+		$weightUnit = "g";
+		if($weightVal > 1000000)
+		{
+			$weightUnit = "t";
+			$weightVal /= 1000000;
+		}
+		else if($weightVal > 1000)
+		{
+			$weightUnit = "kg";
+			$weightVal /= 1000;
+		}
+		return $weightVal.$weightUnit;
+	}
+}

+ 212 - 0
src/classes/config.php

@@ -0,0 +1,212 @@
+<?php
+/**
+ * @copyright Copyright(c) 2011 aircheng.com
+ * @file config.php
+ * @brief
+ * @author webning
+ * @date 2011-03-24
+ * @version 0.6
+ * @note
+ */
+/**
+ * @brief Config 产品中所有Config文件取值统一入口文件
+ * @class Config
+ */
+class Config
+{
+	//不需要过滤的键名
+	private static $safeKey = array('index_slide','service_online');
+	private $configFile;
+    private $config;
+    /**
+     * @brief 初始化对应的config文件
+     * @param String $config config文件名
+     */
+    public function __construct($config)
+    {
+        $this->initConfig($config);
+    }
+
+    /**
+     * @brief 设定Config文件
+     * @param String $config config文件名
+     */
+    public function setConfig($config)
+    {
+        $this->initConfig($config);
+    }
+
+    /**
+     * @brief 获取全部的config信息
+     */
+    public function getInfo()
+    {
+    	return $this->config;
+    }
+
+    /**
+     * @brief  初始化对应的config文件
+     * @param String $config config文件名
+     * @return Array 或者为null
+     */
+    private function initConfig($config)
+    {
+        if(isset(IWeb::$app->config['configExt']) && isset(IWeb::$app->config['configExt'][$config]))
+        {
+        	$this->configFile = IWeb::$app->getBasePath().IWeb::$app->config['configExt'][$config];
+        	$this->config     = require($this->configFile);
+        }
+        else
+        	$this->config = null;
+    }
+
+    /**
+     * @brief 取得当前Config文件下的对应变量
+     * @param String $name 变量名
+     * @return mixed
+     * @note 此函数可自由扩展自己对应的默认值
+     */
+    public function __get($name)
+    {
+        if(isset($this->config[$name]))
+        {
+            return $this->config[$name];
+        }
+        return '';
+    }
+
+    /**
+     * @brief 取得当前Config文件下的对应变量
+     * @param String $name 变量名
+     * @return mixed
+     * @note 此函数可自由扩展自己对应的默认值
+     */
+    public function write($inputArray)
+    {
+    	return self::edit($this->configFile , $inputArray);
+    }
+
+	/**
+	 * @brief 修改配置文件信息
+	 * @param string 配置文件名
+	 * @param array  写入的配置内容 key:配置信息里面key值; value:配置信息里面的value值
+	 * @return boolean
+	 */
+	public static function edit($configFile,$inputArray)
+	{
+		//安全过滤要写入文件的内容
+		foreach($inputArray as $key => $val)
+		{
+			if(!in_array($key,self::$safeKey))
+			{
+				$inputArray[$key] = IFilter::act($val,'text');
+			}
+		}
+
+		$configStr = "";
+
+		//读取配置信息内容
+		if(file_exists($configFile))
+		{
+			$configStr   = file_get_contents($configFile);
+			$configArray = require($configFile);
+		}
+
+		if(trim($configStr)=="")
+		{
+			$configStr   = "<?php return array( \r\n);?>";
+			$configArray = array();
+		}
+
+		//表单中存在但是不进行录用的键值
+		$except = array('form_index');
+
+		foreach($except as $value)
+		{
+			unset($inputArray[$value]);
+		}
+
+		$inputArray = array_merge($configArray,$inputArray);
+		$configData = var_export($inputArray,true);
+		$configStr = "<?php return {$configData}?>";
+
+		//写入配置文件
+		$fileObj   = new IFile($configFile,'w+');
+		$writeResult = $fileObj->write($configStr);
+		return $writeResult;
+	}
+
+	/**
+	 * @brief 获取语言包,主题,皮肤的方案
+	 * @param string $type  方案类型: theme:主题; skin:皮肤; lang:语言包;
+	 * @param string $theme 此参数只有$type为skin时才有用,获取任意theme下的skin方案;
+	 * @return array key=>方案名称;value=>具体数据
+	 */
+	public static function getSitePlan($type,$theme = null)
+	{
+		$defaultConf = 'config.php';
+		$planPath    = null;    //资源方案的路径
+		$planList    = array(); //方案列表
+		$configKey   = array('name','version','author','time','thumb','info','type');
+
+		//根据不同的类型设置方案路径
+		switch($type)
+		{
+			case "theme":
+			{
+				$planPath = IWeb::$app->getViewPath();
+				$webPath  = IWeb::$app->getWebViewPath();
+			}
+			break;
+
+			case "skin":
+			{
+				$planPath = IWeb::$app->getViewPath().$theme."/".IWeb::$app->defaultSkinDir."/";
+				$webPath  = IWeb::$app->getWebViewPath().$theme."/".IWeb::$app->defaultSkinDir."/";
+			}
+			break;
+
+			case "lang":
+			{
+				$planPath = IWeb::$app->getLanguagePath();
+			}
+			break;
+		}
+
+		if($planPath && is_dir($planPath))
+		{
+			$planList = array();
+			$dirRes   = opendir($planPath);
+
+			//遍历目录读取配置文件
+			while(false !== ($dir = readdir($dirRes)))
+			{
+				if($dir[0] == ".")
+				{
+					continue;
+				}
+				$fileName = $planPath.'/'.$dir.'/'.$defaultConf;
+				$tempData = file_exists($fileName) ? include($fileName) : array();
+				if($tempData)
+				{
+					//拼接系统所需数据
+					foreach($configKey as $val)
+					{
+						if(!isset($tempData[$val]))
+						{
+							$tempData[$val] = '';
+						}
+					}
+
+					//缩略图拼接路径
+					if(isset($tempData['thumb']) && isset($webPath))
+					{
+						$tempData['thumb'] = $webPath.$dir.'/'.$tempData['thumb'];
+					}
+					$planList[$dir] = $tempData;
+				}
+			}
+		}
+		return $planList;
+	}
+}

+ 655 - 0
src/classes/countsum.php

@@ -0,0 +1,655 @@
+<?php
+/**
+ * @copyright (c) 2011 aircheng.com
+ * @file countsum.php
+ * @brief 计算购物车中的商品价格
+ * @author chendeshan
+ * @date 2011-02-24
+ * @version 0.6
+ */
+class CountSum
+{
+	//用户ID
+	public $user_id = 0;
+
+	//用户组ID
+	public $group_id = '';
+
+	//用户组折扣
+	public $group_discount = '';
+
+	//错误信息
+	public $error = '';
+
+	/**
+	 * 构造函数
+	 */
+	public function __construct($user_id = 0)
+	{
+		if($user_id)
+		{
+			$this->user_id = $user_id;
+		}
+		else
+		{
+			$userCheckRights = IWeb::$app->getController()->user;
+			$this->user_id = ( isset($userCheckRights['user_id']) && $userCheckRights['user_id'] ) ? $userCheckRights['user_id'] : 0;
+		}
+
+		//获取用户组ID及组的折扣率
+		if($this->user_id)
+		{
+			$groupObj = new IModel('member as m , user_group as g');
+			$groupRow = $groupObj->getObj('m.user_id = '.$this->user_id.' and m.group_id = g.id','g.*');
+			if($groupRow)
+			{
+				$this->group_id       = $groupRow['id'];
+				$this->group_discount = $groupRow['discount'] * 0.01;
+			}
+		}
+	}
+
+	/**
+	 * 获取会员组价格
+	 * @param $id   int    商品或货品ID
+	 * @param $type string goods:商品; product:货品
+	 * @return float 价格
+	 */
+	public function getGroupPrice($id,$type = 'goods')
+	{
+		if(!$this->group_id)
+		{
+			return null;
+		}
+
+		//1,查询特定商品的组价格
+		$groupPriceDB = new IModel('group_price');
+		if($type == 'goods')
+		{
+			$discountRow = $groupPriceDB->getObj('goods_id = '.$id.' and group_id = '.$this->group_id,'price');
+		}
+		else
+		{
+			$discountRow = $groupPriceDB->getObj('product_id = '.$id.' and group_id = '.$this->group_id,'price');
+		}
+
+		if($discountRow)
+		{
+			return $discountRow['price'];
+		}
+
+		//2,根据会员折扣率计算商品折扣
+		if($this->group_discount)
+		{
+			if($type == 'goods')
+			{
+				$goodsDB  = new IModel('goods');
+				$goodsRow = $goodsDB->getObj('id = '.$id,'sell_price');
+				return $goodsRow ? Util::priceFormat($goodsRow['sell_price'] * $this->group_discount) : null;
+			}
+			else
+			{
+				$productDB  = new IModel('products');
+				$productRow = $productDB->getObj('id = '.$id,'sell_price');
+				return $productRow ? Util::priceFormat($productRow['sell_price'] * $this->group_discount) : null;
+			}
+		}
+		return null;
+	}
+
+	/**
+	 * 获取会员组价格区间,(1)手动定义商品价格; (2)商品自动折扣
+	 * @param  $id   int 商品ID
+	 * @return float 价格
+	 */
+	public function groupPriceRange($id)
+	{
+		if(!$this->group_id)
+		{
+			return null;
+		}
+
+		//查询商品会员价格
+		$goodsDB = new IModel('goods');
+		$goodsRow= $goodsDB->getObj('id = '.$id,'sell_price');
+		if(!$goodsRow)
+		{
+			return null;
+		}
+
+		//默认商品折扣价格
+		$resultPrice = array(
+			'minSellPrice' => Util::priceFormat($goodsRow['sell_price'] * $this->group_discount)
+		);
+
+		//查询会员价格设定表
+		$groupPriceDB = new IModel('group_price');
+		$discountRow  = $groupPriceDB->getObj('goods_id = '.$id.' and group_id = '.$this->group_id,'min(price) as minGroupPrice,max(price) as maxGroupPrice');
+		if(isset($discountRow['minGroupPrice']) && $discountRow['minGroupPrice'])
+		{
+			$resultPrice['minGroupPrice'] = $discountRow['minGroupPrice'];
+		}
+		if(isset($discountRow['maxGroupPrice']) && $discountRow['maxGroupPrice'])
+		{
+			$resultPrice['maxGroupPrice'] = $discountRow['maxGroupPrice'];
+		}
+
+		//如果设置了指定的会员价格,那么就移除默认的折扣价格
+		if($discountRow && current($discountRow))
+		{
+			unset($resultPrice['minSellPrice']);
+		}
+
+		//查询货品默认价格
+		$tb_product   = new IModel('products');
+		$product_info = $tb_product->getObj('goods_id='.$id,'max(sell_price) as maxSellPrice');
+		if(isset($product_info['maxSellPrice']) && $product_info['maxSellPrice'])
+		{
+			$resultPrice['maxSellPrice'] = Util::priceFormat($product_info['maxSellPrice'] * $this->group_discount);
+		}
+
+		$minPrice = min($resultPrice);
+		$maxPrice = max($resultPrice);
+		return $minPrice == $maxPrice ? $minPrice : join('-',array($minPrice,$maxPrice));
+	}
+
+	/**
+	 * @brief 计算商品价格
+	 * @param Array $buyInfo ,购物车格式
+	 * @promo string 活动类型 团购,抢购
+	 * @active_id int 活动ID
+	 * @return array or bool
+	 */
+	public function goodsCount($buyInfo,$promo='',$active_id='')
+	{
+		$this->sum           = 0;       //原始总额(优惠前)
+		$this->final_sum     = 0;       //应付总额(优惠后)
+    	$this->weight        = 0;       //总重量
+    	$this->reduce        = 0;       //减少总额
+    	$this->count         = 0;       //总数量
+    	$this->promotion     = array(); //促销活动规则文本
+    	$this->proReduce     = 0;       //促销活动规则优惠额
+    	$this->point         = 0;       //增加积分
+    	$this->exp           = 0;       //增加经验
+    	$this->freeFreight   = array(); //商家免运费,免运费的商家ID,自营ID为0
+    	$this->tax           = 0;       //商品税金
+    	$this->seller        = array(); //商家商品总额统计, 商家ID => 商品金额
+
+		$user_id      = $this->user_id;
+		$group_id     = $this->group_id;
+    	$goodsList    = array();
+    	$productList  = array();
+    	$giftIds      = array();//奖励性促销规则IDS
+
+		//活动购买情况
+    	if($promo && $active_id)
+    	{
+    		$ac_type    = isset($buyInfo['goods']) && $buyInfo['goods']['id'] ? "goods" : "product";
+    		$ac_id      = current($buyInfo[$ac_type]['id']);
+    		$ac_buy_num = $buyInfo[$ac_type]['data'][$ac_id]['count'];
+
+			//开启促销活动
+	    	$activeObject = new Active($promo,$active_id,$user_id,$ac_id,$ac_type,$ac_buy_num);
+	    	$activeResult = $activeObject->checkValid();
+	    	if($activeResult === true)
+	    	{
+	    		$typeRow  = $activeObject->originalGoodsInfo;
+	    		$disPrice = $activeObject->activePrice;
+
+				//设置优惠价格,如果不存在则优惠价等于商品原价
+				$typeRow['reduce'] = $typeRow['sell_price'] - $disPrice;
+				$typeRow['count']  = $ac_buy_num;
+    			$current_sum_all   = $typeRow['sell_price'] * $ac_buy_num;
+    			$current_reduce_all= $typeRow['reduce']     * $ac_buy_num;
+				$typeRow['sum']    = $current_sum_all - $current_reduce_all;
+
+    			if(!isset($this->seller[$typeRow['seller_id']]))
+    			{
+    				$this->seller[$typeRow['seller_id']] = 0;
+    			}
+    			$this->seller[$typeRow['seller_id']] += $typeRow['sum'];
+
+    			//全局统计
+		    	$this->weight += $typeRow['weight'] * $ac_buy_num;
+		    	$this->point  += $typeRow['point']  * $ac_buy_num;
+		    	$this->exp    += $typeRow['exp']    * $ac_buy_num;
+		    	$this->sum    += $current_sum_all;
+		    	$this->reduce += $current_reduce_all;
+		    	$this->count  += $ac_buy_num;
+		    	$this->tax    += self::getGoodsTax($typeRow['sum'],$typeRow['seller_id']);
+		    	$typeRow == "goods" ? ($goodsList[] = $typeRow) : ($productList[] = $typeRow);
+	    	}
+	    	else
+	    	{
+	    		$this->error .= $activeResult;
+	    		return $activeResult;
+	    	}
+    	}
+    	else
+    	{
+			/*开始计算goods和product的优惠信息 , 会根据条件分析出执行以下哪一种情况:
+			 *(1)查看此商品(货品)是否已经根据不同会员组设定了优惠价格;
+			 *(2)当前用户是否属于某个用户组中的成员,并且此用户组享受折扣率;
+			 *(3)优惠价等于商品(货品)原价;
+			 */
+
+			//获取商品或货品数据
+			/*Goods 拼装商品优惠价的数据*/
+	    	if(isset($buyInfo['goods']['id']) && $buyInfo['goods']['id'])
+	    	{
+	    		//购物车中的商品数据
+	    		$goodsIdStr = join(',',$buyInfo['goods']['id']);
+	    		$goodsObj   = new IQuery('goods as go');
+	    		$goodsObj->where = 'go.id in ('.$goodsIdStr.') and go.is_del = 0';
+	    		$goodsObj->fields= 'go.name,go.cost_price,go.id as goods_id,go.img,go.sell_price,go.point,go.weight,go.store_nums,go.exp,go.goods_no,0 as product_id,go.seller_id';
+	    		$goodsList       = $goodsObj->find();
+
+	    		//开始优惠情况判断
+	    		foreach($goodsList as $key => $val)
+	    		{
+	    			//检查库存
+	    			if($buyInfo['goods']['data'][$val['goods_id']]['count'] <= 0 || $buyInfo['goods']['data'][$val['goods_id']]['count'] > $val['store_nums'])
+	    			{
+	    				$goodsList[$key]['name'] .= "【无库存】";
+	    				$this->error .= "<商品:".$val['name']."> 购买数量超出库存,请重新调整购买数量。";
+	    			}
+
+	    			$groupPrice                = $this->getGroupPrice($val['goods_id'],'goods');
+	    			$goodsList[$key]['reduce'] = $groupPrice === null ? 0 : $val['sell_price'] - $groupPrice;
+	    			$goodsList[$key]['count']  = $buyInfo['goods']['data'][$val['goods_id']]['count'];
+	    			$current_sum_all           = $goodsList[$key]['sell_price'] * $goodsList[$key]['count'];
+	    			$current_reduce_all        = $goodsList[$key]['reduce']     * $goodsList[$key]['count'];
+	    			$goodsList[$key]['sum']    = $current_sum_all - $current_reduce_all;
+	    			if(!isset($this->seller[$val['seller_id']]))
+	    			{
+	    				$this->seller[$val['seller_id']] = 0;
+	    			}
+	    			$this->seller[$val['seller_id']] += $goodsList[$key]['sum'];
+
+	    			//全局统计
+			    	$this->weight += $val['weight'] * $goodsList[$key]['count'];
+			    	$this->point  += $val['point']  * $goodsList[$key]['count'];
+			    	$this->exp    += $val['exp']    * $goodsList[$key]['count'];
+			    	$this->sum    += $current_sum_all;
+			    	$this->reduce += $current_reduce_all;
+			    	$this->count  += $goodsList[$key]['count'];
+			    	$this->tax    += self::getGoodsTax($goodsList[$key]['sum'],$val['seller_id']);
+			    }
+	    	}
+
+			/*Product 拼装商品优惠价的数据*/
+	    	if(isset($buyInfo['product']['id']) && $buyInfo['product']['id'])
+	    	{
+	    		//购物车中的货品数据
+	    		$productIdStr = join(',',$buyInfo['product']['id']);
+	    		$productObj   = new IQuery('products as pro,goods as go');
+	    		$productObj->where  = 'pro.id in ('.$productIdStr.') and go.id = pro.goods_id';
+	    		$productObj->fields = 'pro.sell_price,pro.cost_price,pro.weight,pro.id as product_id,pro.spec_array,pro.goods_id,pro.store_nums,pro.products_no as goods_no,go.name,go.point,go.exp,go.img,go.seller_id';
+	    		$productList  = $productObj->find();
+
+	    		//开始优惠情况判断
+	    		foreach($productList as $key => $val)
+	    		{
+	    			//检查库存
+	    			if($buyInfo['product']['data'][$val['product_id']]['count'] <= 0 || $buyInfo['product']['data'][$val['product_id']]['count'] > $val['store_nums'])
+	    			{
+	    				$productList[$key]['name'] .= "【无库存】";
+	    				$this->error .= "<货品:".$val['name']."> 购买数量超出库存,请重新调整购买数量。";
+	    			}
+
+	    			$groupPrice                  = $this->getGroupPrice($val['product_id'],'product');
+					$productList[$key]['reduce'] = $groupPrice === null ? 0 : $val['sell_price'] - $groupPrice;
+	    			$productList[$key]['count']  = $buyInfo['product']['data'][$val['product_id']]['count'];
+	    			$current_sum_all             = $productList[$key]['sell_price']  * $productList[$key]['count'];
+	    			$current_reduce_all          = $productList[$key]['reduce']      * $productList[$key]['count'];
+	    			$productList[$key]['sum']    = $current_sum_all - $current_reduce_all;
+	    			if(!isset($this->seller[$val['seller_id']]))
+	    			{
+	    				$this->seller[$val['seller_id']] = 0;
+	    			}
+	    			$this->seller[$val['seller_id']] += $productList[$key]['sum'];
+
+	    			//全局统计
+			    	$this->weight += $val['weight'] * $productList[$key]['count'];
+			    	$this->point  += $val['point']  * $productList[$key]['count'];
+			    	$this->exp    += $val['exp']    * $productList[$key]['count'];
+			    	$this->sum    += $current_sum_all;
+			    	$this->reduce += $current_reduce_all;
+			    	$this->count  += $productList[$key]['count'];
+			    	$this->tax    += self::getGoodsTax($productList[$key]['sum'],$val['seller_id']);
+			    }
+	    	}
+
+	    	//总金额满足的促销规则
+	    	if($user_id)
+	    	{
+	    		//计算每个商家促销规则
+	    		foreach($this->seller as $seller_id => $sum)
+	    		{
+			    	$proObj = new ProRule($sum,$seller_id);
+			    	$proObj->setUserGroup($group_id);
+			    	if($proObj->isFreeFreight() == true)
+			    	{
+			    		$this->freeFreight[] = $seller_id;
+			    	}
+			    	//获取奖励型促销规则
+			    	$giftIds[$seller_id] = $proObj->getAwardIds();
+			    	$this->promotion = array_merge($proObj->getInfo(),$this->promotion);
+			    	$this->proReduce += $sum - $proObj->getSum();
+	    		}
+	    	}
+    	}
+
+    	$this->final_sum = $this->sum - $this->reduce - $this->proReduce;
+    	$this->final_sum = $this->final_sum <= 0 ? 0 : $this->final_sum;
+    	$resultList      = array_merge($goodsList,$productList);
+    	if(!$resultList)
+    	{
+    		$this->error .= "当前没有选购商品,请重新选择商品下单";
+    	}
+
+    	return array(
+    		'final_sum'  => $this->final_sum,
+    		'promotion'  => $this->promotion,
+    		'proReduce'  => $this->proReduce,
+    		'sum'        => $this->sum,
+    		'goodsList'  => $resultList,
+    		'count'      => $this->count,
+    		'reduce'     => $this->reduce,
+    		'weight'     => common::formatWeight($this->weight),
+    		'point'      => $this->point,
+    		'exp'        => $this->exp,
+    		'tax'        => $this->tax,
+    		'freeFreight'=> $this->freeFreight,
+    		'seller'     => $this->seller,
+    		'giftIds'    => $giftIds,
+    	);
+	}
+
+	//购物车计算
+	public function cart_count($id = '',$type = '',$buy_num = 1,$promo='',$active_id='')
+	{
+		//单品购买
+		if($id && $type)
+		{
+			$type = ($type == "goods") ? "goods" : "product";
+
+			//规格必填
+			if($type == "goods")
+			{
+				$productsDB = new IModel('products');
+				if($productsDB->getObj('goods_id = '.$id))
+				{
+					$this->error .= '请先选择商品的规格';
+					return $this->error;
+				}
+			}
+
+    		$buyInfo = array(
+    			$type => array('id' => array($id),'data' => array($id => array('count' => $buy_num)),'count' => $buy_num)
+    		);
+		}
+		else
+		{
+			//获取购物车中的商品和货品信息
+	    	$cartObj = new Cart();
+	    	$buyInfo = $cartObj->getMyCart();
+		}
+    	return $this->goodsCount($buyInfo,$promo,$active_id);
+    }
+
+    /**
+     * 计算订单信息,其中部分计算都是以商品原总价格计算的$goodsSum
+     * @param $goodsResult array CountSum结果集
+     * @param $province_id int 省份ID
+     * @param $delievery_id int 配送方式ID
+     * @param $payment_id int 支付ID
+     * @param $is_invoice int 是否要发票
+     * @param $discount float 订单的加价或者减价
+     * @param $promo string 促销活动
+     * @param $active_id int 促销活动ID
+     * @return $result 最终的返回数组
+     */
+    public function countOrderFee($goodsResult,$province_id,$delivery_id,$payment_id,$is_invoice,$discount = 0,$promo = '',$active_id = '')
+    {
+    	//根据商家进行商品分组
+    	$sellerGoods = array();
+    	foreach($goodsResult['goodsList'] as $key => $val)
+    	{
+    		if(!isset($sellerGoods[$val['seller_id']]))
+    		{
+    			$sellerGoods[$val['seller_id']] = array();
+    		}
+    		$sellerGoods[$val['seller_id']][] = $val;
+    	}
+
+		$cartObj = new Cart();
+    	foreach($sellerGoods as $seller_id => $item)
+    	{
+    		$num          = array();
+    		$productID    = array();
+    		$goodsID      = array();
+    		$goodsArray   = array();
+    		$productArray = array();
+    		foreach($item as $key => $val)
+    		{
+    			$goodsID[]   = $val['goods_id'];
+    			$productID[] = $val['product_id'];
+    			$num[]       = $val['count'];
+	    		if($val['product_id'] > 0)
+	    		{
+	    			$productArray[$val['product_id']] = $val['count'];
+	    		}
+	    		else
+	    		{
+	    			$goodsArray[$val['goods_id']] = $val['count'];
+	    		}
+    		}
+    		$sellerData = $this->goodsCount($cartObj->cartFormat(array("goods" => $goodsArray,"product" => $productArray)),$promo,$active_id);
+	    	if(is_string($sellerData))
+	    	{
+				return $sellerData;
+	    	}
+
+	    	$deliveryList = Delivery::getDelivery($province_id,$delivery_id,$goodsID,$productID,$num);
+	    	if(is_string($deliveryList))
+	    	{
+				return $deliveryList;
+	    	}
+
+			//物流无法送达
+	    	if($deliveryList['if_delivery'] == 1)
+	    	{
+	    		return '所选物流方式无法送达至您所在地';
+	    	}
+
+			//有促销免运费活动
+			if(isset($sellerData['freeFreight']) && $sellerData['freeFreight'])
+			{
+				foreach($sellerData['freeFreight'] as $sid)
+				{
+					if(isset($deliveryList['seller_price'][$sid]))
+					{
+						$deliveryList['price'] -= $deliveryList['seller_price'][$sid];
+						$deliveryList['seller_price'][$sid] = 0;
+					}
+				}
+			}
+
+	    	$extendArray = array(
+	    		'deliveryOrigPrice' => $deliveryList['org_price'],
+	    		'deliveryPrice'     => $deliveryList['price'] <= 0 ? 0 : $deliveryList['price'],
+	    		'insuredPrice'      => $deliveryList['protect_price'],
+	    		'taxPrice'          => $is_invoice == true ? $sellerData['tax'] : 0,
+	    		'paymentPrice'      => $payment_id != 0 ? self::getGoodsPaymentPrice($payment_id,$sellerData['final_sum']) : 0,
+	    		'goodsResult'       => $sellerData,
+	    		'orderAmountPrice'  => 0,
+	    		'giftIds'           => isset($sellerData['giftIds'][$seller_id]) ? $sellerData['giftIds'][$seller_id] : '',
+	    	);
+	    	$orderAmountPrice = array_sum(array(
+		    	$sellerData['final_sum'],
+		    	$extendArray['deliveryPrice'],
+		    	$extendArray['insuredPrice'],
+		    	$extendArray['taxPrice'],
+		    	$extendArray['paymentPrice'],
+	    	));
+
+			//订单减价折扣不能高于订单总额,禁止0元订单
+	    	if($discount < 0 && $orderAmountPrice <= abs($discount))
+	    	{
+	    		return '订单减价折扣不能低于订单总额';
+	    	}
+			$orderAmountPrice               += $discount;
+			$extendArray['orderAmountPrice'] = $orderAmountPrice <= 0 ? 0 : round($orderAmountPrice,2);
+			$sellerGoods[$val['seller_id']]  = array_merge($sellerData,$extendArray);
+    	}
+    	return $sellerGoods;
+    }
+
+    /**
+     * 获取商品的税金
+     * @param $goodsSum float 商品总价格
+     * @param $seller_id int 商家ID
+     * @return $goodsTaxPrice float 商品的税金
+     */
+    public static function getGoodsTax($goodsSum,$seller_id = 0)
+    {
+    	if($seller_id)
+    	{
+    		$sellerDB = new IModel('seller');
+    		$sellerRow= $sellerDB->getObj('id = '.$seller_id);
+    		$tax_per  = $sellerRow['tax'];
+    	}
+    	else
+    	{
+			$siteConfigObj = new Config("site_config");
+			$site_config   = $siteConfigObj->getInfo();
+			$tax_per       = isset($site_config['tax']) ? $site_config['tax'] : 0;
+    	}
+		$goodsTaxPrice = $goodsSum * ($tax_per * 0.01);
+		return round($goodsTaxPrice,2);
+    }
+
+    /**
+     * 获取商品金额的支付费用
+     * @param $payment_id int 支付方式ID
+     * @param $goodsSum float 商品总价格
+     * @return $goodsPayPrice
+     */
+    public static function getGoodsPaymentPrice($payment_id,$goodsSum)
+    {
+		$paymentObj = new IModel('payment');
+		$paymentRow = $paymentObj->getObj('id = '.$payment_id,'poundage,poundage_type');
+
+		if($paymentRow)
+		{
+			if($paymentRow['poundage_type'] == 1)
+			{
+				//按照百分比
+				return $goodsSum * ($paymentRow['poundage'] * 0.01);
+			}
+			//按照固定金额
+			return $paymentRow['poundage'];
+		}
+		return 0;
+    }
+
+	/**
+	 * @brief 获取商户订单货款结算
+	 * @param int $seller_id 商户ID
+	 * @param datetime $start_time 订单开始时间
+	 * @param datetime $end_time 订单结束时间
+	 * @param string $is_checkout 是否已经结算 0:未结算; 1:已结算; null:不限
+	 * @param IQuery 结果集对象
+	 */
+    public static function getSellerGoodsFeeQuery($seller_id = '',$start_time = '',$end_time = '',$is_checkout = '')
+    {
+    	$where  = "status in (5,6,7) and pay_type != 0 and pay_status = 1 and distribution_status in (0,1,2)";
+    	$where .= $is_checkout !== '' ? " and is_checkout = ".$is_checkout : "";
+    	$where .= $seller_id          ? " and seller_id = ".$seller_id : " and seller_id > 0";
+    	$where .= $start_time         ? " and create_time >= '{$start_time}' " : "";
+    	$where .= $end_time           ? " and create_time <= '{$end_time}' "   : "";
+
+    	$orderGoodsDB = new IQuery('order');
+    	$orderGoodsDB->order = "id desc";
+    	$orderGoodsDB->where = $where;
+    	return $orderGoodsDB;
+    }
+
+	/**
+	 * @brief 计算商户货款及其他费用
+	 * @param array $orderList 订单数据关联
+	 * @return array(
+	 * 'orderAmountPrice' => 订单金额(去掉pay_fee支付手续费),'refundFee' => 退款金额, 'commissionFee' => 分销佣金金额, 'orgCountFee' => 原始结算金额,
+	 * 'countFee' => 实际结算金额, 'platformFee' => 平台促销活动金额(代金券等平台补贴给商家),'commission' => '手续费' ,'commissionPer' => '手续费比率',
+	 * 'orderNum' => 订单数量, 'order_ids' => 订单IDS,'orderNoList' => 订单编号
+	 * ),
+	 */
+    public static function countSellerOrderFee($orderList)
+    {
+    	$result = array(
+			'orderAmountPrice' => 0,
+			'refundFee'        => 0,
+			'commissionFee'    => 0,
+			'orgCountFee'      => 0,
+			'countFee'         => 0,
+			'platformFee'      => 0,
+			'commission'       => 0,
+			'commissionPer'    => 0,
+			'orderNum'         => count($orderList),
+			'order_ids'        => array(),
+			'orderNoList'      => array(),
+    	);
+
+    	if($orderList && is_array($orderList))
+    	{
+    		$refundObj = new IModel("refundment_doc");
+    		$propObj   = new IModel("prop");
+    		foreach($orderList as $key => $item)
+    		{
+    			//检查平台促销活动
+    			//1,代金券
+    			if($item['prop'])
+    			{
+    				$propRow = $propObj->getObj('id = '.$item['prop'].' and type = 0');
+    				if($propRow && $propRow['seller_id'] == 0)
+    				{
+    					$propRow['value'] = min($item['real_amount'],$propRow['value']);
+    					$result['platformFee'] += $propRow['value'];
+    				}
+    			}
+
+    			$result['orderAmountPrice'] += $item['order_amount'] - $item['pay_fee'];
+    			$result['order_ids'][]       = $item['id'];
+    			$result['orderNoList'][]     = $item['order_no'];
+
+    			//是否存在退款
+    			$refundList = $refundObj->query("order_id = ".$item['id'].' and pay_status = 2');
+    			foreach($refundList as $k => $val)
+    			{
+    				$result['refundFee'] += $val['amount'];
+    			}
+
+    			//是否存在订单佣金
+    			$itemCommissionFee = plugin::trigger('getCommissionFeeByOrderId',$item['id']);
+    			if($itemCommissionFee)
+    			{
+    				$result['commissionFee'] += $itemCommissionFee;
+    			}
+    		}
+    	}
+
+		//应该结算金额
+		$result['orgCountFee'] = $result['orderAmountPrice'] - $result['refundFee'] - $result['commissionFee'] + $result['platformFee'];
+
+		//获取结算手续费
+		$siteConfigData = new Config('site_config');
+		$result['commissionPer'] = $siteConfigData->commission ? $siteConfigData->commission : 0;
+		$result['commission']    = round($result['orgCountFee'] * $result['commissionPer']/100,2);
+
+		//最终结算金额
+		$result['countFee'] = $result['orgCountFee'] - $result['commission'];
+
+    	return $result;
+    }
+}

+ 388 - 0
src/classes/dbbackup.php

@@ -0,0 +1,388 @@
+<?php
+/**
+ * @copyright (c) 2011 aircheng.com
+ * @file DBBackup.php
+ * @brief 数据库备份
+ * @author chendeshan
+ * @date 2015/5/6 13:45:17
+ * @version 3.2
+ */
+
+/**
+ * @class DBBackup
+ * @brief 数据库备份类
+ */
+class DBBackup
+{
+	private $maxLimit     = 1500;              //设置最大读取数据条数(条)
+	private $partSize     = 5000;              //分卷大小(KB)
+	private $ctrlRes      = array();           //要操作的资源
+	private $fileName     = null;              //当前备份数据的文件名
+	private $part         = 1;                 //分卷号初始值
+	private $totalSize    = 0;                 //备份数据共占字节数
+	private $showMess     = false;             //展示状态信息
+	private $dir          = 'backup/database'; //备份路径
+	private $fPrefix      = 'iwebshop';        //备份文件名前缀
+	private $fExtend      = '.sql';            //备份文件扩展名
+	private $tablePre     = 'iwebshop_';       //表前缀
+
+	//构造函数
+	function __construct($ctrlRes = null)
+	{
+		if(is_array($ctrlRes))
+		{
+			sort($ctrlRes);
+		}
+
+		$this->ctrlRes = $ctrlRes;
+		if(isset(IWeb::$app->config['dbbackup']) && IWeb::$app->config['dbbackup']!=null)
+		{
+			$this->dir = IWeb::$app->config['dbbackup'];
+		}
+
+		if(isset(IWeb::$app->config['DB']['tablePre']))
+		{
+			$this->tablePre = IWeb::$app->config['DB']['tablePre'];
+		}
+
+		if(!file_exists($this->dir))
+		{
+			$issetDir = IFile::mkdir($this->dir);
+			if(!$issetDir)
+			{
+				throw new IException("创建目录:".$this->dir." 失败");
+			}
+		}
+	}
+
+	//备份的文件列表
+	function getList()
+	{
+		$fileArray  = array(
+			'system'   => array(),
+			'unsystem' => array(),
+		);
+
+		$dirRes = opendir($this->dir);
+		while( false !== ($fileName = readdir($dirRes)) )
+		{
+			if($fileName[0] == '.')
+			{
+				continue;
+			}
+
+			if(stripos($fileName,$this->fPrefix) !== false && stripos($fileName,$this->fExtend) !== false)
+				$key = 'system';
+			else
+				$key = 'unsystem';
+
+			$fileArray[$key][$fileName] = array(
+				'name' => $fileName,
+				'size' => number_format(filesize($this->dir.'/'.$fileName)/1024,1),
+				'time' => date('Y-m-d H:i:s', filemtime($this->dir.'/'.$fileName) )
+			);
+			krsort($fileArray[$key]);
+		}
+		return $fileArray;
+	}
+
+	//下载文件
+	function download($file)
+	{
+		header('Content-Type: text/html; charset=UTF-8');
+		header('Content-Description: File Transfer');
+		header('Content-Type: application/octet-stream');
+		header('Content-Disposition: attachment; filename='.basename($file));
+		readfile($this->dir.'/'.$file);
+	}
+
+	//删除数据备份文件
+	function del()
+	{
+		foreach($this->ctrlRes as $val)
+		{
+			if(file_exists($this->dir.'/'.$val))
+				unlink($this->dir.'/'.$val);
+			else
+				return false;
+		}
+	}
+
+	//执行恢复
+	function runRes()
+	{
+		foreach($this->ctrlRes as $val)
+		{
+			$fileName = $this->dir.'/'.$val;
+			$this->parseSQL($fileName);
+		}
+	}
+
+	//解析备份文件中的SQL
+	function parseSQL($fileName)
+	{
+		//忽略外键约束
+		$this->query("SET FOREIGN_KEY_CHECKS = 0;");
+
+		$fhandle  = fopen($fileName,'r');
+		while(!feof($fhandle))
+		{
+			$lstr = fgets($fhandle);     //获取指针所在的一行数据
+
+			//判断当前行存在字符
+			if(isset($lstr[0]) && $lstr[0]!='#')
+			{
+				$prefix = substr($lstr,0,2);  //截取前2字符判断SQL类型
+				switch($prefix)
+				{
+					case '--' :
+					case '//' :
+					{
+						continue;
+					}
+
+					case '/*':
+					{
+						if(substr($lstr,-5) == "*/;\r\n" || substr($lstr,-4) == "*/\r\n")
+							continue;
+						else
+						{
+							$this->skipComment($fhandle);
+							continue;
+						}
+					}
+
+					default :
+					{
+						$sqlArray[] = trim($lstr);
+						if(substr(trim($lstr),-1) == ";")
+						{
+							$sqlStr   = join($sqlArray);
+							$sqlArray = array();
+
+							$this->query($sqlStr);
+
+							//回调函数
+							$this->actionCallBack($fileName);
+						}
+					}
+				}
+			}
+		}
+
+		//开启外键约束
+		$this->query("SET FOREIGN_KEY_CHECKS = 1;");
+	}
+
+	//略过注释
+	function skipComment($fhandle)
+	{
+		$lstr = fgets($fhandle,4096);
+		if(substr($lstr,-5) == "*/;\r\n" || substr($lstr,-4) == "*/\r\n")
+			return true;
+		else
+			$this->skipComment($fhandle);
+	}
+
+	//执行SQL
+	function query($sql)
+	{
+		//创建数据库对象
+		$dbObj = IDBFactory::getDB();
+		$dbObj->query($sql);
+	}
+
+	//打包下载
+	function packDownload()
+	{
+		if(class_exists('ZipArchive'))
+		{
+			$fileName = $this->fPrefix.'_'.date('Ymd_His').'.zip';
+			$zip = new ZipArchive();
+			$zip->open($this->dir.'/'.$fileName,ZIPARCHIVE::CREATE);
+			foreach($this->ctrlRes as $file)
+			{
+				$attachfile = $this->dir.'/'.$file;
+				$zip->addFile($attachfile,basename($attachfile));
+			}
+			$zip->close();
+
+			return $fileName;
+		}
+		else
+		{
+			return false;
+		}
+	}
+
+	//动作执行回调函数
+	function actionCallBack($mess)
+	{
+		//防止超时
+		set_time_limit(60);
+	}
+
+	//设置展示状态开关
+	function setShowMess($isOpen = false)
+	{
+		$this->showMess = $isOpen;
+	}
+
+	//设置备份的路径
+	function setDir($dir)
+	{
+		$this->dir = $dir;
+	}
+
+	//设置分卷大小(KB)
+	function setPartSize($size)
+	{
+		$this->partSize = $size;
+	}
+
+	//设置最大读取数据条数(条)
+	function setMaxLimit($maxLimit)
+	{
+		$this->maxLimit = $maxLimit;
+	}
+
+	//执行备份
+	function runBak()
+	{
+		//循环表
+		foreach($this->ctrlRes as $name)
+		{
+			if($name == $this->tablePre."goods")
+			{
+				$this->setMaxLimit(30);
+			}
+
+			$tableStruct = $this->createStructure($name);//生成表结构
+			$sumTime     = $this->countTime($name);      //计算写入文件的总次数
+
+			//生成表数据
+			$tableData = '';
+			for($time = 0;$time < $sumTime;$time++)
+			{
+				$offset = $time * $this->maxLimit;        //计算读取开始偏移值
+				$data   = $this->getData($name,$offset);  //根据偏移值获取数据
+
+				//数据存在
+				if($data)
+				{
+					$tableData = "INSERT INTO `".$name."` VALUES\r\n";
+				}
+
+				foreach($data as $rs)
+				{
+					$tableData .= "(";
+					foreach($rs as $key => $val)
+					{
+						if(is_int($key)) continue;
+						$tableData .= '\''.addslashes(str_replace(array("\n","\r\n","\r","\t"),"",$val)).'\',';
+					}
+					$tableData  = rtrim($tableData,',');
+					$tableData .= "),\r\n";
+				}
+
+				if($tableData)
+				{
+					$tableData  = rtrim($tableData,",\r\n");
+					$tableData .= ";\r\n\r\n";
+				}
+
+				//表结构和$time次的表数据 总和
+				$content = $tableStruct.$tableData;
+
+				//判断文件是否溢出,如果溢出则分卷
+				if($this->checkOverflow(strlen($content)))
+				{
+					$this->part+=1;
+				}
+
+				//清空数据
+				$tableStruct = '';
+				$tableData   = '';
+				$this->writeFile($this->getFilename(),$content); //写入文件
+			}
+			//回调函数
+			$this->actionCallBack($name);
+		}
+	}
+
+	//写入文件
+	function writeFile($fileName,$content)
+	{
+		$fileObj = new IFile($fileName,'a+');
+		$fileObj->write($content);
+	}
+
+	//检测文件是否存放的数据是否溢出
+	function checkOverflow($cSize)
+	{
+		$this->totalSize+=$cSize;
+		if($this->totalSize >= ($this->partSize<<10)*$this->part)
+			return true;
+		else
+			return false;
+	}
+
+	//生成文件名
+	function getFilename()
+	{
+		if($this->fileName === null)
+		{
+			//获取当前时间:年月日_时分秒
+			$nowTime = date('Ymd_His');
+			$this->fileName = $this->dir.'/'.$this->fPrefix.'_'.$nowTime.'_'.rand(1000000,9999999);
+			return $this->fileName.'_'.$this->part.$this->fExtend;
+		}
+		else
+			return $this->fileName.'_'.$this->part.$this->fExtend;
+	}
+
+	//获取分段数据(数据库)
+	function getData($name,$offset=0)
+	{
+		//创建数据库对象
+		$dbObj = IDBFactory::getDB();
+
+		//获取从$start至$limitNum这段数据
+		$sql   = 'SELECT * FROM '.$name.' LIMIT '.$offset.','.$this->maxLimit;
+		$data  = $dbObj->query($sql);
+		return $data;
+	}
+
+	//计算$name数据表写入次数(数据库)
+	function countTime($name)
+	{
+		$dbObj = IDBFactory::getDB();
+
+		//获取数据表总的数据条数
+		$sql      = 'SELECT COUNT(*) as num FROM '.$name;
+		$numArray = $dbObj->query($sql);
+		$dataNum  = $numArray[0]['num'];
+
+		//计算读取的分页数
+		if($dataNum > 0)
+			return ceil($dataNum/$this->maxLimit);
+		else
+			return 1;
+	}
+
+	//创建$name数据表结构的SQL语句(数据库)
+	function createStructure($name)
+	{
+		//创建数据库对象
+		$dbObj = IDBFactory::getDB();
+
+		//获取表结构创建语句
+		$tableArray  = $dbObj->query('SHOW CREATE TABLE `'.$name.'`');
+		$tableRow    = current($tableArray);
+		$tableString = $tableRow['Create Table'];
+
+		//SQL初始化拼接字符串
+		$bakContent = "DROP TABLE IF EXISTS `".$name."`;\r\n".$tableString.";\r\n\r\n";
+		return $bakContent;
+	}
+}

+ 231 - 0
src/classes/delivery.php

@@ -0,0 +1,231 @@
+<?php
+/**
+ * @copyright (c) 2011 aircheng.com
+ * @file article.php
+ * @brief 订单中配送方式的计算
+ * @author relay
+ * @date 2011-02-24
+ * @version 0.6
+ */
+class Delivery
+{
+	//用户ID
+	public static $user_id = 0;
+
+	//首重重量
+	private static $firstWeight  = 0;
+
+	//次重重量
+	private static $secondWeight = 0;
+
+	/**
+	 * 根据重量计算给定价格
+	 * @param $weight float 总重量
+	 * @param $firstFee float 首重费用
+	 * @param $second float 次重费用
+	 */
+	private static function getFeeByWeight($weight,$firstFee,$secondFee)
+	{
+		//当商品重量小于或等于首重的时候
+		if($weight <= self::$firstWeight)
+		{
+			return $firstFee;
+		}
+
+		//当商品重量大于首重时,根据次重进行累加计算
+		$num = ceil(($weight - self::$firstWeight)/self::$secondWeight);
+		return $firstFee + $secondFee * $num;
+	}
+
+	/**
+	 * @brief 配送方式计算管理模块
+	 * @param $province    int 省份的ID
+	 * @param $delivery_id int 配送方式ID
+	 * @param $goods_id    array 商品ID
+	 * @param $product_id  array 货品ID
+	 * @param $num         array 商品数量
+	 * @return array(
+	 *  id => 配送方式ID,
+	 *  name => 配送方式NAME,
+	 *  description => 配送方式描述,
+	 *	if_delivery => 0:支持配送;1:不支持配送,
+	 *  price => 实际运费总额,
+	 *  protect_price => 商品保价总额,
+	 *  org_price => 原始运费总额,
+	 *	seller_price => array(商家ID => 实际运费),
+	 *	seller_protect_price => array(商家ID => 商品保价),
+	 *  seller_org_price => array(商家ID => 原始运费),
+	 *	)
+	 */
+	public static function getDelivery($province,$delivery_id,$goods_id,$product_id = 0,$num = 1)
+	{
+		//获取默认的配送方式信息
+		$delivery    = new IModel('delivery');
+		$deliveryDefaultRow = $delivery->getObj('is_delete = 0 and status = 1 and id = '.$delivery_id);
+		if(!$deliveryDefaultRow)
+		{
+			return "配送方式不存在";
+		}
+
+		//最终返回结果
+		$result = array(
+			'id'                   => $deliveryDefaultRow['id'],
+			'name'                 => $deliveryDefaultRow['name'],
+			'description'          => $deliveryDefaultRow['description'],
+			'if_delivery'          => 0,
+			'org_price'            => 0,
+			'price'                => 0,
+			'protect_price'        => 0,
+			'seller_org_price'     => array(),
+			'seller_price'         => array(),
+			'seller_protect_price' => array(),
+		);
+
+		//读取全部商品,array('goodsSum' => 商品总价,'weight' => 商品总重量)
+		$sellerGoods   = array();
+		$goods_id      = is_array($goods_id)  ? $goods_id   : array($goods_id);
+		$product_id    = is_array($product_id)? $product_id : array($product_id);
+		$num           = is_array($num)       ? $num        : array($num);
+		foreach($goods_id as $key => $gid)
+		{
+			$pid      = $product_id[$key];
+			$gnum     = $num[$key];
+			if($pid > 0)
+			{
+				$goodsRow = Api::run("getProductInfo",array('#id#',$pid));
+				if(!$goodsRow)
+				{
+					return "计算商品运费货品ID【".$pid."】信息不存在";
+				}
+			}
+			else
+			{
+				$goodsRow = Api::run("getGoodsInfo",array('#id#',$gid));
+				if(!$goodsRow)
+				{
+					return "计算商品运费商品ID【".$gid."】信息不存在";
+				}
+			}
+
+			if(!isset($sellerGoods[$goodsRow['seller_id']]))
+			{
+				$sellerGoods[$goodsRow['seller_id']] = array('goodsSum' => 0,'weight' => 0,'isDeliveryFee' => 1);//个别商品免运费但是要看订单中其他商品设置
+			}
+
+			//商品免运费
+			if(isset($goodsRow['is_delivery_fee']) && $goodsRow['is_delivery_fee'] == 1)
+			{
+				$goodsRow['weight'] = 0;
+			}
+			else
+			{
+				$sellerGoods[$goodsRow['seller_id']]['isDeliveryFee'] = 0;
+			}
+
+			$sellerGoods[$goodsRow['seller_id']]['weight']  += $goodsRow['weight']     * $gnum;
+			$sellerGoods[$goodsRow['seller_id']]['goodsSum']+= $goodsRow['sell_price'] * $gnum;
+		}
+
+		//根据商家不同计算运费
+		$deliveryExtendDB = new IModel('delivery_extend');
+		foreach($sellerGoods as $seller_id => $data)
+		{
+			$weight        = $data['weight'];//计算运费
+			$goodsSum      = $data['goodsSum'];//计算保价
+			$isDeliveryFee = $data['isDeliveryFee'];//是否都是免运费商品
+
+			//使用商家配置的物流运费
+			$seller_id         = IFilter::act($seller_id,'int');
+			$deliverySellerRow = $deliveryExtendDB->getObj('delivery_id = '.$delivery_id.' and seller_id = '.$seller_id);
+			$deliveryRow       = $deliverySellerRow ? $deliverySellerRow : $deliveryDefaultRow;
+
+	 		//设置首重和次重
+	 		self::$firstWeight          = $deliveryRow['first_weight'];
+	 		self::$secondWeight         = $deliveryRow['second_weight'];
+			$deliveryRow['if_delivery'] = '0';
+
+	 		//当配送方式是统一配置的时候,不进行区分地区价格
+	 		if($deliveryRow['price_type'] == 0)
+	 		{
+	 			$deliveryRow['price'] = self::getFeeByWeight($weight,$deliveryRow['first_price'],$deliveryRow['second_price']);
+	 		}
+	 		//当配送方式为指定区域和价格的时候
+	 		else
+	 		{
+				$matchKey = '';
+				$flag     = false;
+
+				//每项都是以';'隔开的省份ID
+				$area_groupid = unserialize($deliveryRow['area_groupid']);
+				if($area_groupid)
+				{
+					foreach($area_groupid as $key => $item)
+					{
+						//匹配到了特殊的省份运费价格
+						if(strpos($item,';'.$province.';') !== false)
+						{
+							$matchKey = $key;
+							$flag     = true;
+							break;
+						}
+					}
+				}
+
+				//匹配到了特殊的省份运费价格
+				if($flag)
+				{
+					//获取当前省份特殊的运费价格
+					$firstprice  = unserialize($deliveryRow['firstprice']);
+					$secondprice = unserialize($deliveryRow['secondprice']);
+
+					$deliveryRow['price'] = self::getFeeByWeight($weight,$firstprice[$matchKey],$secondprice[$matchKey]);
+				}
+				else
+				{
+	     			//判断是否设置默认费用了
+	     			if($deliveryRow['open_default'] == 1)
+	     			{
+	     				$deliveryRow['price'] = self::getFeeByWeight($weight,$deliveryRow['first_price'],$deliveryRow['second_price']);
+	     			}
+	     			else
+	     			{
+	     				$deliveryRow['price']       = '0';
+	     				$deliveryRow['if_delivery'] = '1';
+	     			}
+				}
+	 		}
+
+	 		$deliveryRow['org_price'] = $deliveryRow['price'];
+
+	 		//计算保价
+	 		if($deliveryRow['is_save_price'] == 1)
+	 		{
+	 			$tempProtectPrice             = $goodsSum * ($deliveryRow['save_rate'] * 0.01);
+	 			$deliveryRow['protect_price'] = ($tempProtectPrice <= $deliveryRow['low_price']) ? $deliveryRow['low_price'] : $tempProtectPrice;
+	 		}
+	 		else
+	 		{
+	 			$deliveryRow['protect_price'] = 0;
+	 		}
+
+			//无法送达
+	 		if($deliveryRow['if_delivery'] == 1)
+	 		{
+	 			$deliveryRow['id']          = $deliveryDefaultRow['id'];
+				$deliveryRow['name']        = $deliveryDefaultRow['name'];
+				$deliveryRow['description'] = $deliveryDefaultRow['description'];
+				return $deliveryRow;
+	 		}
+
+			//更新最终数据
+			$result['org_price']         += $deliveryRow['org_price'];
+	 		$result['price']             += $isDeliveryFee == 1 ? 0 : $deliveryRow['price'];
+	 		$result['protect_price']     += $deliveryRow['protect_price'];
+
+			$result['seller_org_price'][$seller_id]     = $deliveryRow['org_price'];
+	 		$result['seller_price'][$seller_id]         = $deliveryRow['price'];
+	 		$result['seller_protect_price'][$seller_id] = $deliveryRow['protect_price'];
+		}
+     	return $result;
+	}
+}

+ 129 - 0
src/classes/expresswaybill.php

@@ -0,0 +1,129 @@
+<?php
+/**
+ * @copyright (c) 2011 [group]
+ * @file expresswaybill.php
+ * @brief 快递单处理类
+ * @author chendeshan
+ * @date 2011-6-15 14:58:39
+ * @version 0.6
+ */
+class Expresswaybill
+{
+	public static $itemData = array(
+		'ship_name'=>'收货人-姓名',
+		'ship_area_0'=>'收货人-地区1级',
+		'ship_area_1'=>'收货人-地区2级',
+		'ship_area_2'=>'收货人-地区3级',
+		'ship_addr'=>'收货人-地址',
+		'ship_tel'=>'收货人-电话',
+		'ship_mobile'=>'收货人-手机',
+		'ship_zip'=>'收货人-邮编',
+		'ship_detail_addr'=>'收货人-地区+详细地址',
+		'dly_name'=>'发货人-姓名',
+		'dly_area_0'=>'发货人-地区1级',
+		'dly_area_1'=>'发货人-地区2级',
+		'dly_area_2'=>'发货人-地区3级',
+		'dly_address'=>'发货人-地址',
+		'dly_tel'=>'发货人-电话',
+		'dly_mobile'=>'发货人-手机',
+		'dly_zip'=>'发货人-邮编',
+		'date_y'=>'当前日期-年',
+		'date_m'=>'当前日期-月',
+		'date_d'=>'当前日期-日',
+		'order_id'=>'订单-订单号',
+		'order_price'=>'订单总金额',
+		'order_weight'=>'订单物品总重量',
+		'order_count'=>'订单-物品数量',
+		'order_memo'=>'订单-备注',
+		'ship_time'=>'订单-送货时间',
+		'shop_name'=>'网店名称',
+		'tick'=>'√ - 对号',
+	);
+
+	//数据转换
+	public function conver($expressConfig,$order_id,$seller_id = 0)
+	{
+		$resultArray = array(); //函数返回数据
+		$wholeData   = array(); //实际的数据
+
+		//获取订单信息
+		$id       = intval($order_id);
+		$orderObj = new IModel('order');
+		$where    = $seller_id ? 'id='.$id.' and seller_id = '.$seller_id : 'id='.$id;
+		$orderRow = $orderObj->getObj($where);
+
+		if(!$orderRow)
+		{
+			return null;
+		}
+
+		//获取发货地址信息
+		$shipInfoObj = new IModel('merch_ship_info');
+		$shipList    = $shipInfoObj->query('is_del = 1 and seller_id = '.$seller_id,'*','is_default desc',1);
+		if(empty($shipList))
+		{
+			$shipRow = array('ship_user_name'=>'','address'=>'','telphone'=>'','mobile'=>'','postcode'=>'','province' => '','city'=>'','area'=>'');
+		}
+		else
+		{
+			$shipRow = $shipList[0];
+		}
+
+		//获取订单总重量和总数量
+		$orderGoodsObj = new IModel('order_goods');
+		$orderTotal    = $orderGoodsObj->getObj('order_id = '.$id,'SUM(goods_nums) as num_total,SUM(goods_weight * goods_nums) as weight_total');
+
+
+		/*拼接实际数据 $wholeData*/
+
+		//查询area地域数据
+		$areaData  = area::name($orderRow['province'],$orderRow['city'],$orderRow['area'],$shipRow['province'],$shipRow['city'],$shipRow['area']);
+
+		//获取site_config配置信息
+		$site_config = new Config('site_config');
+		$site_config = $site_config->getInfo();
+
+		$wholeData['ship_name']   = $orderRow['accept_name'];
+		$wholeData['ship_area_0'] = isset($areaData[$orderRow['province']]) ? $areaData[$orderRow['province']] : '';
+		$wholeData['ship_area_1'] = isset($areaData[$orderRow['city']])     ? $areaData[$orderRow['city']]     : '';
+		$wholeData['ship_area_2'] = isset($areaData[$orderRow['area']])     ? $areaData[$orderRow['area']]     : '';
+		$wholeData['ship_addr']   = $orderRow['address'];
+		$wholeData['ship_tel']    = $orderRow['telphone'];
+		$wholeData['ship_mobile'] = $orderRow['mobile'];
+		$wholeData['ship_zip']    = $orderRow['postcode'];
+		$wholeData['ship_detail_addr'] = $wholeData['ship_area_0'].$wholeData['ship_area_1'].$wholeData['ship_area_2'].$orderRow['address'];
+
+		$wholeData['dly_name']    = $shipRow['ship_user_name'];
+		$wholeData['dly_area_0']  = isset($areaData[$shipRow['province']]) ? $areaData[$shipRow['province']] : '';
+		$wholeData['dly_area_1']  = isset($areaData[$shipRow['city']])     ? $areaData[$shipRow['city']] : '';
+		$wholeData['dly_area_2']  = isset($areaData[$shipRow['area']])     ? $areaData[$shipRow['area']] : '';
+		$wholeData['dly_address'] = $shipRow['address'];
+		$wholeData['dly_tel']     = $shipRow['telphone'];
+		$wholeData['dly_mobile']  = $shipRow['mobile'];
+		$wholeData['dly_zip']     = $shipRow['postcode'];
+
+		$wholeData['date_y']      = date('Y');
+		$wholeData['date_m']      = date('m');
+		$wholeData['date_d']      = date('d');
+
+		$wholeData['order_id']    = $orderRow['order_no'];
+		$wholeData['order_price'] = $orderRow['order_amount'];
+		$wholeData['order_weight'] = isset($orderTotal['weight_total']) ? $orderTotal['weight_total'] : '';
+		$wholeData['order_count']  = isset($orderTotal['num_total'])    ? $orderTotal['num_total'] : '';
+		$wholeData['order_memo']   = $orderRow['note'];
+		$wholeData['ship_time']    = $orderRow['accept_time'];
+		$wholeData['shop_name']    = isset($site_config['name']) ? $site_config['name'] : '';
+		$wholeData['tick']         = '√';
+
+		//进行数据替换
+		foreach($expressConfig as $key => $val)
+		{
+			$item_tmp             = JSON::decode($val);
+			$item_tmp['typeText'] = isset($wholeData[$item_tmp['typeId']]) ? $wholeData[$item_tmp['typeId']] : '';
+			$resultArray[]        = JSON::encode($item_tmp);
+		}
+
+		return $resultArray;
+	}
+}
+?>

+ 73 - 0
src/classes/freight_facade.php

@@ -0,0 +1,73 @@
+<?php
+/**
+ * @copyright Copyright(c) 2014 aircheng.com
+ * @file freight_facade.php
+ * @author nswe
+ * @date 2014/4/18 16:22:33
+ * @version 1.0.0
+ */
+
+/**
+ * @class freight_facade
+ * @brief 快递跟踪接口类
+ */
+class freight_facade
+{
+	//使用的物流接口
+	public static $freightInterface = 'hqepay';
+
+	/**
+	 * @brief 开始快递跟踪
+	 * @param $ShipperCode    string 物流公司编码
+	 * @param $LogisticCode   string 物流单号
+	 */
+	public static function line($ShipperCode,$LogisticCode)
+	{
+		if( $freightObj = self::createObject() )
+		{
+			return $freightObj->line($ShipperCode,$LogisticCode);
+		}
+	}
+
+	/**
+	 * @brief 创建物流接口实力
+	 * @return object 快递跟踪类实例
+	 */
+	private static function createObject()
+	{
+		//类库路径
+		$basePath   = IWeb::$app->getBasePath().'plugins/freight/';
+
+		//配置参数
+		$siteConfig = new Config('site_config');
+
+		switch(self::$freightInterface)
+		{
+			default:
+			{
+				include($basePath.'hqepay.php');
+				return new Hqepay($siteConfig->freightid,$siteConfig->freightkey);
+			}
+		}
+	}
+}
+
+/**
+ * @brief 物流开发接口
+ */
+interface freight_inter
+{
+	/**
+	 * @brief 物流快递轨迹查询
+	 * @param $ShipperCode string 物流公司快递号
+	 * @param $LogisticCode string 快递单号
+	 */
+	public function line($ShipperCode,$LogisticCode);
+
+	/**
+	 * @brief 处理返回数据统一数据格式
+	 * @param $result 结果处理
+	 * @return array 通用的结果集 array('result' => 'success或者fail','data' => array( array('time' => '时间','station' => '地点'),......),'reason' => '失败原因')
+	 */
+	public function response($result);
+}

+ 1079 - 0
src/classes/goods_class.php

@@ -0,0 +1,1079 @@
+<?php
+/**
+ * @copyright (c) 2011 aircheng.com
+ * @file goods_class.php
+ * @brief 商品管理类库
+ * @author nswe
+ * @date 2014/8/18 11:53:43
+ * @version 2.6
+ */
+class goods_class
+{
+	//算账类库
+	private static $countsumInstance = null;
+
+	//商户ID
+	public $seller_id = '';
+
+	//构造函数
+	public function __construct($seller_id = '')
+	{
+		$this->seller_id = $seller_id;
+	}
+
+	/**
+	 * 获取商品价格
+	 * @param int $goods_id 商品ID
+	 * @param float $sell_price 商品销售价
+	 */
+	public static function price($goods_id,$sell_price)
+	{
+		if(self::$countsumInstance == null)
+		{
+			self::$countsumInstance = new CountSum();
+		}
+		$price = self::$countsumInstance->getGroupPrice($goods_id);
+		return $price ? $price : $sell_price;
+	}
+
+	/**
+	 * 生成商品货号
+	 * @return string 货号
+	 */
+	public static function createGoodsNo()
+	{
+		$config = new Config('site_config');
+		return $config->goods_no_pre.time().rand(10,99);
+	}
+
+	/**
+	 * @brief 修改商品数据
+	 * @param int $id 商品ID
+	 * @param array $postData 商品所需数据,键名分为"_"前缀和非"_"前缀,非"_"前缀的是goods表的字段
+	 */
+	public function update($id,$postData)
+	{
+		$goodsUpdateData = array();//更新到goods表的字段数据
+		$nowDataTime = ITime::getDateTime();
+
+		foreach($postData as $key => $val)
+		{
+			//数据过滤分组
+			if(strpos($key,'attr_id_') !== false)
+			{
+				$goodsAttrData[ltrim($key,'attr_id_')] = IFilter::act($val);
+			}
+			//对应goods表字段
+			else if($key[0] != '_')
+			{
+				$goodsUpdateData[$key] = IFilter::addSlash($val);
+			}
+		}
+
+		//商家发布商品默认设置
+		if($this->seller_id)
+		{
+			$goodsUpdateData['seller_id'] = $this->seller_id;
+			$goodsUpdateData['is_del'] = $goodsUpdateData['is_del'] == 2 ? 2 : 3;
+
+			//如果商户是VIP则无需审核商品
+			if($goodsUpdateData['is_del'] == 3)
+			{
+				$sellerDB = new IModel('seller');
+				$sellerRow= $sellerDB->getObj('id = '.$this->seller_id);
+				if($sellerRow['is_vip'] == 1)
+				{
+					$goodsUpdateData['is_del'] = 0;
+				}
+			}
+		}
+
+		//上架或者下架处理
+		if(isset($goodsUpdateData['is_del']))
+		{
+			//上架
+			if($goodsUpdateData['is_del'] == 0)
+			{
+				$goodsUpdateData['up_time']   = $nowDataTime;
+				$goodsUpdateData['down_time'] = null;
+			}
+			//下架
+			else if($goodsUpdateData['is_del'] == 2)
+			{
+				$goodsUpdateData['up_time']  = null;
+				$goodsUpdateData['down_time']= $nowDataTime;
+			}
+			//审核或者删除
+			else
+			{
+				$goodsUpdateData['up_time']   = null;
+				$goodsUpdateData['down_time'] = null;
+			}
+		}
+
+		//是否存在货品
+		$goodsUpdateData['spec_array'] = '';
+		if(isset($postData['_spec_array']))
+		{
+			//生成goods中的spec_array字段数据
+			$goods_spec_array = array();
+			foreach($postData['_spec_array'] as $key => $val)
+			{
+				foreach($val as $v)
+				{
+					$tempSpec = JSON::decode($v);
+					if(!isset($goods_spec_array[$tempSpec['id']]))
+					{
+						$goods_spec_array[$tempSpec['id']] = array('id' => $tempSpec['id'],'name' => $tempSpec['name'],'type' => $tempSpec['type'],'value' => array());
+					}
+
+					if(!in_array(array($tempSpec['tip'] => $tempSpec['value']),$goods_spec_array[$tempSpec['id']]['value']))
+					{
+						$goods_spec_array[$tempSpec['id']]['value'][] = array($tempSpec['tip'] => $tempSpec['value']);
+					}
+				}
+			}
+			$goodsUpdateData['spec_array'] = IFilter::act(JSON::encode($goods_spec_array));
+		}
+
+		//用sell_price最小的货品填充商品表
+		$defaultKey = array_search(min($postData['_sell_price']),$postData['_sell_price']);
+
+		//赋值goods表默认数据
+		$goodsUpdateData['name']         = IFilter::act($goodsUpdateData['name']);
+		$goodsUpdateData['goods_no']     = isset($postData['_goods_no'][$defaultKey])     ? IFilter::act($postData['_goods_no'][$defaultKey])             : '';
+		$goodsUpdateData['market_price'] = isset($postData['_market_price'][$defaultKey]) ? IFilter::act($postData['_market_price'][$defaultKey],'float') : 0;
+		$goodsUpdateData['sell_price']   = isset($postData['_sell_price'][$defaultKey])   ? IFilter::act($postData['_sell_price'][$defaultKey],'float')   : 0;
+		$goodsUpdateData['cost_price']   = isset($postData['_cost_price'][$defaultKey])   ? IFilter::act($postData['_cost_price'][$defaultKey],'float')   : 0;
+		$goodsUpdateData['weight']       = isset($postData['_weight'][$defaultKey])       ? IFilter::act($postData['_weight'][$defaultKey],'float')       : 0;
+		$goodsUpdateData['store_nums']   = IFilter::act(array_sum($postData['_store_nums']),'int');
+
+		if(isset($postData['_imgList']) && $postData['_imgList'])
+		{
+			$postData['_imgList']   = trim($postData['_imgList'],',');
+			$postData['_imgList']   = explode(",",$postData['_imgList']);
+			$postData['_imgList']   = array_filter($postData['_imgList']);
+			$goodsUpdateData['img'] = $goodsUpdateData['img'] ? $goodsUpdateData['img'] : current($postData['_imgList']);
+		}
+
+		//处理商品
+		$goodsDB = new IModel('goods');
+		if($id)
+		{
+			$goodsDB->setData($goodsUpdateData);
+
+			$where = " id = {$id} ";
+			if($this->seller_id)
+			{
+				$where .= " and seller_id = ".$this->seller_id;
+			}
+
+			if($goodsDB->update($where) <= 0)
+			{
+				$goodsDB->rollback();
+				die("更新商品错误");
+			}
+		}
+		else
+		{
+			$goodsUpdateData['create_time'] = $nowDataTime;
+			$goodsDB->setData($goodsUpdateData);
+			$id = $goodsDB->add();
+			if(!$id)
+			{
+				$goodsDB->rollback();
+				die("添加商品失败");
+			}
+		}
+
+		//处理商品属性
+		$goodsAttrDB = new IModel('goods_attribute');
+		$goodsAttrDB->del('goods_id = '.$id);
+		if($goodsUpdateData['model_id'] > 0 && isset($goodsAttrData) && $goodsAttrData)
+		{
+			foreach($goodsAttrData as $key => $val)
+			{
+				$attrData = array(
+					'goods_id' => $id,
+					'model_id' => $goodsUpdateData['model_id'],
+					'attribute_id' => $key,
+					'attribute_value' => is_array($val) ? join(',',$val) : $val
+				);
+				$goodsAttrDB->setData($attrData);
+				$goodsAttrDB->add();
+			}
+		}
+
+		//处理货品数据信息
+		$productsDB = new IModel('products');
+		if(isset($postData['_spec_array']))
+		{
+			//是否存在货品
+			$proList = $productsDB->query('goods_id = '.$id,'id,products_no');
+
+			//货号和ID关系
+			$relationPro = array();
+			if($proList)
+			{
+				foreach($proList as $key => $val)
+				{
+					$relationPro[$val['products_no']] = $val['id'];
+				}
+			}
+
+			//创建货品信息
+			$productIdArray = array();//post数据次序和ID关系
+			foreach($postData['_goods_no'] as $key => $rs)
+			{
+				$productsData = array(
+					'goods_id'     => $id,
+					'products_no'  => IFilter::act($postData['_goods_no'][$key]),
+					'store_nums'   => IFilter::act($postData['_store_nums'][$key],'int'),
+					'market_price' => IFilter::act($postData['_market_price'][$key],'float'),
+					'sell_price'   => IFilter::act($postData['_sell_price'][$key],'float'),
+					'cost_price'   => IFilter::act($postData['_cost_price'][$key],'float'),
+					'weight'       => IFilter::act($postData['_weight'][$key],'float'),
+					'spec_array'   => "[".join(',',IFilter::act($this->specArraySort($postData['_spec_array'][$key])))."]"
+				);
+				$productsData['id'] = 'NULL';
+				if(isset($relationPro[$rs]))
+				{
+					$productsData['id'] = $relationPro[$rs];
+					unset($relationPro[$rs]);
+				}
+				$productsDB->setData($productsData,'id');
+				$productIdArray[$key] = $productsDB->replace();
+			}
+			//清理残余的货品
+			if($relationPro)
+			{
+				$productsDB->del('id in ('.join(",",$relationPro).')');
+			}
+		}
+		else
+		{
+			$productsDB->del('goods_id = '.$id);
+		}
+
+		//处理商品分类
+		$categoryDB = new IModel('category_extend');
+		$categoryDB->del('goods_id = '.$id);
+		if(isset($postData['_goods_category']) && $postData['_goods_category'])
+		{
+			foreach($postData['_goods_category'] as $item)
+			{
+				$item = IFilter::act($item,'int');
+				$categoryDB->setData(array('goods_id' => $id,'category_id' => $item));
+				$categoryDB->add();
+			}
+		}
+
+		//处理商品促销
+		$commendDB = new IModel('commend_goods');
+		$commendDB->del('goods_id = '.$id);
+		if(isset($postData['_goods_commend']) && $postData['_goods_commend'])
+		{
+			foreach($postData['_goods_commend'] as $item)
+			{
+				$item = IFilter::act($item,'int');
+				$commendDB->setData(array('goods_id' => $id,'commend_id' => $item));
+				$commendDB->add();
+			}
+		}
+
+		//处理商品关键词
+		keywords::add($goodsUpdateData['search_words']);
+
+		//处理商品图片
+		$photoRelationDB = new IModel('goods_photo_relation');
+		$photoRelationDB->del('goods_id = '.$id);
+		if(isset($postData['_imgList']) && $postData['_imgList'])
+		{
+			$photoDB = new IModel('goods_photo');
+			foreach($postData['_imgList'] as $key => $val)
+			{
+				$val = IFilter::act($val);
+				$photoPic = $photoDB->getObj('img = "'.$val.'"','id');
+				if($photoPic)
+				{
+					$photoRelationDB->setData(array('goods_id' => $id,'photo_id' => $photoPic['id']));
+					$photoRelationDB->add();
+				}
+			}
+		}
+
+		//处理会员组的价格
+		$groupPriceDB = new IModel('group_price');
+		$groupPriceDB->del('goods_id = '.$id);
+		if(isset($productIdArray) && $productIdArray)
+		{
+			foreach($productIdArray as $index => $value)
+			{
+				if(isset($postData['_groupPrice'][$index]) && $postData['_groupPrice'][$index])
+				{
+					$temp = JSON::decode($postData['_groupPrice'][$index]);
+					foreach($temp as $k => $v)
+					{
+						$groupPriceDB->setData(array(
+							'goods_id'   => $id,
+							'product_id' => IFilter::act($value,'int'),
+							'group_id'   => IFilter::act($k,'int'),
+							'price'      => IFilter::act($v,'float'),
+						));
+						$groupPriceDB->add();
+					}
+				}
+			}
+		}
+		else
+		{
+			if(isset($postData['_groupPrice'][0]) && $postData['_groupPrice'][0])
+			{
+				$temp = JSON::decode($postData['_groupPrice'][0]);
+				foreach($temp as $k => $v)
+				{
+					$groupPriceDB->setData(array(
+						'goods_id' => $id,
+						'group_id' => IFilter::act($k,'int'),
+						'price'    => IFilter::act($v,'float'),
+					));
+					$groupPriceDB->add();
+				}
+			}
+		}
+		return $id;
+	}
+
+	/**
+	* @brief 删除与商品相关表中的数据
+	*/
+	public function del($goods_id)
+	{
+		$goodsWhere = " id = '{$goods_id}' ";
+		if($this->seller_id)
+		{
+			$goodsWhere .= " and seller_id = ".$this->seller_id;
+		}
+
+		//图片清理
+		$tb_photo_relation = new IModel('goods_photo_relation');
+		$photoMD5Data      = $tb_photo_relation->query('goods_id = '.$goods_id);
+
+		$tb_photo          = new IModel('goods_photo');
+		foreach($photoMD5Data as $key => $md5)
+		{
+			//图片是否被其他商品共享占用
+			$isUserd = $tb_photo_relation->getObj('photo_id = "'.$md5['photo_id'].'" and goods_id != '.$goods_id);
+			if(!$isUserd)
+			{
+				$imgData = $tb_photo->getObj('id = "'.$md5['photo_id'].'"');
+				isset($imgData['img']) ? IFile::unlink($imgData['img']) : "";
+				$tb_photo->del('id = "'.$md5['photo_id'].'"');
+			}
+		}
+		$tb_photo_relation->del('goods_id = '.$goods_id);
+
+		//删除商品表
+		$tb_goods = new IModel('goods');
+		$goodsRow = $tb_goods->getObj($goodsWhere,"content");
+		if(isset($goodsRow['content']) && $goodsRow['content'])
+		{
+			preg_match_all('%src="(/.*?(?:.jpg|.png|.gif))"%i',$goodsRow['content'],$result);
+			if($result && isset($result[1]) && is_array($result[1]))
+			{
+				foreach($result[1] as $detailPic)
+				{
+					$detailPic = IWeb::$app->getBasePath().stristr($detailPic,IWeb::$app->config['upload']);
+					is_file($detailPic) ? IFile::unlink($detailPic) : "";
+				}
+			}
+		}
+		$tb_goods ->del($goodsWhere);
+	}
+	/**
+	 * 获取编辑商品所有数据
+	 * @param int $id 商品ID
+	 */
+	public function edit($id)
+	{
+		$id = IFilter::act($id,'int');
+		$goodsWhere = " id = {$id} ";
+		if($this->seller_id)
+		{
+			$goodsWhere .= " and seller_id = ".$this->seller_id;
+		}
+
+		//获取商品
+		$obj_goods = new IModel('goods');
+		$goods_info = $obj_goods->getObj($goodsWhere);
+
+		if(!$goods_info)
+		{
+			return null;
+		}
+
+		//获取商品的会员价格
+		$groupPriceDB = new IModel('group_price');
+		$goodsPrice   = $groupPriceDB->query("goods_id = ".$goods_info['id']." and product_id is NULL ");
+		$temp = array();
+		foreach($goodsPrice as $key => $val)
+		{
+			$temp[$val['group_id']] = $val['price'];
+		}
+		$goods_info['groupPrice'] = $temp ? JSON::encode($temp) : '';
+
+		//赋值到FORM用于渲染
+		$data = array('form' => $goods_info);
+
+		//获取货品
+		$productObj = new IModel('products');
+		$product_info = $productObj->query('goods_id = '.$id);
+		if($product_info)
+		{
+			//获取货品会员价格
+			foreach($product_info as $k => $rs)
+			{
+				$temp = array();
+				$productPrice = $groupPriceDB->query('product_id = '.$rs['id']);
+				foreach($productPrice as $key => $val)
+				{
+					$temp[$val['group_id']] = $val['price'];
+				}
+				$product_info[$k]['groupPrice'] = $temp ? JSON::encode($temp) : '';
+			}
+			$data['product'] = $product_info;
+		}
+
+		//加载推荐类型
+		$tb_commend_goods = new IModel('commend_goods');
+		$commend_goods = $tb_commend_goods->query('goods_id='.$goods_info['id'],'commend_id');
+		if($commend_goods)
+		{
+			foreach($commend_goods as $value)
+			{
+				$data['goods_commend'][] = $value['commend_id'];
+			}
+		}
+
+		//相册
+		$tb_goods_photo = new IQuery('goods_photo_relation as ghr');
+		$tb_goods_photo->join = 'left join goods_photo as gh on ghr.photo_id=gh.id';
+		$tb_goods_photo->fields = 'gh.img';
+		$tb_goods_photo->where = 'ghr.goods_id='.$goods_info['id'];
+		$tb_goods_photo->order = 'ghr.id asc';
+		$data['goods_photo'] = $tb_goods_photo->find();
+
+		//扩展基本属性
+		$goodsAttr = new IQuery('goods_attribute');
+		$goodsAttr->where = "goods_id=".$goods_info['id']." and attribute_id != '' ";
+		$attrInfo = $goodsAttr->find();
+		if($attrInfo)
+		{
+			foreach($attrInfo as $item)
+			{
+				//key:属性名;val:属性值,多个属性值以","分割
+				$data['goods_attr'][$item['attribute_id']] = $item['attribute_value'];
+			}
+		}
+
+		//商品分类
+		$categoryExtend = new IQuery('category_extend');
+		$categoryExtend->where = 'goods_id = '.$goods_info['id'];
+		$tb_goods_photo->fields = 'category_id';
+		$cateData = $categoryExtend->find();
+		if($cateData)
+		{
+			foreach($cateData as $item)
+			{
+				$data['goods_category'][] = $item['category_id'];
+			}
+		}
+		return $data;
+	}
+	/**
+	 * @param
+	 * @return array
+	 * @brief 无限极分类递归函数
+	 */
+	public static function sortdata($catArray, $id = 0 , $prefix = '')
+	{
+		static $formatCat = array();
+		static $floor     = 0;
+
+		foreach($catArray as $key => $val)
+		{
+			if($val['parent_id'] == $id)
+			{
+				$str         = self::nstr($prefix,$floor);
+				$val['name'] = $str.$val['name'];
+
+				$val['floor'] = $floor;
+				$formatCat[]  = $val;
+
+				unset($catArray[$key]);
+
+				$floor++;
+				self::sortdata($catArray, $val['id'] ,$prefix);
+				$floor--;
+			}
+		}
+		return $formatCat;
+	}
+
+	/**
+	 * @brief 根据商品分类的父类ID进行数据归类
+	 * @param array $categoryData 商品category表的结构数组
+	 * @return array
+	 */
+	public static function categoryParentStruct($categoryData)
+	{
+		$result = array();
+		foreach($categoryData as $key => $val)
+		{
+			if(isset($result[$val['parent_id']]) && is_array($result[$val['parent_id']]))
+			{
+				$result[$val['parent_id']][] = $val;
+			}
+			else
+			{
+				$result[$val['parent_id']] = array($val);
+			}
+		}
+		return $result;
+	}
+
+	/**
+	 * @brief 计算商品的价格区间
+	 * @param $min          最小价格
+	 * @param $max          最大价格
+	 * @param $showPriceNum 展示分组最大数量
+	 * @return array        价格区间分组
+	 */
+	public static function getGoodsPrice($min,$max,$showPriceNum = 5)
+	{
+		$goodsPrice = array("min" => $min,"max" => $max);
+		if($goodsPrice['min'] == null && $goodsPrice['max'] == null)
+		{
+			return array();
+		}
+
+		if($goodsPrice['min'] <= 0)
+		{
+			$minPrice = 1;
+			$result = array('0-'.$minPrice);
+		}
+		else
+		{
+			$minPrice = ceil($goodsPrice['min']);
+			$result = array('1-'.$minPrice);
+		}
+
+		//商品价格计算
+		$perPrice = ceil(($goodsPrice['max'] - $minPrice)/($showPriceNum - 1));
+
+		if($perPrice > 0)
+		{
+			for($addPrice = $minPrice+1; $addPrice < $goodsPrice['max'];)
+			{
+				$stepPrice = $addPrice + $perPrice;
+				$stepPrice = substr(intval($stepPrice),0,1).str_repeat('9',(strlen(intval($stepPrice)) - 1));
+				$result[]  = $addPrice.'-'.$stepPrice;
+				$addPrice  = $stepPrice + 1;
+			}
+		}
+		return $result;
+	}
+
+	//处理商品列表显示缩进
+	public static function nstr($str,$num=0)
+	{
+		$return = '';
+		for($i=0;$i<$num;$i++)
+		{
+			$return .= $str;
+		}
+		return $return;
+	}
+
+	/**
+	 * @brief  根据分类ID获取其全部父分类数据(自下向上的获取数据)
+	 * @param  int   $catId  分类ID
+	 * @return array $result array(array(父分类1_ID => 父分类2_NAME),....array(子分类ID => 子分类NAME))
+	 */
+	public static function catRecursion($catId)
+	{
+		$result = array();
+		$catDB  = new IModel('category');
+		$catRow = $catDB->getObj("id = '{$catId}'");
+		while(true)
+		{
+			if($catRow)
+			{
+				array_unshift($result,array('id' => $catRow['id'],'name' => $catRow['name']));
+				$catRow = $catDB->getObj('id = '.$catRow['parent_id']);
+			}
+			else
+			{
+				break;
+			}
+		}
+		return $result;
+	}
+
+	/**
+	 * @brief 优先获取子分类,如果为空再获取其兄弟分类
+	 * @param int $catId 分类ID
+	 * @return array
+	 */
+	public static function catTree($catId)
+	{
+		$result    = array();
+		$catDB     = new IModel('category');
+		$childList = $catDB->query("parent_id = '{$catId}'","*","sort asc");
+		if(!$childList)
+		{
+			$catRow = $catDB->getObj("id = '{$catId}'");
+			$childList = $catDB->query('parent_id = '.$catRow['parent_id'],"*","sort asc");
+		}
+		return $childList;
+	}
+
+	/**
+	 * @brief 获取子分类可以无限递归获取子分类
+	 * @param int $catId 分类ID
+	 * @param int $level 层级数
+	 * @return string 所有分类的ID拼接字符串
+	 */
+	public static function catChild($catId,$level = 1)
+	{
+		if($level == 0)
+		{
+			return $catId;
+		}
+
+		$temp   = array();
+		$result = array($catId);
+		$catDB  = new IModel('category');
+
+		while(true)
+		{
+			$id = current($result);
+			if(!$id)
+			{
+				break;
+			}
+			$temp = $catDB->query('parent_id = '.$id);
+			foreach($temp as $key => $val)
+			{
+				if(!in_array($val['id'],$result))
+				{
+					$result[] = $val['id'];
+				}
+			}
+			next($result);
+		}
+		return join(',',$result);
+	}
+
+	/**
+	 * @brief 返回商品状态
+	 * @param int $is_del 商品状态
+	 * @return string 状态文字
+	 */
+	public static function statusText($is_del)
+	{
+		$date = array('0' => '上架','1' => '删除','2' => '下架','3' => '等审');
+		return isset($date[$is_del]) ? $date[$is_del] : '';
+	}
+
+	public static function getGoodsCategory($goods_id){
+
+		$gcQuery         = new IQuery('category_extend as ce');
+		$gcQuery->join   = "left join category as c on c.id = ce.category_id";
+		$gcQuery->where  = "ce.goods_id = '{$goods_id}'";
+		$gcQuery->fields = 'c.name';
+
+		$gcList = $gcQuery->find();
+		$strCategoryNames = '';
+		foreach($gcList as $val){
+			$strCategoryNames .= $val['name'] . ',';
+		}
+		unset($gcQuery,$gcList);
+		return $strCategoryNames;
+	}
+
+	/**
+	 * @brief 返回检索条件相关信息
+	 * @param int $search 条件数组
+	 * @return array 查询条件($join,$where)数据组
+	 */
+	public static function getSearchCondition($search)
+	{
+		$join  = array();
+		$where = array();
+
+		//条件筛选处理
+		if(isset($search['name']) && isset($search['keywords']))
+		{
+			$name     = IFilter::act($search['name'], 'string');
+			$keywords = IFilter::act($search['keywords'], 'string');
+			if($keywords)
+			{
+				if($name == "seller.true_name")
+				{
+					$sellerDB = new IModel('seller');
+					$sellerRow= $sellerDB->getObj('true_name like "%'.$keywords.'%"');
+					$seller_id= isset($sellerRow['id']) ? $sellerRow['id'] : "NULL";
+					$where[]  = "go.seller_id = ".$seller_id;
+				}
+				else
+				{
+					$where[] = $name." like '%".$keywords."%'";
+				}
+			}
+		}
+
+		if(isset($search['category_id']))
+		{
+			$category_id = IFilter::act($search['category_id'], 'int');
+			if (0 < $category_id)
+			{
+				$join[]  = "left join category_extend as ce on ce.goods_id = go.id";
+				$where[] = "ce.category_id = ".$category_id;
+			}
+		}
+
+		if(isset($search['is_del']) && $search['is_del'] !== '')
+		{
+			$is_del  = IFilter::act($search['is_del'], 'int');
+			$where[] = "go.is_del = ".$is_del;
+		}
+		else
+		{
+			$where[] = "go.is_del != 1";
+		}
+
+		if(isset($search['store_nums']))
+		{
+			$store_nums = IFilter::act($search['store_nums'], 'string');
+			if ('' != $store_nums)
+			{
+				$store_nums = htmlspecialchars_decode($store_nums);
+				$where[] = $store_nums;
+			}
+		}
+
+		if(isset($search['commend_id']))
+		{
+			$commend_id = IFilter::act($search['commend_id'], 'int');
+			if (0 < $commend_id)
+			{
+				$join[] = "left join commend_goods as cg on go.id = cg.goods_id";
+				$where[]= "cg.commend_id = ".$commend_id;
+			}
+		}
+
+		if(isset($search['seller_id']))
+		{
+			$seller_id = IFilter::act($search['seller_id'], 'string');
+			if ('' != $seller_id)
+			{
+				$where[] = "go.seller_id ".$seller_id;
+			}
+		}
+		// 高级筛选
+		if (isset($search['adv_search']) && 1 == $search['adv_search'])
+		{
+			if (isset($search['brand_id']) && !empty($search['brand_id']))
+			{
+				$brand_id = IFilter::act($search['brand_id'], 'int');
+				$where[] = "go.brand_id = ".$brand_id;
+			}
+			if (isset($search['sell_price']) && !empty($search['sell_price']))
+			{
+				$sell_price = explode(",", $search['sell_price']);
+				$sell_price_0 = IFilter::act($sell_price[0], 'float');
+				if (isset($sell_price[1]))
+				{
+					$sell_price_1 = IFilter::act($sell_price[1], 'float');
+				}
+				else
+				{
+					$sell_price_1 = 0;
+				}
+				if ($sell_price_0 == $sell_price_1)
+				{
+					$where[] = "go.sell_price = $sell_price_0";
+				}
+				else if ($sell_price_0 > $sell_price_1)
+				{
+					$where[] = "go.sell_price between $sell_price_1 and $sell_price_0";
+				}
+				else
+				{
+					$where[] = "go.sell_price between $sell_price_0 and $sell_price_1";
+				}
+			}
+			if (isset($search['create_time']) && !empty($search['create_time']))
+			{
+				$create_time = explode(",", $search['create_time']);
+				// 验证日期
+				$is_check_0 = ITime::checkDateTime($create_time[0]);
+				$is_check_1 = false;
+				if (isset($create_time[1]))
+				{
+					$is_check_1 = ITime::checkDateTime($create_time[1]);
+				}
+				if ($is_check_0 && $is_check_1)
+				{
+					// 是否相等
+					if ($create_time[0] == $create_time[1])
+					{
+						$where[] = "go.create_time between '".$create_time[0]." 00:00:00' and '".$create_time[0]." 23:59:59'";
+					}
+					else
+					{
+						$difference = ITime::getDiffSec($create_time[0].' 00:00:00', $create_time[1].' 00:00:00');
+						if (0 < $difference)
+						{
+							$where[] = "go.create_time between '".$create_time[1]." 00:00:00' and '".$create_time[0]." 23:59:59'";
+						}
+						else
+						{
+							$where[] = "go.create_time between '".$create_time[0]." 00:00:00' and '".$create_time[1]." 23:59:59'";
+						}
+					}
+				}
+				elseif ($is_check_0)
+				{
+					$where[] = "go.create_time between '".$create_time[0]." 00:00:00' and '".$create_time[0]." 23:59:59'";
+				}
+			}
+		}
+		$results = array(join("  ",$join),join(" and ",$where));
+		unset($join,$where);
+		return $results;
+	}
+
+	/**
+	 * @brief 检查商品或者货品的库存是否充足
+	 * @param $buy_num 检查数量
+	 * @param $goods_id 商品id
+	 * @param $product_id 货品id
+	 * @result array() true:满足数量; false:不满足数量
+	 */
+	public static function checkStore($buy_num,$goods_id,$product_id = 0)
+	{
+		$data = $product_id ? Api::run('getProductInfo',array('#id#',$product_id)) : Api::run('getGoodsInfo',array('#id#',$goods_id));
+
+		//库存判断
+		if(!$data || $buy_num <= 0 || $buy_num > $data['store_nums'])
+		{
+			return false;
+		}
+		return true;
+	}
+
+	/**
+	 * @brief 商品根据折扣更新价格
+	 * @param string or int $goods_id 商品id
+	 * @param float $discount 折扣
+	 * @param string $discountType 打折的类型: percent 百分比, constant 常数
+	 * @param string reduce or add 减少或者增加
+	 */
+	public static function goodsDiscount($goods_id,$discount,$discountType = "percent",$type = "reduce")
+	{
+		//减少
+		if($type == "reduce")
+		{
+			if($discountType == "percent")
+			{
+				$updateData = array("sell_price" => "sell_price * ".$discount/100);
+			}
+			else
+			{
+				$updateData = array("sell_price" => "sell_price - ".$discount);
+			}
+		}
+		//增加
+		else
+		{
+			if($discountType == "percent")
+			{
+				$updateData = array("sell_price" => "sell_price / ".$discount/100);
+			}
+			else
+			{
+				$updateData = array("sell_price" => "sell_price + ".$discount);
+			}
+		}
+
+		//更新商品
+		$goodsDB = new IModel('goods');
+		$goodsDB->setData($updateData);
+		$goodsDB->update("id in (".$goods_id.")","sell_price");
+
+		//更新货品
+		$productDB = new IModel('products');
+		$productDB->setData($updateData);
+		$productDB->update("goods_id in (".$goods_id.")","sell_price");
+	}
+
+	/**
+	 * @brief 批量修改商品数据
+	 * @param array $idArray 商品ID数组
+	 * @param array $paramData 商品设置数据
+	 */
+	public function multiUpdate($idArray,$paramData)
+	{
+		$goods_id   = implode(",", $idArray);
+		$updateData = array();
+
+		// 所属商户(只有管理员才可以设置)
+		if ($this->seller_id == 0 && isset($paramData['sellerid']) && '-1' != $paramData['sellerid'])
+		{
+			$updateData['seller_id'] = IFilter::act($paramData['sellerid'], 'int');
+		}
+		// 市场价格
+		$market_price = isset($paramData['market_price']) ? IFilter::act($paramData['market_price'], 'float') : 0;
+		if (0 < $market_price)
+		{
+			$market_price_operator = $this->getOperator($paramData['market_price_type']);
+			$updateData['market_price'] = "market_price".$market_price_operator.$market_price;
+		}
+		// 销售价格
+		$sell_price = isset($paramData['sell_price']) ? IFilter::act($paramData['sell_price'], 'float') : 0;
+		if (0 < $sell_price)
+		{
+			$sell_price_operator = $this->getOperator($paramData['sell_price_type']);
+			$updateData['sell_price'] = "sell_price".$sell_price_operator.$sell_price;
+		}
+		// 成本价格
+		$cost_price = isset($paramData['cost_price']) ? IFilter::act($paramData['cost_price'], 'float') : 0;
+		if (0 < $cost_price)
+		{
+			$cost_price_operator = $this->getOperator($paramData['cost_price_type']);
+			$updateData['cost_price'] = "cost_price".$cost_price_operator.$cost_price;
+		}
+		// 库存
+		$store_nums = isset($paramData['store_nums']) ? IFilter::act($paramData['store_nums'], 'int') : 0;
+		if (0 < $store_nums)
+		{
+			$store_nums_operator = $this->getOperator($paramData['store_nums_type']);
+			$updateData['store_nums'] = "store_nums".$store_nums_operator.$store_nums;
+		}
+		// 积分
+		$point = isset($paramData['point']) ? IFilter::act($paramData['point'], 'int') : 0;
+		if (0 < $point)
+		{
+			$point_operator = $this->getOperator($paramData['point_type']);
+			$updateData['point'] = "point".$point_operator.$point;
+		}
+		// 经验
+		$exp = isset($paramData['exp']) ? IFilter::act($paramData['exp'], 'int') : 0;
+		if (0 < $exp)
+		{
+			$exp_operator = $this->getOperator($paramData['exp_type']);
+			$updateData['exp'] = "exp".$exp_operator.$exp;
+		}
+		// 商品品牌
+		if ('-1' != $paramData['brand_id'])
+		{
+			$updateData['brand_id'] = IFilter::act($paramData['brand_id'], 'int');
+		}
+
+		// 批量更新商品
+		if (!empty($updateData))
+		{
+			$except = array('market_price','sell_price','cost_price','store_nums','point','exp');
+			$goodsDB = new IModel('goods');
+			$goodsDB->setData($updateData);
+			$where = "id in (".$goods_id.")";
+			$where.= $this->seller_id ? " and seller_id = ".$this->seller_id : "";
+			$result = $goodsDB->update($where,$except);
+
+			// 批量更新货品表
+			$exceptProducts = array('store_nums','market_price','sell_price','cost_price');
+			$updateDataProducts = array();
+			foreach ($updateData as $key => $value)
+			{
+				if (in_array($key, $exceptProducts))
+				{
+					$updateDataProducts[$key] = $value;
+				}
+			}
+			if (0 < count($updateDataProducts))
+			{
+				$productsDB = new IModel('products');
+				$productsDB->setData($updateDataProducts);
+				$whereProducts = "goods_id in (".$goods_id.")";
+				$resultProducts = $productsDB->update($whereProducts, $exceptProducts);
+
+				$productObj = new IQuery('products as pro');
+				$productObj->where = $whereProducts;
+				$productObj->fields = "pro.goods_id, sum(pro.store_nums) AS sum_store_nums, min(pro.market_price) as min_market_price, min(pro.sell_price) as min_sell_price, min(pro.cost_price) as min_cost_price";
+				$productObj->group = "pro.goods_id";
+
+				$productList = $productObj->find();
+
+				foreach ($productList as $key => $val)
+				{
+					$tempData = array(
+						'store_nums' => $val['sum_store_nums'],
+						'market_price' => $val['min_market_price'],
+						'sell_price' => $val['min_sell_price'],
+						'cost_price' => $val['min_cost_price']
+					);
+					$goodsDB->setData($tempData);
+					$tempWhere = "id=".$val['goods_id']."";
+					$tempResult = $goodsDB->update($tempWhere);
+				}
+			}
+		}
+
+		// 商品分类
+		if (isset($paramData['category']) && !empty($paramData['category']))
+		{
+			$categoryDB = new IModel('category_extend');
+			$categoryDB->del('goods_id in ('.$goods_id.')');
+			$categoryArray = IFilter::act($paramData['category'], 'int');
+			foreach ($idArray as $gid)
+			{
+				foreach ($categoryArray as $category_id)
+				{
+					$categoryDB->setData(array('goods_id' => $gid, 'category_id' => $category_id));
+					$categoryDB->add();
+				}
+			}
+		}
+		return true;
+	}
+
+	/**
+	 * @brief 获取运算符号
+	 * @param string $type 	运算类型 1-增加 2-减少
+	 * @return string 		运算符号
+	 */
+	protected function getOperator($type)
+	{
+		return '2'==$type ? '-' : '+';
+	}
+
+	//货品products表spec_array排序
+	public function specArraySort($specArray)
+	{
+		foreach($specArray as $key => $value)
+		{
+			$value        = JSON::decode($value);
+			$temp         = array(
+				'id'    => $value['id'],
+				'type'  => $value['type'],
+				'value' => $value['value'],
+				'name'  => $value['name'],
+				'tip'   => $value['tip'],
+			);
+			$specArray[$key] = JSON::encode($temp);
+		}
+		return $specArray;
+	}
+}

+ 126 - 0
src/classes/hsms.php

@@ -0,0 +1,126 @@
+<?php
+/**
+ * @copyright (c) 2015 aircheng.com
+ * @file hsms.php
+ * @brief 短信发送接口
+ * @author nswe
+ * @date 2015/5/30 16:23:21
+ * @version 3.3
+ */
+
+ /**
+ * @class Hsms
+ * @brief 短信发送接口
+ */
+class Hsms
+{
+	private static $smsInstance = null;
+
+	//每次用户主动(非系统)发送的短信间隔
+	private static $sendStep = 50;
+
+	/**
+	 * @brief 获取config用户配置
+	 * @return array
+	 */
+	private static function getPlatForm()
+	{
+		$siteConfigObj = new Config("site_config");
+		return $siteConfigObj->sms_platform;
+	}
+
+	/**
+	 * @brief 发送短信
+	 * @param string $mobiles 多个手机号为用半角,分开,如13899999999,13688888888(最多200个)
+	 * @param string $content 短信内容
+	 * @param int $delay 延迟设置
+	 * @return success or fail
+	 */
+	public static function send($mobiles, $content, $delay = 1)
+	{
+		if(!$content)
+		{
+			return "短信内容不能为空";
+		}
+
+		if( $delay == 1 && !isset($_SERVER['HTTP_USER_AGENT']) )
+		{
+			return "非客户端访问";
+		}
+
+		if(IClient::getIp() == '')
+		{
+			return "ip信息不合法";
+		}
+
+		$mobile_array = explode(",", $mobiles);
+		foreach ($mobile_array as $key => $val)
+		{
+			if(false === IValidate::mobi($val))
+			{
+				unset($mobile_array[$key]);
+			}
+		}
+
+		if(!$mobile_array)
+		{
+			return "非法手机号码";
+		}
+
+		if(count($mobile_array) > 200)
+		{
+			return "手机号超过200个";
+		}
+
+		//延迟机制
+		if($delay == 1)
+		{
+			$cacheObj = new ICache();
+			$smsTime = $cacheObj->get('smsDelay');
+			if($smsTime && time() - $smsTime < self::$sendStep)
+			{
+				return "短信发送频率太快,请稍候再试...";
+			}
+			//更新发送时间
+			$cacheObj->set('smsDelay',time());
+		}
+
+		if(self::$smsInstance == null)
+		{
+			$platform = self::getPlatForm();
+			switch($platform)
+			{
+				case "zhutong":
+				{
+					$classFile = IWeb::$app->getBasePath().'plugins/hsms/zhutong.php';
+					require($classFile);
+					self::$smsInstance = new zhutong();
+				}
+				break;
+
+				default:
+				{
+					$classFile = IWeb::$app->getBasePath().'plugins/hsms/haiyan.php';
+					require($classFile);
+					self::$smsInstance = new haiyan();
+				}
+			}
+		}
+		return self::$smsInstance->send($mobiles, $content);
+	}
+}
+
+/**
+ * @brief 短信抽象类
+ */
+abstract class hsmsBase
+{
+	//短信发送接口
+	abstract public function send($mobile,$content);
+
+	//短信发送结果接口
+	abstract public function response($result);
+
+	//短信配置参数
+	abstract public function getParam();
+}

+ 74 - 0
src/classes/keywords.php

@@ -0,0 +1,74 @@
+<?php
+/**
+ * @copyright (c) 2011 aircheng.com
+ * @file keywords.php
+ * @brief 词库管理类
+ * @author chendeshan
+ * @date 2013/5/9 13:17:33
+ * @version 0.6
+ */
+class keywords
+{
+	/**
+	 * 向词库中添加词
+	 * @param $word  string 多个词以','分隔
+	 * @param $hot   int    0:否;1:是
+	 * @param $order int    排序
+	 */
+	public static function add($word, $hot = 0, $order = 99)
+	{
+		$hot   = IFilter::act($hot,'int');
+		$order = IFilter::act($order,'int');
+
+		if($word)
+		{
+			$keywordObj  = new IModel('keyword');
+			$wordArray   = explode(',',$word);
+			$wordArray   = IFilter::act($wordArray);
+			$wordArray   = array_unique($wordArray);
+
+			foreach($wordArray as $word)
+			{
+				if(IString::getStrLen($word) >= 15)
+				{
+					continue;
+				}
+				$is_exists = $keywordObj->getObj('word = "'.$word.'"');
+				if(empty($is_exists))
+				{
+					$dataArray = array(
+						'hot'        => $hot,
+						'word'       => $word,
+						'order'      => $order,
+					);
+					$keywordObj->setData($dataArray);
+					$keywordObj->add();
+				}
+				else
+				{
+					$dataArray = array(
+						'hot'        => $hot,
+						'order'      => $order,
+					);
+					$keywordObj->setData($dataArray);
+					$keywordObj->update("word = '".$word."'");
+				}
+			}
+			return array('flag'=>true);
+		}
+		return array('flag'=>false,'data'=>'请填写关键词');
+	}
+
+	/**
+	 * @brief 计算关键词所关联的商品数量
+	 * @param string $word   词语
+	 * return int    $result 商品数量
+	*/
+	public static function count($word)
+	{
+		$word     = IFilter::act($word);
+		$goodsObj = new IModel('goods');
+		$countNum = $goodsObj->getObj('name like "%'.$word.'%" or FIND_IN_SET("'.$word.'", search_words) AND is_del=0 ','count(*) as num');
+		return isset($countNum['num']) ? $countNum['num'] : 0;
+	}
+}

+ 37 - 0
src/classes/layoutroute.php

@@ -0,0 +1,37 @@
+<?php
+/**
+ * @copyright (c) 2014 aircheng
+ * @file themeroute.php
+ * @brief 视图布局选择路由类
+ * @author nswe
+ * @date 2014/7/15 18:50:48
+ * @version 2.6
+ */
+class layoutroute extends IInterceptorBase
+{
+	/**
+	 * @brief layout布局文件进行选择,从主题中的config.php中获取layout配置
+	 */
+	public static function onCreateView($controller,$actionObj)
+	{
+		if($controller->layout === false)
+		{
+			return;
+		}
+		//从主题中的config.php获取layout配置
+		$themeConfig = is_file($controller->getViewPath().'config.php') ? include($controller->getViewPath().'config.php') : null;
+
+		$keyArray = array();
+		$keyArray[] = $controller->getId()."@".$actionObj->getId();
+		$keyArray[] = $controller->getId();
+
+		foreach($keyArray as $key => $val)
+		{
+			if(isset($themeConfig['layout'][$val]))
+			{
+				$controller->layout = $themeConfig['layout'][$val];
+				return;
+			}
+		}
+	}
+}

+ 46 - 0
src/classes/log.php

@@ -0,0 +1,46 @@
+<?php
+/**
+ * @class log
+ * @brief 日志记录类
+ */
+class Log
+{
+	private $logInfo = array(
+		'operation' => array('table' => 'log_operation','cols' => array('author','action','content')),
+	);
+
+	//获取日志对象
+	public function __construct($logType = 'db')
+	{
+
+	}
+
+	/**
+	 * @brief 写入日志
+	 * @param string $type 日志类型
+	 * @param array  $logs 日志内容数据
+	 */
+	public function write($type,$logs = array())
+	{
+		$logInfo = $this->logInfo;
+		if(!isset($logInfo[$type]))
+		{
+			return false;
+		}
+
+		//组合日志数据
+		$tableName = $logInfo[$type]['table'];
+		$content = array(
+			'datetime' => ITime::getDateTime(),
+		);
+
+		foreach($logInfo[$type]['cols'] as $key => $val)
+		{
+			$content[$val] = isset($logs[$val]) ? $logs[$val] : isset($logs[$key]) ? $logs[$key] : '';
+		}
+
+		$logObj = new IModel($tableName);
+		$logObj->setData($content);
+		return $logObj->add();
+	}
+}

+ 46 - 0
src/classes/mailtemplate.php

@@ -0,0 +1,46 @@
+<?php
+/**
+ * @copyright (c) 2014 aircheng.com
+ * @file sendmail.php
+ * @brief 邮件数据模板
+ * @author chendeshan
+ * @date 2014/11/28 23:20:51
+ * @version 2.9
+ */
+class mailTemplate
+{
+	/**
+	 * @brief 找回密码模板
+	 * @param array $param 模版参数
+	 * @return string
+	 */
+	public static function findPassword($param)
+	{
+		$siteConfig = new Config("site_config");
+		$templateString = "您好,您在{$siteConfig->name}申请找回密码的操作,点击下面这个链接进行密码重置:<a href='{url}'>{url}</a>。<br />如果不能点击,请您把它复制到地址栏中打开。";
+		return strtr($templateString,$param);
+	}
+
+	/**
+	 * @brief 验证邮件模板
+	 * @param array $param 模版参数
+	 * @return string
+	 */
+	public static function checkMail($param)
+	{
+		$siteConfig = new Config("site_config");
+		$templateString = "感谢您注册{$siteConfig->name}服务,点击下面这个链接进行邮箱验证并激活您的帐号:<a href='{url}'>{url}</a>。<br />如果不能点击,请您把它复制到地址栏中打开。";
+		return strtr($templateString,$param);
+	}
+
+	/**
+	 * @brief 到货通知邮件模板
+	 * @param array $param 模版参数
+	 * @return string
+	 */
+	public static function notify($param)
+	{
+		$templateString = "尊敬的用户,您需要购买的 <{goodsName}> 现已全面到货,机不可失,从速购买! <a href='{url}' target='_blank'>立即购买</a>";
+		return strtr($templateString,$param);
+	}
+}

+ 321 - 0
src/classes/menu.php

@@ -0,0 +1,321 @@
+<?php
+/**
+ * @copyright Copyright(c) 2016 aircheng.com
+ * @file menu.php
+ * @brief 后台系统菜单管理
+ * @author nswe
+ * @date 2016/3/4 23:59:33
+ * @version 4.4
+ */
+class Menu
+{
+    //菜单的配制数据
+	public static $menu = array(
+		'商品'=>array(
+			'商品管理'=>array(
+				'/goods/goods_list' => '商品列表',
+				'/goods/goods_edit' => '商品添加'
+			),
+			'商品分类'=>array(
+				'/goods/category_list'	=>	'分类列表',
+				'/goods/category_edit'	=>	'添加分类'
+			),
+			'品牌'=>array(
+				'/brand/category_list'  =>	'品牌分类',
+				'/brand/brand_list'		=>	'品牌列表'
+			),
+			'模型'=>array(
+				'/goods/model_list'=>'模型列表',
+				'/goods/spec_list'=>'规格列表',
+				'/goods/spec_photo'=>'规格图库'
+			),
+			'搜索'=>array(
+				'/tools/keyword_list' => '关键词列表',
+				'/tools/search_list' => '搜索统计'
+			)
+		),
+
+		'会员'=>array(
+			'会员管理'=>array(
+	    		'/member/member_list' 	=> '会员列表',
+	     		'/member/group_list' 	=> '会员组列表',
+	     		'/member/withdraw_list' =>'会员提现管理',
+				'/comment/message_list'	=> '会员消息',
+			),
+			'商户管理' => array(
+				'/member/seller_list' => '商户列表',
+				'/member/seller_edit' => '添加商户',
+				'/comment/seller_message_list' => '商户消息'
+			),
+			'信息处理' => array(
+				'/comment/suggestion_list'  => '建议管理',
+				'/comment/refer_list'		=> '咨询管理',
+				'/comment/discussion_list'	=> '讨论管理',
+				'/comment/comment_list'		=> '评价管理',
+				'/message/notify_list'      => '到货通知',
+				'/message/registry_list'    => '邮件订阅',
+				'/message/marketing_sms_list'=> '营销短信',
+			),
+		),
+
+	   '订单'=>array(
+        	'订单管理'=>array(
+                '/order/order_list' => '订单列表',
+                '/order/order_edit' => '添加订单'
+        	),
+        	'单据管理'=>array(
+             	'/order/order_collection_list'  => '收款单',
+             	'/order/order_refundment_list'  => '退款单',
+        		'/order/order_delivery_list'    => '发货单',
+        		'/order/refundment_list'        => '退款申请列表',
+        	),
+        	'发货地址'=>array(
+        		'/order/ship_info_list'         => '发货地址管理',
+        	),
+		),
+
+		'营销'=>array(
+        	'促销活动' => array(
+        		'/market/pro_rule_list' => '促销活动列表'
+        	),
+        	'营销活动' => array(
+        		'/market/pro_speed_list' => '限时抢购',
+        		'/market/regiment_list' => '团购',
+        		'/market/sale_list' => '特价',
+        	),
+        	'代金券管理'=>array(
+        		'/market/ticket_list'       => '代金券列表',
+        	)
+		),
+
+		'统计'=>array(
+			'基础数据统计'=>array(
+      			'/market/user_reg' 	   => '用户注册统计',
+				'/market/spanding_avg' => '人均消费统计',
+      			'/market/amount'       => '销售金额统计'
+			),
+			'日志操作记录'=>array(
+				'/market/account_list'   => '充值操作记录',
+				'/market/operation_list' => '后台操作记录',
+			),
+			'商户数据统计'=>array(
+				'/market/order_goods_list' => '货款明细列表',
+				'/market/bill_list' => '货款结算申请',
+			)
+		),
+
+
+        '系统'=>array(
+    		'后台首页'=>array(
+    			'/system/default' => '后台首页',
+    		),
+        	'网站管理'=>array(
+        		'/system/conf_base' => '网站设置',
+        		'/system/conf_ui/type/site'   => '网站前台主题',
+        		'/system/conf_ui/type/system'   => '后台管理主题',
+        		'/system/conf_ui/type/seller'   => '商家管理主题',
+        	),
+        	'支付管理'=>array(
+            	'/system/payment_list' => '支付方式'
+        	),
+        	'第三方平台'=>array(
+            	'/system/oauth_list' => 'oauth登录列表',
+            	'/system/hsms' => '手机短信平台',
+        	),
+        	'配送管理'=>array(
+            	'/system/delivery'  	=> '配送方式',
+        		'/system/freight_list'	=> '物流公司',
+	    		'/system/takeself_list' => '自提点列表',
+	    		'/system/takeself_edit'  => '添加自提点',
+        	),
+        	'地域管理'=>array(
+        		'/system/area_list' => '地区列表',
+        	),
+        	'权限管理'=>array(
+        		'/system/admin_list' => '管理员',
+        		'/system/role_list'  => '角色',
+        		'/system/right_list' => '权限资源'
+        	),
+		),
+
+       '工具'=>array(
+			'数据库管理'=>array(
+				'/tools/db_bak' => '数据库备份',
+				'/tools/db_res' => '数据库还原',
+			),
+			'文章管理'=>array(
+				'/tools/article_cat_list'=> '文章分类',
+				'/tools/article_list'=> '文章列表'
+			),
+
+			'帮助管理'=>array(
+   				'/tools/help_cat_list'=> '帮助分类',
+   				'/tools/help_list'=> '帮助列表'
+   			),
+
+   			'广告管理'=>array(
+   				'/tools/ad_position_list'=> '广告位列表',
+   				'/tools/ad_list'=> '广告列表'
+   			),
+
+   			'公告管理'=>array(
+   				'/tools/notice_list'=> '公告列表',
+   				'/tools/notice_edit'=> '公告发布'
+   			),
+     		'网站地图'=>array(
+            	'/tools/seo_sitemaps' => '网站搜索地图',
+			)
+		),
+		'插件' => array(
+       		'插件管理' => array(
+       			'/plugins/plugin_list' => '插件列表',
+       		),
+		),
+	);
+
+	//非菜单连接映射关系,array(视图名称 => menu数组中已存在的菜单连接)
+	public static $innerPathUrl = array(
+		"/system/navigation" => "/system/default",
+		"/system/navigation_edit" => "/system/default",
+	);
+
+    /**
+     * @brief 根据权限初始化菜单
+     * @param int $roleId 角色ID
+     * @return array 菜单数组
+     */
+    public static function init($roleId)
+    {
+		//菜单创建事件触发
+		plugin::trigger("onSystemMenuCreate");
+
+		//根据角色分配权限
+		if($roleId == 0)
+		{
+			$adminRights = 'administrator';
+		}
+		else
+		{
+			$roleObj = new IModel('admin_role');
+			$where   = 'id = '.$roleId.' and is_del = 0';
+			$roleRow = $roleObj->getObj($where);
+			$adminRights = isset($roleRow['rights']) ? $roleRow['rights'] : '';
+		}
+
+		//1,超管返回全部菜单
+		if($adminRights == "administrator")
+		{
+			return self::$menu;
+		}
+
+		//2,根据权限码显示菜单
+		$result      = array();
+		$defaultShow = array('/system/default');
+		foreach(self::$menu as $key1 => $val1)
+		{
+			foreach($val1 as $key2 => $val2)
+			{
+				foreach($val2 as $key3 => $val3)
+				{
+					//把菜单数据里面的路径转化成@符号做权限码比对
+					$tempKey3 = str_replace("/","@",trim($key3,"/"));
+					if(in_array($key3,$defaultShow) || strpos($adminRights,$tempKey3) !== false)
+					{
+						$result[$key1][$key2][$key3] = $val3;
+					}
+				}
+			}
+		}
+		return $result;
+    }
+
+    /**
+     * @brief 根据当前URL动态生成菜单分组
+     * @param array  $menu 菜单数据
+     * @param string $info 连接信息
+     * @return array 菜单数组
+     */
+    public static function get($menu,$info)
+    {
+    	$result = self::menuInfo($menu,$info);
+    	if($result)
+    	{
+    		return $result;
+    	}
+
+		//历史URL信息
+		$lastInfo = IUrl::getRefRoute();
+		if($lastInfo && strpos($lastInfo,$info) === false && $result = self::menuInfo($menu,$lastInfo))
+		{
+			ICookie::set('lastInfo',$lastInfo);
+			return $result;
+		}
+
+		//从COOKIE读取URL信息
+		$lastInfo = ICookie::get('lastInfo');
+		if($lastInfo)
+		{
+			return self::menuInfo($menu,$lastInfo);
+		}
+		return array('插件' => self::$menu['插件']);
+    }
+
+	/**
+	 * @brief 判断url路径获取定义的菜单项
+	 * @param array  $menu 当前管理员权限合法的菜单
+	 * @param string $info 访问的URL
+	 * @return array(地址=>名称) or null
+	 */
+    public static function menuInfo($menu,$info)
+    {
+    	//已有菜单查找
+		foreach($menu as $key1 => $val1)
+		{
+			foreach($val1 as $key2 => $val2)
+			{
+				foreach($val2 as $key3 => $val3)
+				{
+					if(strpos($key3,$info) !== false || strpos($info,$key3) !== false)
+					{
+						return array($key1 => $menu[$key1]);
+					}
+				}
+			}
+		}
+
+		//配置菜单映射
+		if(self::$innerPathUrl)
+		{
+			foreach(self::$innerPathUrl as $key => $val)
+			{
+				if(strpos($key,$info) !== false)
+				{
+					return self::menuInfo($menu,$val);
+				}
+			}
+		}
+		return null;
+    }
+
+    /**
+     * @brief 获取顶级分类关系数据
+     * @param array $menu 菜单数据
+     * @return array 顶级菜单数组
+     */
+    public static function getTopMenu($menu)
+    {
+    	$result = array();
+		foreach($menu as $key1 => $val1)
+		{
+			foreach($val1 as $key2 => $val2)
+			{
+				foreach($val2 as $key3 => $val3)
+				{
+					$result[$key1] = $key3;
+					break 2;
+				}
+			}
+		}
+		return $result;
+    }
+}

+ 60 - 0
src/classes/menuSeller.php

@@ -0,0 +1,60 @@
+<?php
+/**
+ * @copyright Copyright(c) 2016 aircheng.com
+ * @file menuSeller.php
+ * @brief 商家系统菜单管理
+ * @author nswe
+ * @date 2016/3/8 9:30:34
+ * @version 4.4
+ */
+class menuSeller
+{
+    //菜单的配制数据
+	public static $menu = array
+	(
+		"统计结算模块" => array(
+			"/seller/index" => "管理首页",
+			"/seller/account" => "销售额统计",
+			"/seller/order_goods_list" => "货款明细列表",
+			"/seller/bill_list" => "货款结算申请",
+		),
+
+		"商品模块" => array(
+			"/seller/goods_list" => "商品列表",
+			"/seller/goods_edit" => "添加商品",
+			"/seller/share_list" => "平台共享商品",
+			"/seller/refer_list" => "商品咨询",
+			"/seller/comment_list" => "商品评价",
+			"/seller/refundment_list" => "商品退款",
+			"/seller/spec_list" => "规格列表",
+		),
+
+		"订单模块" => array(
+			"/seller/order_list" => "订单列表",
+		),
+
+		"营销模块" => array(
+			"/seller/regiment_list" => "团购",
+			"/seller/pro_rule_list" => "促销活动列表",
+		),
+
+		"配置模块" => array(
+			"/seller/delivery" => "物流配送",
+			"/seller/message_list" => "消息通知",
+			"/seller/ship_info_list" => "发货地址",
+			"/seller/seller_edit" => "资料修改",
+		),
+	);
+
+    /**
+     * @brief 根据权限初始化菜单
+     * @param int $roleId 角色ID
+     * @return array 菜单数组
+     */
+    public static function init($roleId = "")
+    {
+		//菜单创建事件触发
+		plugin::trigger("onSellerMenuCreate");
+		return self::$menu;
+    }
+}

+ 73 - 0
src/classes/menuUcenter.php

@@ -0,0 +1,73 @@
+<?php
+/**
+ * @copyright Copyright(c) 2016 aircheng.com
+ * @file menuUcenter.php
+ * @brief 用户中心菜单管理
+ * @author nswe
+ * @date 2016/3/8 9:33:25
+ * @version 4.4
+ */
+class menuUcenter
+{
+	//菜单与图标对应关系
+	public static $ico = array(
+		"我的订单"   => "icon-th-list",
+		"我的积分"   => "icon-trophy",
+		"我的代金券" => "icon-tags",
+		"退款申请"   => "icon-signout",
+		"站点建议"   => "icon-file-alt",
+		"商品咨询"   => "icon-comment-alt",
+		"商品评价"   => "icon-comments-alt",
+		"短信息"     => "icon-bell-alt",
+		"收藏夹"     => "icon-heart",
+		"帐户余额"   => "icon-money",
+		"在线充值"   => "icon-signin",
+		"地址管理"   => "icon-map-marker",
+		"个人资料"   => "icon-table",
+		"修改密码"   => "icon-key",
+	);
+
+    //菜单的配制数据
+	public static $menu = array(
+		"交易记录" => array(
+			"/ucenter/order" => "我的订单",
+			"/ucenter/integral" => "我的积分",
+			"/ucenter/redpacket" => "我的代金券",
+		),
+
+		"服务中心" => array(
+			"/ucenter/refunds" => "退款申请",
+			"/ucenter/complain" => "站点建议",
+			"/ucenter/consult" => "商品咨询",
+			"/ucenter/evaluation" => "商品评价",
+		),
+
+		"应用" => array(
+			"/ucenter/message" => "短信息",
+			"/ucenter/favorite" => "收藏夹",
+		),
+
+		"账户资金" => array(
+			"/ucenter/account_log" => "帐户余额",
+			"/ucenter/online_recharge" => "在线充值",
+		),
+
+		"个人设置" => array(
+			"/ucenter/address" => "地址管理",
+			"/ucenter/info" => "个人资料",
+			"/ucenter/password" => "修改密码",
+		),
+	);
+
+    /**
+     * @brief 根据权限初始化菜单
+     * @param int $roleId 角色ID
+     * @return array 菜单数组
+     */
+    public static function init($roleId = "")
+    {
+		//菜单创建事件触发
+		plugin::trigger("onUcenterMenuCreate");
+		return self::$menu;
+    }
+}

+ 177 - 0
src/classes/mess.php

@@ -0,0 +1,177 @@
+<?php
+/**
+ * @copyright (c) 2011 aircheng.com
+ * @file mess.php
+ * @brief 会员消息的管理
+ * @author chendeshan
+ * @date 2013/11/13 11:44:08
+ * @version 0.6
+ */
+ /**
+  * example:
+  * $message = new Mess($data['user_id']);
+  * $message->writeMessage('0',1);
+ */
+class Mess
+{
+	//用户信息数据库实例
+	private $memberDB = null;
+
+	//用户id
+	private $user_id = '';
+
+	//用户消息ID
+	private $messageIds = '';
+
+	/**
+	 * @brief 构造函数 用户id
+	 * @param string $user_id 用户id
+	 */
+	function __construct($user_id)
+	{
+		$this->user_id  = $user_id;
+		$this->memberDB = new IModel('member');
+		$memberRow      = $this->memberDB->getObj('user_id = '.$user_id);
+
+		//过滤消息内容
+		if($memberRow['message_ids'])
+		{
+			$messObj   = new IModel('message');
+			$messArray = explode(',',$memberRow['message_ids']);
+			foreach($messArray as $key => $messId)
+			{
+				$mid = abs($messId);
+				if(!$messObj->getObj('id = '.$mid))
+				{
+					$memberRow['message_ids'] = str_replace(",".$messId.",",",",",".trim($memberRow['message_ids'],",").",");
+				}
+			}
+			$this->memberDB->setData(array('message_ids' => $memberRow['message_ids']));
+			$this->memberDB->update("user_id = ".$user_id);
+		}
+		$this->messageIds = $memberRow['message_ids'];
+	}
+
+	/**
+	 * @brief 存储消息串
+	 * @return boolean
+	 */
+	private function save()
+	{
+		$this->memberDB->setData(array('message_ids' => $this->messageIds));
+		return $this->memberDB->update('user_id='.$this->user_id);
+	}
+
+	/**
+	 * @brief 将messageid写入member表中
+	 * @param $message_id int 消息的id
+	 * @param $read int 0:未读(追加到用户id串后面),1:已读(把用户id串增加‘-’负号)
+	 * @return int or boolean
+	 */
+	public function writeMessage($message_id,$read = 0)
+	{
+		if($read == 1)
+		{
+			$tempIds = ','.trim($this->messageIds,',').',';
+			if(strpos($tempIds,','.$message_id.',') === false)
+			{
+				return false;
+			}
+			$tempIds = str_replace(','.$message_id.',',',-'.$message_id.',',$tempIds);
+			$this->messageIds = trim($tempIds,',').',';
+		}
+		else
+		{
+			$this->messageIds .= $message_id.',';
+		}
+
+		return $this->save();
+	}
+	/**
+	 * @brief 获得member表中的messageid,去掉 '-' 且没有最后的 ',' 的message的id
+	 * @return $message String 返回站内所有消息id的字符串
+	 */
+	public function getAllMsgIds()
+	{
+		return str_replace('-','',trim($this->messageIds,','));
+	}
+	/**
+	 * @brief 判断messageid是否已经读过
+	 * @param $mess_id int message的id
+	 * @return $is_blog boolean 返回true为已读,false为未读
+	 */
+	public function is_read($messageId)
+	{
+		if(strpos(','.trim($this->messageIds,',').',',',-'.$messageId.',') === false)
+		{
+			return false;
+		}
+		return true;
+	}
+
+	/**
+	 * @brief 删除member表中的message_ids的数据
+	 * @param $message_id string 要删除的消息ID值
+	 * @return string message_ids结果字符串
+	 */
+	public function delMessage($message_id)
+	{
+		$tempIds = str_replace(','.$message_id.',','',','.trim($this->messageIds,',').',');
+		$tempIds = str_replace(',-'.$message_id.',','',','.trim($tempIds,',').',');
+		$tempIds = trim($tempIds,',').',';
+		$this->messageIds = $tempIds;
+		$this->save();
+	}
+
+	/**
+	 * 直接发站内信到用户
+	 * 这个地方直接调用了Mysql的操作类
+	 * @param $userIds string 用户Id的串
+	 * @param $content 信件内容 array('title' => '标题','content' => '内容')
+	 */
+	public static function sendToUser($userIds,$content)
+	{
+		set_time_limit(0);
+
+		//插入$content
+		$data = array(
+			'title'   => $content['title'],
+			'content' => $content['content'],
+			'time'    => ITime::getDateTime(),
+		);
+
+		$msgDB = new IModel("message");
+		$msgDB->setData($data);
+		$id = $msgDB->add();
+
+		if($id === false)
+		{
+			return false;
+		}
+		else
+		{
+			$db = IDBFactory::getDB();
+			$tableName = IWeb::$app->config['DB']['tablePre']."member";
+			if($userIds)
+			{
+				$sql = "UPDATE `{$tableName}` SET message_ids = CONCAT( IFNULL(message_ids,'') ,'{$id},') WHERE user_id in ({$userIds})";
+			}
+			else
+			{
+				$sql = "UPDATE `{$tableName}` SET message_ids = CONCAT( IFNULL(message_ids,'') ,'{$id},')";
+			}
+			return $db->query($sql);
+		}
+	}
+
+	/**
+	 * @brief 获取未读的短消息
+	 * @return int 消息数量
+	 */
+	public function needReadNum()
+	{
+		$tempIds = ','.trim($this->messageIds,',').',';
+		preg_match_all('|,\d+|',$tempIds,$result);
+		return count(current($result));
+	}
+}

+ 163 - 0
src/classes/model.php

@@ -0,0 +1,163 @@
+<?php
+/**
+ * @copyright Copyright(c) 2011 aircheng.com
+ * @file model.php
+ * @brief 模型表业务处理
+ * @author nswe
+ * @date 2011-01-12
+ * @version 4.8
+ * @note
+ * @update 2017/6/7 10:22:32 去掉模型和spec规格关联性
+ */
+class Model
+{
+	/**
+	 * @brief 商品模型添加/修改
+	 * @param string $model_id 		模型编号
+	 * @param string $model_name 	模型名字
+	 * @param array $attribute 		表字段 数组格式,如Array ([name] 	=> Array ( [0] => '' )
+	 *														[show_type] => Array ( [0] => '' )
+	 *														[value] 	=> Array ( [0] => '' )
+	 *														[is_seach] 	=> Array ( [0] => 1 ))
+	 * @return bool bool:true成功;false失败
+	 */
+    public function model_update($model_id,$model_name,$attribute)
+    {
+    	if(!$model_name)
+    	{
+    		return false;
+    	}
+
+    	//初始化model商品模型表类对象
+		$modelObj = new IModel('model');
+
+		//设置更新字段数据
+		$dataArray = array(
+			'name' => $model_name
+		);
+		$modelObj->setData($dataArray);
+
+		if($model_id)
+		{
+			//更新商品模型数据
+			$modelObj->update("id = {$model_id}");
+		}
+		else
+		{
+			//添加新商品模型
+			$model_id = $modelObj->add();
+		}
+
+		if($model_id)
+		{
+			if($attribute)
+			{
+				$this->attribute_update($attribute,$model_id);
+			}
+			return true;
+		}
+		return false;
+    }
+
+	/**
+	 * @brief 商品属性添加/修改
+	 * @param array $attribute 表字段 数组格式,如Array ([name] 		=> Array ( [0] => '' )
+	 *													[show_type] => Array ( [0] => '' )
+	 *													[value] 	=> Array ( [0] => '' )
+	 *													[is_seach] 	=> Array ( [0] => 1 ))
+	 * @param int $model_id 模型编号
+	 */
+    public function attribute_update($attribute,$model_id)
+    {
+    	//初始化attribute商品模型属性表类对象
+		$attributeObj = new IModel('attribute');
+		$len = count($attribute['name']);
+		$ids = "";
+	    for($i = 0;$i< $len;$i++)
+		{
+			if(isset($attribute['name'][$i]) && isset($attribute['value'][$i]))
+			{
+				$options = str_replace(',',',',$attribute['value'][$i]);
+				$type = isset($attribute['is_search'][$i]) ? $attribute['is_search'][$i] : 0;
+
+				//设置商品模型扩展属性 字段赋值
+				$filedData = array(
+					"model_id" 	=> $model_id,
+					"type" 		=> IFilter::act($attribute['show_type'][$i]),
+					"name" 		=> $attribute['name'][$i],
+					"value" 	=> rtrim($options,','),
+					"search" 	=> IFilter::act($type)
+				);
+
+				$attributeObj->setData($filedData);
+				$id = intval($attribute['id'][$i]);
+				if($id)
+				{
+					//更新商品模型扩展属性
+					$attributeObj->update("id = ".$id);
+				}
+				else
+				{
+					//新增商品模型扩展属性
+					$id = $attributeObj->add();
+				}
+				$ids .= $id.',';
+			}
+		}
+
+		if($ids)
+		{
+			$ids = trim($ids,',');
+
+			//删除商品模型扩展属性
+			$where = "model_id = $model_id  and id not in (".$ids.") ";
+			$attributeObj->del($where);
+		}
+    }
+
+	/**
+	 * @brief 将$attribute、$spec的POST数组转换成正常数组
+	 * @param array $attribute 表字段 数组格式,如Array ([name] 		=> Array ( [0] => '' )
+	 *													[show_type] => Array ( [0] => '' )
+	 *													[value] 	=> Array ( [0] => '' )
+	 *													[is_seach] 	=> Array ( [0] => 1 ))
+	 * @return array
+	 */
+    public function postArrayChange($attribute)
+    {
+    	$len = count($attribute['name']);
+    	$model_attr = array();
+		for( $i = 0;$i< $len;$i++)
+		{
+			$model_attr[$i]['id'] = $attribute['id'][$i];
+			$model_attr[$i]['name'] = $attribute['name'][$i];
+			$model_attr[$i]['type'] = $attribute['show_type'][$i];
+			$model_attr[$i]['value'] = $attribute['value'][$i];
+			$model_attr[$i]['search'] = $attribute['is_search'][$i];
+		}
+		return array('model_attr'=>$model_attr);
+    }
+
+	/**
+	 * @brief 根据模型编号  获取模型详细信息
+	 * @param int $model_id 模型编号
+	 * @return array 数组格式 	Array ( [id] => '',[name] => '', [model_attr] => Array ( ))
+	 */
+    public function get_model_info($model_id)
+    {
+    	$model_id = intval($model_id);
+    	//初始化model商品模型表类对象
+		$modelObj = new IModel('model');
+		//根据模型编号  获取商品模型详细信息
+		$model_info = $modelObj->getObj('id = '.$model_id);
+		if($model_info)
+		{
+			//初始化attribute商品模型属性表类对象
+			$attributeObj = new IModel('attribute');
+			//根据商品模型编号 获取商品模型扩展属性
+			$model_attr = $attributeObj->query("model_id = ".$model_id);
+			$model_info['model_attr'] = $model_attr;
+		}
+		return $model_info;
+    }
+}

+ 29 - 0
src/classes/oauthbase.php

@@ -0,0 +1,29 @@
+<?php
+/**
+ * @copyright (c) 2011 aircheng.com
+ * @file OauthBase.php
+ * @brief oauth协议登录基础类
+ * @author chendeshan
+ * @date 2011-7-18 9:34:18
+ * @version 0.6
+ */
+
+/**
+ * @class Oauth
+ * @brief oauth协议登录基础类
+ */
+abstract class OauthBase
+{
+	//获取回调URL地址
+	protected function getReturnUrl()
+	{
+		$className = strtolower( get_class($this) );
+		return IUrl::getHost().IUrl::creatUrl('/simple/oauth_callback/oauth_name/'.$className);
+	}
+
+	abstract public function getLoginUrl();
+	abstract public function checkStatus($parms);
+	abstract public function getAccessToken($parms);
+	abstract public function getUserInfo();
+	abstract public function getFields();
+}

+ 92 - 0
src/classes/oauthcore.php

@@ -0,0 +1,92 @@
+<?php
+/**
+ * @copyright (c) 2011 aircheng.com
+ * @file OauthCore.php
+ * @brief oauth协议登录接口
+ * @author chendeshan
+ * @date 2017/1/18 18:29:40
+ * @version 4.7
+ */
+
+/**
+ * @class OauthCore
+ * @brief oauth协议接口
+ */
+class OauthCore
+{
+	private $oauthObj = null;
+
+	//构造函数
+	public function __construct($id)
+	{
+		$oauthRow = $this->getOauthRow($id);
+		if(!$oauthRow)
+		{
+			throw new IException("【ID:{$id}】的第三方登录方式不存在");
+		}
+
+		if($this->requireFile($oauthRow['file']))
+		{
+			$config   = unserialize($oauthRow['config']);
+			$fileName = ucfirst($oauthRow['file']);
+			$this->oauthObj = new $fileName($config);
+		}
+		else
+		{
+			return false;
+		}
+	}
+
+	//获取字段数据
+	public function getFields()
+	{
+		return $this->oauthObj->getFields();
+	}
+
+	//回调函数
+	public function checkStatus($parms)
+	{
+		return $this->oauthObj->checkStatus($parms);
+	}
+
+	//获取平台的用户信息
+	public function getUserInfo()
+	{
+		return $this->oauthObj->getUserInfo();
+	}
+
+	//获取登录url地址
+	public function getLoginUrl()
+	{
+		return $this->oauthObj->getLoginUrl();
+	}
+
+	//获取令牌数据
+	public function getAccessToken($parms)
+	{
+		return $this->oauthObj->getAccessToken($parms);
+	}
+
+	//根据id值获取数据库中的数据
+	private function getOauthRow($id)
+	{
+		$oauthObj = new IModel('oauth');
+		$oauthRow = $oauthObj->getObj('id = '.$id);
+		return $oauthRow;
+	}
+
+	//引入平台接口文件
+	private function requireFile($fileName)
+	{
+		$classFile = IWeb::$app->getBasePath().'plugins/oauth/'.$fileName.'/'.$fileName.'.php';
+		if(file_exists($classFile))
+		{
+			include_once($classFile);
+			return true;
+		}
+		else
+		{
+			return false;
+		}
+	}
+}

+ 1747 - 0
src/classes/order_class.php

@@ -0,0 +1,1747 @@
+<?php
+/**
+ * @copyright (c) 2011 aircheng.com
+ * @file Order_Class.php
+ * @brief 订单中相关的
+ * @author relay
+ * @date 2011-02-24
+ * @version 0.6
+ */
+class Order_Class
+{
+	/**
+	 * @brief 产生订单ID
+	 * @return string 订单ID
+	 */
+	public static function createOrderNum()
+	{
+		$newOrderNo = date('YmdHis').rand(100000,999999);
+
+		$orderDB = new IModel('order');
+		if($orderDB->getObj('order_no = "'.$newOrderNo.'"'))
+		{
+			return self::createOrderNum();
+		}
+		return $newOrderNo;
+	}
+
+	/**
+	 * 添加评论商品的机会
+	 * @param $order_id 订单ID
+	 */
+	public static function addGoodsCommentChange($order_id)
+	{
+		//获取订单对象
+		$orderDB  = new IModel('order');
+		$orderRow = $orderDB->getObj('id = '.$order_id);
+
+		//获取此订单中的商品种类
+		$orderGoodsDB        = new IQuery('order_goods');
+		$orderGoodsDB->where = 'order_id = '.$order_id.' and is_send = 1';
+		$orderList           = $orderGoodsDB->find();
+
+		//可以允许进行商品评论
+		$commentDB = new IModel('comment');
+		$goodsDB   = new IModel('goods');
+
+		//对每类商品进行评论开启
+		foreach($orderList as $val)
+		{
+			//判断此订单商品是否已经加入评论表
+			$issetComment = $commentDB->getObj('order_no = "'.$orderRow['order_no'].'" and goods_id = '.$val['goods_id']);
+			if($issetComment)
+			{
+				continue;
+			}
+
+			$issetGoods = $goodsDB->getObj('id = '.$val['goods_id']);
+			if($issetGoods)
+			{
+				$attr = array(
+					'goods_id'       => $val['goods_id'],
+					'order_no'       => $orderRow['order_no'],
+					'user_id'        => $orderRow['user_id'],
+					'time'           => ITime::getDateTime(),
+					'seller_id'      => $val['seller_id'],
+					'order_goods_id' => $val['id'],
+				);
+				$commentDB->setData($attr);
+				$commentDB->add();
+			}
+		}
+	}
+
+	/**
+	 * 支付成功后修改订单状态
+	 * @param $orderNo  string 订单编号
+	 * @param $admin_id int    管理员ID
+	 * @param $note     string 收款的备注
+	 * @return false or int order_id
+	 */
+	public static function updateOrderStatus($orderNo,$admin_id = '',$note = '')
+	{
+		//获取订单信息
+		$orderObj  = new IModel('order');
+		$orderRow  = $orderObj->getObj('order_no = "'.$orderNo.'"');
+
+		if(empty($orderRow))
+		{
+			return false;
+		}
+
+		if($orderRow['pay_status'] == 1)
+		{
+			return $orderRow['id'];
+		}
+		else if($orderRow['pay_status'] == 0)
+		{
+			$dataArray = array(
+				'status'     => ($orderRow['status'] == 5) ? 5 : 2,
+				'pay_time'   => ITime::getDateTime(),
+				'pay_status' => 1,
+			);
+
+			$orderObj->setData($dataArray);
+			$is_success = $orderObj->update('order_no = "'.$orderNo.'"');
+			if($is_success == '')
+			{
+				return false;
+			}
+
+			//删除订单中使用的道具
+			$ticket_id = trim($orderRow['prop']);
+			if($ticket_id != '')
+			{
+				$propObj  = new IModel('prop');
+				$propData = array('is_userd' => 1);
+				$propObj->setData($propData);
+				$propObj->update('id = '.$ticket_id);
+			}
+
+			//注册用户进行奖励
+			if($orderRow['user_id'])
+			{
+				$user_id = $orderRow['user_id'];
+
+				//获取用户信息
+				$memberObj  = new IModel('member');
+				$memberRow  = $memberObj->getObj('user_id = '.$user_id,'prop,group_id');
+
+				//(1)删除订单中使用的道具
+				if($ticket_id != '')
+				{
+					$finnalTicket = str_replace(','.$ticket_id.',',',',','.trim($memberRow['prop'],',').',');
+					$memberData   = array('prop' => $finnalTicket);
+					$memberObj->setData($memberData);
+					$memberObj->update('user_id = '.$user_id);
+				}
+
+				if($memberRow)
+				{
+					//(2)进行促销活动奖励(普通订单方式)
+					if($orderRow['type'] == 0 && $orderRow['prorule_ids'])
+					{
+				    	$proObj = new ProRule();
+				    	$awardText = $proObj->setAwardByIds($orderRow['prorule_ids'],$user_id);
+				    	if($awardText)
+				    	{
+					    	$orderObj->setData(array('note' => "concat(note,'".$awardText."')"));
+					    	$orderObj->update('order_no = "'.$orderNo.'"','note');
+				    	}
+					}
+
+			    	//(3)增加经验值
+			    	plugin::trigger('expUpdate',$user_id,$orderRow['exp']);
+
+					//(4)增加积分
+					$pointConfig = array(
+						'user_id' => $user_id,
+						'point'   => $orderRow['point'],
+						'log'     => '成功购买了订单号:'.$orderRow['order_no'].'中的商品,奖励积分'.$orderRow['point'],
+					);
+					$pointObj = new Point();
+					$pointObj->update($pointConfig);
+				}
+			}
+
+			//插入收款单
+			$collectionDocObj = new IModel('collection_doc');
+			$collectionData   = array(
+				'order_id'   => $orderRow['id'],
+				'user_id'    => $orderRow['user_id'],
+				'amount'     => $orderRow['order_amount'],
+				'time'       => ITime::getDateTime(),
+				'payment_id' => $orderRow['pay_type'],
+				'pay_status' => 1,
+				'if_del'     => 0,
+				'note'       => $note,
+				'admin_id'   => $admin_id ? $admin_id : 0
+			);
+
+			$collectionDocObj->setData($collectionData);
+			$collectionDocObj->add();
+
+			//促销活动订单
+			if($orderRow['type'] != 0)
+			{
+				Active::payCallback($orderNo,$orderRow['type']);
+			}
+
+			//非货到付款的支付方式
+			if($orderRow['pay_type'] != 0)
+			{
+				//减少库存量
+				$orderGoodsDB = new IModel('order_goods');
+				$orderGoodsList = $orderGoodsDB->query('order_id = '.$orderRow['id']);
+				$orderGoodsListId = array();
+				foreach($orderGoodsList as $key => $val)
+				{
+					$orderGoodsListId[] = $val['id'];
+				}
+				self::updateStore($orderGoodsListId,'reduce');
+			}
+
+			//自提点短信发送
+			self::sendTakeself($orderNo);
+			$mobile = "";
+
+			//订单付款后短信通知商家或者管理员进行订单处理
+			if($orderRow['seller_id'] > 0)
+			{
+				$sellerObj = new IModel('seller');
+				$sellerRow = $sellerObj->getObj("id = ".$orderRow['seller_id']);
+				$mobile    = $sellerRow['mobile'] ? $sellerRow['mobile'] : "";
+			}
+			else
+			{
+				$config = new Config('site_config');
+				$mobile = $config->mobile ? $config->mobile : "";
+			}
+			$smsContent = smsTemplate::payFinishToAdmin(array('{orderNo}' => $orderNo));
+			Hsms::send($mobile,$smsContent,0);
+
+			//线上支付完成发送事件
+			plugin::trigger('orderPayFinish',$orderRow);
+
+			return $orderRow['id'];
+		}
+		else
+		{
+			return false;
+		}
+	}
+
+	/**
+	 * @brief 自提点短信发送
+	 * @param string $orderNo 订单编号
+	 */
+	public static function sendTakeself($orderNo)
+	{
+		//获取订单信息
+		$orderObj  = new IModel('order');
+		$orderRow  = $orderObj->getObj('order_no = "'.$orderNo.'"');
+
+		if(empty($orderRow))
+		{
+			return false;
+		}
+
+		//自提方式短信验证提醒
+		if($orderRow['takeself'] > 0)
+		{
+			$takeselfObj = new IModel('takeself');
+			$takeselfRow = $takeselfObj->getObj('id = '.$orderRow['takeself']);
+			if($takeselfRow)
+			{
+				$mobile_code = rand(100000,999999);
+				$orderObj->setData(array('checkcode' => $mobile_code));
+				$checkResult = $orderObj->update('id = '.$orderRow['id']);
+				if($checkResult)
+				{
+					$smsContent = smsTemplate::takeself(array('{orderNo}' => $orderRow['order_no'],'{address}' => $takeselfRow['address'],'{mobile_code}' => $mobile_code,'{phone}' => $takeselfRow['phone'],'{name}' => $takeselfRow['name']));
+					Hsms::send($orderRow['mobile'],$smsContent,0);
+				}
+			}
+		}
+		//普通付款通知
+		else
+		{
+			$smsContent = smsTemplate::payFinishToUser(array('{orderNo}' => $orderNo));
+			Hsms::send($orderRow['mobile'],$smsContent,0);
+		}
+	}
+
+	/**
+	 * 订单商品数量更新操作[公共]
+	 * @param array $orderGoodsId ID数据
+	 * @param string $type 增加或者减少 add 或者 reduce
+	 */
+	public static function updateStore($orderGoodsId,$type = 'add')
+	{
+		if(!is_array($orderGoodsId))
+		{
+			$orderGoodsId = array($orderGoodsId);
+		}
+
+		$newStoreNums     = 0;
+		$updateGoodsId    = array();
+		$orderGoodsObj    = new IModel('order_goods');
+		$goodsObj         = new IModel('goods');
+		$productObj       = new IModel('products');
+		$goodsList        = $orderGoodsObj->query('id in('.join(",",$orderGoodsId).') and is_send = 0','goods_id,product_id,goods_nums,seller_id');
+
+		foreach($goodsList as $key => $val)
+		{
+			//货品库存更新
+			if($val['product_id'] != 0)
+			{
+				$productObj->lock = 'for update';
+				$productsRow = $productObj->getObj('id = '.$val['product_id'],'store_nums');
+				$productObj->lock = '';
+				if(!$productsRow)
+				{
+					continue;
+				}
+
+				//同步更新所属商品的库存量
+				if(in_array($val['goods_id'],$updateGoodsId) == false)
+				{
+					$updateGoodsId[] = $val['goods_id'];
+				}
+
+				$updateSql = $type == 'add' ? array('store_nums' => 'store_nums + '.$val['goods_nums']) : array('store_nums' => 'store_nums - '.$val['goods_nums']);
+				$productObj->setData($updateSql);
+				$productObj->update('id = '.$val['product_id'],'store_nums');
+			}
+			//商品库存更新
+			else
+			{
+				$goodsObj->lock = 'for update';
+				$goodsRow = $goodsObj->getObj('id = '.$val['goods_id'],'store_nums');
+				$goodsObj->lock = '';
+				if(!$goodsRow)
+				{
+					continue;
+				}
+
+				$updateSql = $type == 'add' ? array('store_nums' => 'store_nums + '.$val['goods_nums']) : array('store_nums' => 'store_nums - '.$val['goods_nums']);
+				$goodsObj->setData($updateSql);
+				$goodsObj->update('id = '.$val['goods_id'],'store_nums');
+			}
+			//库存减少销售量增加,两者成反比
+			$saleData = ($type == 'add') ? -$val['goods_nums'] : $val['goods_nums'];
+
+			//更新goods商品销售量sale字段
+			$goodsObj->setData(array('sale' => 'sale + '.$saleData));
+			$goodsObj->update('id = '.$val['goods_id'],'sale');
+
+			//更新seller商家销售量sale字段
+			$sellerDB = new IModel('seller');
+			$sellerDB->setData(array('sale' => 'sale + '.$saleData));
+			$sellerDB->update('id = '.$val['seller_id'],'sale');
+		}
+
+		//更新统计goods的库存
+		if($updateGoodsId)
+		{
+			foreach($updateGoodsId as $val)
+			{
+				$totalRow = $productObj->getObj('goods_id = '.$val,'SUM(store_nums) as store');
+				$goodsObj->setData(array('store_nums' => $totalRow['store']));
+				$goodsObj->update('id = '.$val);
+			}
+		}
+	}
+
+	/**
+	 * @brief 获取订单扩展数据资料
+	 * @param $order_id int 订单的id
+	 * @param $user_id int 用户id
+	 * @return array()
+	 */
+	public function getOrderShow($order_id,$user_id = 0,$seller_id = 0)
+	{
+		$where = 'id = '.$order_id;
+		if($user_id !== 0)
+		{
+			$where .= ' and user_id = '.$user_id;
+		}
+
+		if($seller_id !== 0)
+		{
+			$where .= ' and seller_id = '.$seller_id;
+		}
+
+		$data = array();
+
+		//获得对象
+		$tb_order = new IModel('order');
+ 		$data = $tb_order->getObj($where);
+ 		if($data)
+ 		{
+	 		$data['order_id'] = $order_id;
+
+	 		//获取配送方式
+	 		$tb_delivery = new IModel('delivery');
+	 		$delivery_info = $tb_delivery->getObj('id='.$data['distribution']);
+	 		if($delivery_info)
+	 		{
+	 			$data['delivery'] = $delivery_info['name'];
+
+	 			//自提点读取
+	 			if($data['takeself'])
+	 			{
+	 				$data['takeself'] = self::getTakeselfInfo($data['takeself']);
+	 			}
+	 		}
+
+	 		$areaData = area::name($data['province'],$data['city'],$data['area']);
+	 		if(isset($areaData[$data['province']]) && isset($areaData[$data['city']]) && isset($areaData[$data['area']]))
+	 		{
+		 		$data['province_str'] = $areaData[$data['province']];
+		 		$data['city_str']     = $areaData[$data['city']];
+		 		$data['area_str']     = $areaData[$data['area']];
+	 		}
+
+	        //物流单号
+	    	$tb_delivery_doc = new IQuery('delivery_doc as dd');
+	    	$tb_delivery_doc->join   = 'left join freight_company as fc on dd.freight_id = fc.id';
+	    	$tb_delivery_doc->fields = 'dd.id,dd.delivery_code,fc.freight_name';
+	    	$tb_delivery_doc->where  = 'order_id = '.$order_id;
+	    	$delivery_info = $tb_delivery_doc->find();
+	    	if($delivery_info)
+	    	{
+	    		$temp = array('freight_name' => array(),'delivery_code' => array(),'delivery_id' => array());
+	    		foreach($delivery_info as $key => $val)
+	    		{
+	    			$temp['delivery_id'][]   = $val['id'];
+	    			$temp['freight_name'][]  = $val['freight_name'];
+	    			$temp['delivery_code'][] = $val['delivery_code'];
+	    		}
+	    		$data['freight']['id']            = current($temp['delivery_id']);
+    			$data['freight']['freight_name']  = join(",",$temp['freight_name']);
+    			$data['freight']['delivery_code'] = join(",",$temp['delivery_code']);
+	    	}
+
+	 		//获取支付方式
+	 		$tb_payment = new IModel('payment');
+	 		$payment_info = $tb_payment->getObj('id='.$data['pay_type']);
+	 		if($payment_info)
+	 		{
+	 			$data['payment'] = $payment_info['name'];
+	 			$data['paynote'] = $payment_info['note'];
+	 		}
+
+	 		//获取商品总重量和总金额
+	 		$tb_order_goods = new IModel('order_goods');
+	 		$order_goods_info = $tb_order_goods->query('order_id='.$order_id);
+	 		$data['goods_amount'] = 0;
+	 		$data['goods_weight'] = 0;
+
+	 		if($order_goods_info)
+	 		{
+	 			foreach ($order_goods_info as $value)
+	 			{
+	 				$data['goods_amount'] += $value['real_price']   * $value['goods_nums'];
+	 				$data['goods_weight'] += $value['goods_weight'] * $value['goods_nums'];
+	 			}
+	 		}
+
+	 		//获取用户信息
+	 		$query = new IQuery('user as u');
+	 		$query->join = ' left join member as m on u.id=m.user_id ';
+	 		$query->fields = 'u.username,m.email,m.mobile,m.contact_addr,m.true_name';
+	 		$query->where = 'u.id='.$data['user_id'];
+	 		$user_info = $query->find();
+	 		if($user_info)
+	 		{
+	 			$user_info = current($user_info);
+	 			$data['username']     = $user_info['username'];
+	 			$data['email']        = $user_info['email'];
+	 			$data['u_mobile']     = $user_info['mobile'];
+	 			$data['contact_addr'] = $user_info['contact_addr'];
+	 			$data['true_name']    = $user_info['true_name'];
+	 		}
+	 		//数据处理用于显示
+	 		$data['goods_weight'] = common::formatWeight($data['goods_weight']);
+ 		}
+ 		return $data;
+	}
+
+	/**
+	 * 获取自提点基本信息
+	 * @param $id int 自提点id
+	 */
+	public static function getTakeselfInfo($id)
+	{
+		$takeselfObj = new IModel('takeself');
+		$takeselfRow = $takeselfObj->getObj('id = '.$id);
+		if(!$takeselfRow)
+		{
+			return '';
+		}
+
+		$temp = area::name($takeselfRow['province'],$takeselfRow['city'],$takeselfRow['area']);
+		$takeselfRow['province_str'] = $temp[$takeselfRow['province']];
+		$takeselfRow['city_str']     = $temp[$takeselfRow['city']];
+		$takeselfRow['area_str']     = $temp[$takeselfRow['area']];
+		return $takeselfRow;
+	}
+
+	/**
+	 * 获取订单基本信息
+	 * @param $orderIdString string 订单ID序列
+	 * @param $seller_id int 商家ID
+	 */
+	public function getOrderInfo($orderIdString,$seller_id = 0)
+	{
+		$orderObj    = new IModel('order');
+		$areaIdArray = array();
+		$where       = 'id in ('.$orderIdString.')';
+		if(!IWeb::$app->getController()->admin['admin_id'])
+		{
+			$where .= 'and seller_id = '.$seller_id;
+		}
+		$orderList = $orderObj->query($where);
+
+		if(!$orderList)
+		{
+			IError::show(403,"无查阅订单权限");
+		}
+
+		foreach($orderList as $key => $val)
+		{
+			$temp = area::name($val['province'],$val['city'],$val['area']);
+			$orderList[$key]['province_str'] = $temp[$val['province']];
+			$orderList[$key]['city_str']     = $temp[$val['city']];
+			$orderList[$key]['area_str']     = $temp[$val['area']];
+		}
+
+		return $orderList;
+	}
+
+	/**
+	 * @brief 把订单商品同步到order_goods表中
+	 * @param $order_id 订单ID
+	 * @param $goodsInfo 商品和货品信息(购物车数据结构,countSum 最终生成的格式)
+	 */
+	public function insertOrderGoods($order_id,$goodsResult = array())
+	{
+		$orderGoodsObj = new IModel('order_goods');
+		if(isset($goodsResult['goodsList']) && $goodsResult['goodsList'])
+		{
+			//清理旧的关联数据
+			$orderGoodsObj->del('order_id = '.$order_id);
+
+			$goodsArray = array(
+				'order_id' => $order_id
+			);
+
+			foreach($goodsResult['goodsList'] as $key => $val)
+			{
+				//拼接商品名称和规格数据
+				$specArray = array('name' => $val['name'],'goodsno' => $val['goods_no'],'value' => '');
+
+				if(isset($val['spec_array']))
+				{
+					$spec = block::show_spec($val['spec_array']);
+					foreach($spec as $skey => $svalue)
+					{
+						$specArray['value'] .= $skey.':'.$svalue.',';
+					}
+					$specArray['value'] = trim($specArray['value'],',');
+				}
+
+				$goodsArray['product_id']  = $val['product_id'];
+				$goodsArray['goods_id']    = $val['goods_id'];
+				$goodsArray['img']         = $val['img'];
+				$goodsArray['goods_price'] = $val['sell_price'];
+				$goodsArray['real_price']  = $val['sell_price'] - $val['reduce'];
+				$goodsArray['goods_nums']  = $val['count'];
+				$goodsArray['goods_weight']= $val['weight'];
+				$goodsArray['goods_array'] = IFilter::addSlash(JSON::encode($specArray));
+				$goodsArray['seller_id']   = $val['seller_id'];
+				$orderGoodsObj->setData($goodsArray);
+				if(!$orderGoodsObj->add())
+				{
+					$orderGoodsObj->rollback();
+					return '订单和商品关系插入报错';
+				}
+			}
+			return true;
+		}
+		else
+		{
+			$orderGoodsObj->rollback();
+			return '商品数据不存在';
+		}
+	}
+	/**
+	 * 获取订单状态
+	 * @param $orderRow array('status' => '订单状态','pay_type' => '支付方式ID','distribution_status' => '配送状态','pay_status' => '支付状态')
+	 * @return int 订单状态值 0:未知; 1:未付款等待发货(货到付款); 2:等待付款(线上支付); 3:已发货(已付款); 4:已付款等待发货; 5:已取消; 6:已完成(已付款,已收货); 7:全部退款; 8:部分发货(货到付款+已经付款); 9:部分退款(未发货+部分发货); 10:部分退款(全部发货); 11:已发货(货到付款); 12:未处理的退款申请
+	 */
+	public static function getOrderStatus($orderRow)
+	{
+		//1,刚生成订单,未付款
+		if($orderRow['status'] == 1)
+		{
+			//选择货到付款
+			if($orderRow['pay_type'] == 0)
+			{
+				if($orderRow['distribution_status'] == 0)
+				{
+					return 1;
+				}
+				else if($orderRow['distribution_status'] == 1)
+				{
+					return 11;
+				}
+				else if($orderRow['distribution_status'] == 2)
+				{
+					return 8;
+				}
+			}
+			//选择在线支付
+			else
+			{
+				return 2;
+			}
+		}
+		//2,已经付款
+		else if($orderRow['status'] == 2)
+		{
+			$refundDB  = new IModel('refundment_doc');
+			$refundRow = $refundDB->getObj('order_no = "'.$orderRow['order_no'].'" and if_del = 0 and pay_status = 0');
+			if($refundRow)
+			{
+				return 12;
+			}
+
+			if($orderRow['distribution_status'] == 0)
+			{
+				return 4;
+			}
+			else if($orderRow['distribution_status'] == 1)
+			{
+				return 3;
+			}
+			else if($orderRow['distribution_status'] == 2)
+			{
+				return 8;
+			}
+		}
+		//3,取消或者作废订单
+		else if($orderRow['status'] == 3 || $orderRow['status'] == 4)
+		{
+			return 5;
+		}
+		//4,完成订单
+		else if($orderRow['status'] == 5)
+		{
+			return 6;
+		}
+		//5,退款
+		else if($orderRow['status'] == 6)
+		{
+			return 7;
+		}
+		//6,部分退款
+		else if($orderRow['status'] == 7)
+		{
+			//发货
+			if($orderRow['distribution_status'] == 1)
+			{
+				return 10;
+			}
+			//未发货
+			else
+			{
+				return 9;
+			}
+		}
+		return 0;
+	}
+
+	//获取订单支付状态
+	public static function getOrderPayStatusText($orderRow)
+	{
+		if($orderRow['status'] == '6')
+		{
+			return '全部退款';
+		}
+
+		if($orderRow['status'] == '7')
+		{
+			return '部分退款';
+		}
+
+		if($orderRow['pay_status'] == 0)
+		{
+			return '未付款';
+		}
+
+		if($orderRow['pay_status'] == 1)
+		{
+			return '已付款';
+		}
+		return '未知';
+	}
+
+	//获取订单类型
+	public static function getOrderTypeText($orderRow)
+	{
+		switch($orderRow['type'])
+		{
+			case "1":
+			{
+				return '团购订单';
+			}
+			break;
+
+			case "2":
+			{
+				return '抢购订单';
+			}
+			break;
+
+			default:
+			{
+				return '普通订单';
+			}
+		}
+	}
+
+	//获取订单配送状态
+	public static function getOrderDistributionStatusText($orderRow)
+	{
+		if($orderRow['status'] == 5)
+		{
+			return '已收货';
+		}
+		else if($orderRow['distribution_status'] == 1)
+		{
+			return '已发货';
+		}
+		else if($orderRow['distribution_status'] == 0)
+		{
+			return '未发货';
+		}
+		else if($orderRow['distribution_status'] == 2)
+		{
+			return '部分发货';
+		}
+	}
+
+	/**
+	 * 获取订单状态问题说明
+	 * @param $statusCode int 订单的状态码
+	 * @return string 订单状态说明
+	 */
+	public static function orderStatusText($statusCode)
+	{
+		$result = array(
+			0 => '未知',
+			1 => '等待发货',
+			2 => '等待付款',
+			3 => '已发货',
+			4 => '等待发货',
+			5 => '已取消',
+			6 => '已完成',
+			7 => '已退款',
+			8 => '部分发货',
+			9 => '部分退款',
+			10=> '部分退款',
+			11=> '已发货',
+			12=> '申请退款',
+		);
+		return isset($result[$statusCode]) ? $result[$statusCode] : '';
+	}
+
+	/**
+	 * @breif 订单的流向
+	 * @param $orderRow array 订单数据
+	 * @return array('时间' => '事件')
+	 */
+	public static function orderStep($orderRow)
+	{
+		$result = array();
+
+		//1,创建订单
+		$result[$orderRow['create_time']] = '订单创建';
+
+		//2,订单支付
+		if($orderRow['pay_status'] > 0)
+		{
+			$result[$orderRow['pay_time']] = '订单付款  '.$orderRow['order_amount'];
+		}
+
+		//3,订单配送
+        if($orderRow['distribution_status'] > 0)
+        {
+        	$result[$orderRow['send_time']] = '订单发货完成';
+    	}
+
+		//4,订单完成
+        if($orderRow['status'] == 5)
+        {
+        	$result[$orderRow['completion_time']] = '订单完成';
+        }
+        ksort($result);
+        return $result;
+	}
+
+	/**
+	 * @brief 商品发货接口
+	 * @param string $order_id 订单id
+	 * @param array $order_goods_relation 订单与商品关联id
+	 * @param int $sendor_id 操作者id
+	 * @param string $sendor 操作者所属 admin,seller
+	 */
+	public static function sendDeliveryGoods($order_id,$order_goods_relation,$sendor_id,$sendor = 'admin')
+	{
+		$order_no = IFilter::act(IReq::get('order_no'));
+
+		//检查此订单是否存在未处理的退款申请
+		$refundDB = new IModel('refundment_doc');
+		$refundRow= $refundDB->getObj('order_no = "'.$order_no.'" and pay_status = 0 and if_del = 0');
+		if($refundRow)
+		{
+			return "此订单有未处理的退款申请";
+		}
+
+	 	$paramArray = array(
+	 		'order_id'      => $order_id,
+	 		'user_id'       => IFilter::act(IReq::get('user_id'),'int'),
+	 		'name'          => IFilter::act(IReq::get('name')),
+	 		'postcode'      => IFilter::act(IReq::get('postcode'),'int'),
+	 		'telphone'      => IFilter::act(IReq::get('telphone')),
+	 		'province'      => IFilter::act(IReq::get('province'),'int'),
+	 		'city'          => IFilter::act(IReq::get('city'),'int'),
+	 		'area'          => IFilter::act(IReq::get('area'),'int'),
+	 		'address'       => IFilter::act(IReq::get('address')),
+	 		'mobile'        => IFilter::act(IReq::get('mobile')),
+	 		'freight'       => IFilter::act(IReq::get('freight'),'float'),
+	 		'delivery_code' => IFilter::act(IReq::get('delivery_code')),
+	 		'delivery_type' => IFilter::act(IReq::get('delivery_type')),
+	 		'note'          => IFilter::act(IReq::get('note'),'text'),
+	 		'time'          => ITime::getDateTime(),
+	 		'freight_id'    => IFilter::act(IReq::get('freight_id'),'int'),
+	 	);
+
+	 	switch($sendor)
+	 	{
+	 		case "admin":
+	 		{
+	 			$paramArray['admin_id'] = $sendor_id;
+
+	 			$adminDB = new IModel('admin');
+	 			$sendorData = $adminDB->getObj('id = '.$sendor_id);
+	 			$sendorName = $sendorData['admin_name'];
+	 			$sendorSort = '平台管理员';
+	 		}
+	 		break;
+
+	 		case "seller":
+	 		{
+	 			$paramArray['seller_id'] = $sendor_id;
+
+	 			$sellerDB = new IModel('seller');
+	 			$sendorData = $sellerDB->getObj('id = '.$sendor_id);
+	 			$sendorName = $sendorData['true_name'];
+	 			$sendorSort = '加盟商户';
+	 		}
+	 		break;
+	 	}
+
+		//订单对象
+		$tb_order   = new IModel('order');
+		$tbOrderRow = $tb_order->getObj('id = '.$order_id);
+
+    	//发送短信,生成订单日志,生成发货单
+    	//1,自提点领取
+    	if($tbOrderRow['takeself'] > 0)
+    	{
+    		//自提商品不需要发货单
+    		$deliveryId = 0;
+
+    		//短信内容
+    		$takeDB = new IModel('takeself');
+    		$takeRow= $takeDB->getObj('id = '.$tbOrderRow['takeself']);
+	    	$replaceData = array(
+	    		'{user_name}' => $paramArray['name'],
+	    		'{order_no}'  => $order_no,
+	    		'{takeself}'  => $takeRow['name'],
+	    	);
+    		$mobileMsg = smsTemplate::takeselfGoods($replaceData);
+
+    		//订单日志内容
+			$logArray = array(
+				'order_id' => $order_id,
+				'user'     => $sendorName,
+				'action'   => '自提',
+				'result'   => '成功',
+				'note'     => '订单【'.$order_no.'】由【'.$sendorSort.'】'.$sendorName.'处理自提',
+				'addtime'  => ITime::getDateTime(),
+			);
+    	}
+    	//2,普通发货物流
+    	else
+    	{
+		 	//插入发货单
+		 	$tb_delivery_doc = new IModel('delivery_doc');
+		 	$tb_delivery_doc->setData($paramArray);
+		 	$deliveryId = $tb_delivery_doc->add();
+
+    		//短信内容
+	    	$freightDB  = new IModel('freight_company');
+	    	$freightRow = $freightDB->getObj('id = '.$paramArray['freight_id']);
+	    	$replaceData = array(
+	    		'{user_name}'        => $paramArray['name'],
+	    		'{order_no}'         => $order_no,
+	    		'{sendor}'           => '['.$sendorSort.']'.$sendorName,
+	    		'{delivery_company}' => $freightRow['freight_name'],
+	    		'{delivery_no}'      => $paramArray['delivery_code'],
+	    	);
+	    	$mobileMsg = smsTemplate::sendGoods($replaceData);
+
+	    	//订单日志内容
+			$logArray = array(
+				'order_id' => $order_id,
+				'user'     => $sendorName,
+				'action'   => '发货',
+				'result'   => '成功',
+				'note'     => '订单【'.$order_no.'】由【'.$sendorSort.'】'.$sendorName.'发货',
+				'addtime'  => ITime::getDateTime(),
+			);
+    	}
+    	//短信发送
+    	Hsms::send($paramArray['mobile'],$mobileMsg,0);
+
+		//订单日志记录
+    	$tb_order_log = new IModel('order_log');
+    	$tb_order_log->setData($logArray);
+    	$sendResult = $tb_order_log->add();
+    	if(!$sendResult)
+    	{
+    		$tb_order_log->rollback();
+    		die('订单日志生成错误');
+    	}
+
+		//如果支付方式为货到付款,则减少库存
+		if($tbOrderRow['pay_type'] == 0)
+		{
+		 	//减少库存量
+		 	self::updateStore($order_goods_relation,'reduce');
+		}
+
+		//更新发货状态
+	 	$orderGoodsDB = new IModel('order_goods');
+	 	$orderGoodsRow = $orderGoodsDB->getObj('is_send = 0 and order_id = '.$order_id,'count(*) as num');
+		$sendStatus = 2;//部分发货
+	 	if(count($order_goods_relation) >= $orderGoodsRow['num'])
+	 	{
+	 		$sendStatus = 1;//全部发货
+	 	}
+	 	foreach($order_goods_relation as $key => $val)
+	 	{
+	 		//商家发货检查商品所有权
+	 		if(isset($paramArray['seller_id']))
+	 		{
+	 			$orderGoodsData = $orderGoodsDB->getObj("id = ".$val);
+	 			$goodsDB = new IModel('goods');
+	 			$sellerResult = $goodsDB->getObj("id = ".$orderGoodsData['goods_id']." and seller_id = ".$paramArray['seller_id']);
+	 			if(!$sellerResult)
+	 			{
+	 				$goodsDB->rollback();
+	 				die('发货的商品信息与商家不符合');
+	 			}
+	 		}
+
+	 		$orderGoodsDB->setData(array(
+	 			"is_send"     => 1,
+	 			"delivery_id" => $deliveryId,
+	 		));
+
+	 		if(!$orderGoodsDB->update(" id = {$val} "))
+	 		{
+	 			$orderGoodsDB->rollback();
+				die('订单商品发货状态修改失败');
+	 		}
+	 	}
+
+	 	//更新发货状态
+	 	$orderUpdate = array(
+	 		'distribution_status' => $sendStatus,
+	 		'send_time'           => ITime::getDateTime(),
+	 	);
+
+ 		//如果全部发货之前已存在 "部分退款" 那么更新订单状态以允许“确认收货”按钮可用
+ 		if($tbOrderRow['status'] == 7 && $sendStatus == 1)
+ 		{
+ 			$orderUpdate['status'] = 2;
+ 		}
+	 	$tb_order->setData($orderUpdate);
+	 	if(!$tb_order->update('id='.$order_id))
+	 	{
+	 		$tb_order->rollback();
+	 		die('订单更新失败');
+	 	}
+    	return true;
+	}
+
+	/**
+	 * @biref 是否可以发货操作
+	 * @param array $orderRow 订单对象
+	 */
+	public static function isGoDelivery($orderRow)
+	{
+		/* 1,已经完全发货
+		 * 2,非货到付款,并且没有支付*/
+		if($orderRow['distribution_status'] == 1 || ($orderRow['pay_type'] != 0 && $orderRow['pay_status'] == 0) || self::getOrderStatus($orderRow) == 12)
+		{
+			return false;
+		}
+		return true;
+	}
+
+	/**
+	 * @brief 获取商品发送状态
+	 */
+	public static function goodsSendStatus($is_send)
+	{
+		$data = array(0 => '未发货',1 => '已发货',2 => '已退货');
+		return isset($data[$is_send]) ? $data[$is_send] : '';
+	}
+
+	//获取订单商品信息
+	public static function getOrderGoods($order_id)
+	{
+		$orderGoodsObj        = new IQuery('order_goods');
+		$orderGoodsObj->where = "order_id = ".$order_id;
+		$orderGoodsObj->fields = 'id,goods_array,goods_id,product_id,goods_nums';
+		$orderGoodsList = $orderGoodsObj->find();
+		$goodList = array();
+		foreach($orderGoodsList as $good)
+		{
+			$temp = JSON::decode($good['goods_array']);
+			$temp['goods_nums'] = $good['goods_nums'];
+			$goodList[] = $temp;
+		}
+		return $goodList;
+	}
+
+	/**
+	 * @brief 返回检索条件相关信息
+	 * @param int $search 条件数组
+	 * @return array 查询条件($join,$where)数据组
+	 */
+	public static function getSearchCondition($search)
+	{
+		$join  = "left join delivery as d on o.distribution = d.id left join payment as p on o.pay_type = p.id";
+		$where = "if_del = 0";
+		//条件筛选处理
+		if(isset($search['is_seller']))
+		{
+			$is_seller = IFilter::act($search['is_seller']);
+			if($is_seller == "self")
+			{
+				$where .= " and o.seller_id = 0 ";
+			}
+			else if($is_seller == "seller")
+			{
+				$where .= " and o.seller_id != 0 ";
+			}
+		}
+
+		if(isset($search['pay_status']) && $search['pay_status'] !== '')
+		{
+			$pay_status = IFilter::act($search['pay_status'], 'int');
+			$where .= " and o.pay_status = ".$pay_status;
+		}
+
+		if(isset($search['distribution_status']) && $search['distribution_status'] !== '')
+		{
+			$distribution_status = IFilter::act($search['distribution_status'], 'int');
+			$where .= " and o.distribution_status = ".$distribution_status;
+		}
+
+		if(isset($search['status']) && $search['status'] !== '')
+		{
+			$status = IFilter::act($search['status'], 'int');
+			$where .= " and o.status = ".$status;
+		}
+
+		if(isset($search['name']) && isset($search['keywords']))
+		{
+			$name = IFilter::act($search['name'], 'string');
+			$keywords = IFilter::act($search['keywords'], 'string');
+			if ($name && $keywords)
+			{
+				switch ($name)
+				{
+					case "seller_name":
+					{
+						$sellerObj = new IModel('seller');
+						$sellerRow = $sellerObj->getObj('true_name = "'.$keywords.'"');
+						$where .= $sellerRow ? " and o.seller_id = ".$sellerRow['id'] : " and null ";
+					}
+					break;
+
+					default:
+						$where .= " and o.".$name." = '".$keywords."'";
+					break;
+				}
+			}
+		}
+
+		// 高级筛选
+		if (isset($search['adv_search']) && 1 == $search['adv_search'])
+		{
+			// 订单总额
+			if (isset($search['order_amount']) && !empty($search['order_amount']))
+			{
+				$order_amount = explode(",", $search['order_amount']);
+				$order_amount_0 = IFilter::act($order_amount[0], 'float');
+				if (isset($order_amount[1]))
+				{
+					$order_amount_1 = IFilter::act($order_amount[1], 'float');
+				}
+				else
+				{
+					$order_amount_1 = 0;
+				}
+				if ($order_amount_0 == $order_amount_1)
+				{
+					$where .= " and o.order_amount = $order_amount_0 ";
+				}
+				else if ($order_amount_0 > $order_amount_1)
+				{
+					$where .= " and o.order_amount between $order_amount_1 and $order_amount_0 ";
+				}
+				else
+				{
+					$where .= " and o.order_amount between $order_amount_0 and $order_amount_1 ";
+				}
+			}
+			// 发货时间
+			if (isset($search['send_time']) && !empty($search['send_time']))
+			{
+				$send_time = explode(",", $search['send_time']);
+				// 验证日期
+				$is_check_0 = ITime::checkDateTime($send_time[0]);
+				$is_check_1 = false;
+				if (isset($send_time[1]))
+				{
+					$is_check_1 = ITime::checkDateTime($send_time[1]);
+				}
+				if ($is_check_0 && $is_check_1)
+				{
+					// 是否相等
+					if ($send_time[0] == $send_time[1])
+					{
+						$where .= " and o.send_time between '".$send_time[0]." 00:00:00' and '".$send_time[0]." 23:59:59'";
+					}
+					else
+					{
+						$difference = ITime::getDiffSec($send_time[0].' 00:00:00', $send_time[1].' 00:00:00');
+						if (0 < $difference)
+						{
+							$where .= " and o.send_time between '".$send_time[1]." 00:00:00' and '".$send_time[0]." 23:59:59'";
+						}
+						else
+						{
+							$where .= " and o.send_time between '".$send_time[0]." 00:00:00' and '".$send_time[1]." 23:59:59'";
+						}
+					}
+				}
+				elseif ($is_check_0)
+				{
+					$where .= " and o.send_time between '".$send_time[0]." 00:00:00' and '".$send_time[0]." 23:59:59'";
+				}
+			}
+			// 下单时间
+			if (isset($search['create_time']) && !empty($search['create_time']))
+			{
+				$create_time = explode(",", $search['create_time']);
+				// 验证日期
+				$is_check_0 = ITime::checkDateTime($create_time[0]);
+				$is_check_1 = false;
+				if (isset($create_time[1]))
+				{
+					$is_check_1 = ITime::checkDateTime($create_time[1]);
+				}
+				if ($is_check_0 && $is_check_1)
+				{
+					// 是否相等
+					if ($create_time[0] == $create_time[1])
+					{
+						$where .= " and o.create_time between '".$create_time[0]." 00:00:00' and '".$create_time[0]." 23:59:59'";
+					}
+					else
+					{
+						$difference = ITime::getDiffSec($create_time[0].' 00:00:00', $create_time[1].' 00:00:00');
+						if (0 < $difference)
+						{
+							$where .= " and o.create_time between '".$create_time[1]." 00:00:00' and '".$create_time[0]." 23:59:59'";
+						}
+						else
+						{
+							$where .= " and o.create_time between '".$create_time[0]." 00:00:00' and '".$create_time[1]." 23:59:59'";
+						}
+					}
+				}
+				elseif ($is_check_0)
+				{
+					$where .= " and o.create_time between '".$create_time[0]." 00:00:00' and '".$create_time[0]." 23:59:59'";
+				}
+			}
+			// 完成时间
+			if (isset($search['completion_time']) && !empty($search['completion_time']))
+			{
+				$completion_time = explode(",", $search['completion_time']);
+				// 验证日期
+				$is_check_0 = ITime::checkDateTime($completion_time[0]);
+				$is_check_1 = false;
+				if (isset($completion_time[1]))
+				{
+					$is_check_1 = ITime::checkDateTime($completion_time[1]);
+				}
+				if ($is_check_0 && $is_check_1)
+				{
+					// 是否相等
+					if ($completion_time[0] == $completion_time[1])
+					{
+						$where .= " and o.completion_time between '".$completion_time[0]." 00:00:00' and '".$completion_time[0]." 23:59:59'";
+					}
+					else
+					{
+						$difference = ITime::getDiffSec($completion_time[0].' 00:00:00', $completion_time[1].' 00:00:00');
+						if (0 < $difference)
+						{
+							$where .= " and o.completion_time between '".$completion_time[1]." 00:00:00' and '".$completion_time[0]." 23:59:59'";
+						}
+						else
+						{
+							$where .= " and o.completion_time between '".$completion_time[0]." 00:00:00' and '".$completion_time[1]." 23:59:59'";
+						}
+					}
+				}
+				elseif ($is_check_0)
+				{
+					$where .= " and o.completion_time between '".$completion_time[0]." 00:00:00' and '".$completion_time[0]." 23:59:59'";
+				}
+			}
+		}
+		$results = array($join,$where);
+		unset($join,$where);
+		return $results;
+	}
+
+	/**
+	 * @brief 是否允许退款申请
+	 * @param array $orderRow 订单表的数据结构
+	 * @param array $orderGoodsIds 订单与商品关系表ID数组
+	 * @return boolean true or false
+	 */
+	public static function isRefundmentApply($orderRow,$orderGoodsIds = array())
+	{
+		if(!is_array($orderGoodsIds))
+		{
+			return "退款商品ID数据类型错误";
+		}
+
+		//要退款的orderGoodsId关联信息
+		if($orderGoodsIds)
+		{
+			$order_id     = $orderRow['id'];
+			$goodsOrderDB = new IModel('order_goods');
+			$refundsDB    = new IModel('refundment_doc');
+
+			foreach($orderGoodsIds as $key => $val)
+			{
+				$goodsOrderRow = $goodsOrderDB->getObj('id = '.$val.' and order_id = '.$order_id);
+				if($goodsOrderRow && $goodsOrderRow['is_send'] == 2)
+				{
+					return "有商品已经做了退款处理";
+				}
+
+				if( $refundsDB->getObj('if_del = 0 and pay_status = 0 and FIND_IN_SET('.$val.',order_goods_id)') )
+				{
+					return "您已经对此商品提交了退款申请,请耐心等待";
+				}
+			}
+
+    		//判断是否已经生成了结算申请或者已经结算了
+    		$billObj = new IModel('bill');
+    		$billRow = $billObj->getObj('FIND_IN_SET('.$order_id.',order_ids)');
+    		if($billRow)
+    		{
+    			return '此订单金额已被商家结算完毕,请直接与商家联系退款';
+    		}
+    		return true;
+		}
+		else
+		{
+			//已经付款,并且未全部退款,未正在发货中
+			if($orderRow['pay_status'] == 1 && $orderRow['status'] != 6 && self::getOrderStatus($orderRow) != 3)
+			{
+				return true;
+			}
+			return false;
+		}
+	}
+
+	/**
+	 * @brief 退款状态
+	 * @param int $pay_status 退款单状态数值
+	 * @return string 状态描述
+	 */
+	public static function refundmentText($pay_status)
+	{
+		$result = array('0' => '申请退款', '1' => '退款失败', '2' => '退款成功');
+		return isset($result[$pay_status]) ? $result[$pay_status] : '';
+	}
+
+	/**
+	 * @brief 还原重置订单所使用的道具
+	 * @param int $order 订单ID
+	 */
+	public static function resetOrderProp($order_id)
+	{
+		$orderDB   = new IModel('order');
+		$orderList = $orderDB->query('id in ( '.$order_id.' )  and prop is not null');
+		foreach($orderList as $key => $orderRow)
+		{
+			if(isset($orderRow['prop']) && $orderRow['prop'])
+			{
+				$propDB = new IModel('prop');
+				$propDB->setData(array('is_close' => 0,'is_userd' => 0));
+				$propDB->update('id = '.$orderRow['prop']);
+
+				//订单付款状态要把代金券ID添加到member表的prop字段中
+				if($orderRow['pay_status'] == 1)
+				{
+					//更新用户prop字段
+					$insert_id   = $orderRow['prop'];
+					$memberArray = array('prop' => "CONCAT(IFNULL(prop,''),'{$insert_id},')");
+					$memberObj   = new IModel('member');
+					$memberObj->setData($memberArray);
+					$memberObj->update('user_id = '.$orderRow["user_id"],'prop');
+				}
+			}
+		}
+	}
+
+	/**
+	 * @brief 商家对退款申请的处理权限
+	 * @param int $refundId 退款单ID
+	 * @param int $seller_id 商家ID
+	 * @return int 退款权限状态, 0:无权查看;1:只读;2:可读可写
+	 */
+	public static function isSellerRefund($refundId,$seller_id)
+	{
+		$refundDB = new IModel('refundment_doc');
+		$refundRow= $refundDB->getObj('id = '.$refundId.' and seller_id = '.$seller_id);
+
+		if($refundRow)
+		{
+			$orderDB = new IModel('order');
+			$orderRow= $orderDB->getObj('id = '.$refundRow['order_id']);
+			if($orderRow['is_checkout'] == 1)
+			{
+				return 1;
+			}
+			else
+			{
+				return 2;
+			}
+		}
+		return 0;
+	}
+
+	/**
+	 * @brief 订单退款操作
+	 * @param int    $refundId 退款单ID
+	 * @param int    $authorId 操作人ID
+	 * @param string $type admin:管理员;seller:商家
+	 * @param int    $way 退款方式, balance:退款余额; other:其他方式退款; origin,原路退回
+	 * @return boolean
+	 */
+	public static function refund($refundId,$authorId,$type = 'admin',$way = 'balance')
+	{
+		plugin::trigger('refundBefore',$refundId);
+		$orderGoodsDB   = new IModel('order_goods');
+		$refundDB       = new IModel('refundment_doc');
+		$goodsDB        = new IModel('goods');
+		$memberDB       = new IModel('member');
+		$tb_order       = new IModel('order');
+
+		$where = 'id = '.$refundId;
+		if($type == "seller")
+		{
+			$where .= ' and seller_id = '.$authorId;
+		}
+
+		$refundsRow = $refundDB->getObj($where);
+		$order_id   = $refundsRow['order_id'];
+		$order_no   = $refundsRow['order_no'];
+		$user_id    = $refundsRow['user_id'];
+
+		if(!$refundsRow)
+		{
+			return "退款申请信息不存在";
+		}
+
+		if(!$refundsRow['order_goods_id'])
+		{
+			return "退款商品信息为空";
+		}
+
+		//当前退款的商品是否之前从未退款
+		$orderGoodsList = $orderGoodsDB->query('id in ('.$refundsRow['order_goods_id'].') and order_id = '.$refundsRow['order_id'].' and is_send != 2');
+		$order_goods_id = explode(",",$refundsRow['order_goods_id']);
+		if(count($orderGoodsList) != count($order_goods_id))
+		{
+			return "要退款商品的状态不正确";
+		}
+
+		//当前退款操作是否为订单的全部退款,如果待退款的商品数量和本次提交退款的商品数量相同则认为此次为全部退款状态
+		$orderGoodsListTemp = $orderGoodsDB->query('order_id = '.$refundsRow['order_id'].' and is_send != 2');
+		$order_goods_id     = explode(",",$refundsRow['order_goods_id']);
+
+		//获取订单数据
+		$orderRow = $tb_order->getObj('id = '.$order_id);
+
+		//全部退款
+		$amount = $refundsRow['amount'];
+		if(count($orderGoodsListTemp) == count($order_goods_id))
+		{
+			$orderStatus = 6;
+
+			//自动计算订单剩余的退款金额,把各项已经退款去除
+			if($amount == 0)
+			{
+				$amount = $orderRow['order_amount'];
+
+				//检查之前已经退款的订单
+				$hasRefundData = $refundDB->query("order_id = ".$refundsRow['order_id']." and pay_status = 2","amount");
+				if($hasRefundData)
+				{
+					foreach($hasRefundData as $value)
+					{
+						$amount -= $value['amount'];
+					}
+				}
+			}
+		}
+		//部分退款
+		else
+		{
+			$orderStatus = 7;
+
+			//自动计算选择的商品退款金额
+			if($amount == 0)
+			{
+				foreach($orderGoodsList as $key => $val)
+				{
+					$amount += $val['goods_nums'] * $val['real_price'];
+				}
+			}
+		}
+
+		//校验订单金额
+		$totalRefundSum = $amount;
+		$hasRefundSum   = $refundDB->getObj('order_id = '.$order_id.' and pay_status = 2','SUM(amount) as sumAmount');
+		if($hasRefundSum && isset($hasRefundSum['sumAmount']) && $hasRefundSum['sumAmount'])
+		{
+			$totalRefundSum += $hasRefundSum['sumAmount'];
+		}
+
+		if($totalRefundSum > $orderRow['order_amount'])
+		{
+			return "退款金额不能大于实际用户支付的订单金额";
+		}
+
+		//如果是商家自己处理的货到付款订单必须用其他方式退款,防止商家和买家刷余额
+		if($orderRow['pay_type'] == 0 && $type == "seller")
+		{
+			$way = 'other';
+		}
+
+		//处理退款金额最终流向
+		$wayResult = false;
+		switch($way)
+		{
+			//用户余额
+			case "balance":
+			{
+				//获取用户信息
+				$memberObj = $memberDB->getObj('user_id = '.$user_id,'user_id');
+				if(!$memberObj)
+				{
+					return "退款到余额的用户不存在";
+				}
+				//用户余额进行的操作记入account_log表
+				$log = new AccountLog();
+				$config = array(
+					'user_id'  => $user_id,
+					'event'    => 'drawback', //withdraw:提现,pay:余额支付,recharge:充值,drawback:退款到余额
+					'num'      => $amount, //整形或者浮点,正为增加,负为减少
+					'order_no' => $order_no // drawback类型的log需要这个值
+				);
+
+				if($type == 'admin')
+				{
+					$config['admin_id'] = $authorId;
+				}
+				else if($type == 'seller')
+				{
+					$config['seller_id'] = $authorId;
+				}
+				$wayResult = $log->write($config);
+				$wayResult = $wayResult > 0 ? true : false;
+			}
+			break;
+
+			//其他方式
+			case "other":
+			{
+				$wayResult = true;
+			}
+			break;
+
+			//原路退回
+			case "origin":
+			{
+				//更新退款表退款金额
+				$refundDB->setData(array('amount' => $amount));
+				$refundDB->update('id = '.$refundId);
+
+				$payment_id = $orderRow['pay_type'];
+				$paymentInstance = Payment::createPaymentInstance($payment_id);
+				if(!method_exists($paymentInstance,"doRefund"))
+				{
+					return '此订单的支付方式不支持原路退回,请更换其他退款方式';
+				}
+				$refundInfo = Payment::getRefundInfo($payment_id,$orderRow,$refundsRow);
+				$wayResult  = $paymentInstance->doRefund($refundInfo);
+			}
+			break;
+		}
+
+		if($wayResult && is_string($wayResult))
+		{
+			return $wayResult;
+		}
+
+		if($wayResult !== true)
+		{
+			return "退款失败";
+		}
+
+		//累计各项数据进行还原操作
+		$reduceExp   = 0;
+		$reducePoint = 0;
+
+		foreach($orderGoodsList as $key => $val)
+		{
+			//库存增加
+			self::updateStore($val['id'],'add');
+
+			//更新退款状态
+			$orderGoodsDB->setData(array('is_send' => 2));
+			$orderGoodsDB->update('id = '.$val['id']);
+
+			//退款积分,经验
+			$goodsRow = $goodsDB->getObj('id = '.$val['goods_id']);
+			$reduceExp   += $goodsRow['exp']  * $val['goods_nums'];
+			$reducePoint += $goodsRow['point']* $val['goods_nums'];
+		}
+
+		//更新订单状态
+		$tb_order->setData(array('status' => $orderStatus));
+		$tb_order->update('id='.$order_id);
+
+		/**
+		 * 当订单为全部退款的状态且未手动输入退款金额(需要系统自动计算退款金额)的时候
+		 * 退款金额 = 订单支付总金额 + 运费(是否发货) - 此订单之前已经退款金额
+		 *
+		 * 进行用户的余额增加操作,订单中的积分,经验的减少操作
+		 */
+		if($orderStatus == 6)
+		{
+			Order_class::resetOrderProp($order_id);
+
+			//促销活动订单
+			if($orderRow['type'] != 0)
+			{
+				Active::refundCallback($orderRow['order_no'],$orderRow['type']);
+			}
+
+			$reduceExp   = $orderRow['exp'];
+			$reducePoint = $orderRow['point'];
+		}
+
+		//更新退款表
+		$updateData = array(
+			'amount'       => $amount,
+			'pay_status'   => 2,
+			'dispose_time' => ITime::getDateTime(),
+			'way'          => $way,
+		);
+		$refundDB->setData($updateData);
+		$refundResult = $refundDB->update('id = '.$refundId);
+		if(!$refundResult)
+		{
+			$refundDB->rollback();
+			return '退款表更新失败';
+		}
+
+		//非游客订单退款
+		if($user_id)
+		{
+			//更新用户的经验值
+			plugin::trigger('expUpdate',$user_id,-$reduceExp);
+
+			//积分记录日志
+			$pointConfig = array(
+				'user_id' => $user_id,
+				'point'   => '-'.$reducePoint,
+				'log'     => '退款订单号:'.$orderRow['order_no'].'中的商品,减掉积分 -'.$reducePoint,
+			);
+			$pointObj = new Point();
+			$pointObj->update($pointConfig);
+		}
+
+		//生成订单日志
+		if($type == 'admin')
+		{
+			$adminObj  = new IModel('admin');
+			$adminRow  = $adminObj->getObj('id = '.$authorId);
+			$authorName= $adminRow['admin_name'];
+		}
+		else if($type == 'seller')
+		{
+			$sellerObj = new IModel('seller');
+			$sellerRow = $sellerObj->getObj('id = '.$authorId);
+			$authorName= $sellerRow['seller_name'];
+		}
+		$tb_order_log = new IModel('order_log');
+		$tb_order_log->setData(array(
+			'order_id' => $order_id,
+			'user'     => $authorName,
+			'action'   => '退款',
+			'result'   => '成功',
+			'note'     => '订单【'.$order_no.'】退款,退款金额:¥'.$amount,
+			'addtime'  => ITime::getDateTime(),
+		));
+		$refundLogResult = $tb_order_log->add();
+
+		//发送退款成功的事件
+		plugin::trigger("refundFinish",$refundId);
+		return $refundLogResult;
+	}
+
+	/**
+	 * @brief 检查订单是否重复
+	 * @param array $checkData 检查的订单数据
+	 * @param array $goodsList 购买的商品数据信息
+	 */
+	public static function checkRepeat($checkData,$goodsList)
+	{
+    	$checkWhere = array();
+    	foreach($checkData as $key => $val)
+    	{
+    		if(!$val)
+    		{
+				return "请完整填写收件人信息";
+    		}
+    		$checkWhere[] = "`".$key."` = '".$val."'";
+    	}
+    	$checkWhere[] = " NOW() < date_add(create_time,INTERVAL 2 MINUTE) "; //在有限时间段内生成的订单
+    	$checkWhere[] = " pay_status != 1 ";//是否付款
+		$where = join(" and ",$checkWhere);
+
+		//查询订单数据库
+		$orderObj  = new IModel('order');
+    	$orderList = $orderObj->query($where);
+
+    	//有重复下单的嫌疑
+    	if($orderList)
+    	{
+    		//当前购买的
+    		$nowBuy = "";
+    		foreach($goodsList as $key => $val)
+    		{
+    			$nowBuy .= $val['goods_id']."@".$val['product_id'];
+    		}
+
+			//已经购买的
+			$orderGoodsDB = new IModel('order_goods');
+			foreach($orderList as $key => $val)
+			{
+	    		$isBuyed = "";
+	    		$orderGoodsList = $orderGoodsDB->query("order_id = ".$val['id']);
+	    		foreach($orderGoodsList as $k => $item)
+	    		{
+	    			$isBuyed .= $item['goods_id']."@".$item['product_id'];
+	    		}
+
+	    		if($nowBuy == $isBuyed)
+	    		{
+					return "您所提交的订单重复,频率太高,请稍候再试...";
+	    		}
+			}
+    	}
+    	return true;
+	}
+
+	/**
+	 * @brief  设置批量子订单
+	 * @param  array $orderKey   批量订单KEY
+	 * @param  array $orderArray 订单号数组
+	 * @return boolean
+	 */
+	public static function setBatch($orderKey,$orderArray)
+	{
+		$cacheObj = new ICache('file');
+		return $cacheObj->set($orderKey,$orderArray);
+	}
+
+	/**
+	 * @brief  获取批量子订单
+	 * @param  array $orderKey 批量订单KEY
+	 * @return array 订单号数组array('订单号' => '金额')
+	 */
+	public static function getBatch($orderKey)
+	{
+		$result   = array();//订单号=>订单金额
+
+		$cacheObj = new ICache('file');
+		$orderList= $cacheObj->get($orderKey);
+		if($orderList)
+		{
+			$orderDB = new IModel('order');
+			foreach($orderList as $key => $val)
+			{
+				$orderRow = $orderDB->getObj('order_no = "'.$val.'"');
+				if($orderRow)
+				{
+					$result[$val] = $orderRow['order_amount'];
+				}
+			}
+		}
+		return $result;
+	}
+
+	/**
+	 * @brief 获取退款方式文字
+	 * @param string $code 编码
+	 */
+	public static function refundWay($code)
+	{
+		$result = array('balance' => '余额退款','other' => '其他方式','origin' => '原路退款');
+		return isset($result[$code]) ? $result[$code] : "未知";
+	}
+}

+ 322 - 0
src/classes/payment.php

@@ -0,0 +1,322 @@
+<?php
+/**
+ * @copyright Copyright(c) 2011 aircheng.com
+ * @file payment.php
+ * @brief 支付方式 操作类
+ * @author kane
+ * @date 2011-01-20
+ * @version 0.6
+ * @note
+ */
+
+/**
+ * @class Payment
+ * @brief 支付方式 操作类
+ */
+//支付状态:支付失败
+define ( "PAY_FAILED", - 1);
+//支付状态:支付超时
+define ( "PAY_TIMEOUT", 0);
+//支付状态:支付成功
+define ( "PAY_SUCCESS", 1);
+//支付状态:支付取消
+define ( "PAY_CANCEL", 2);
+//支付状态:支付错误
+define ( "PAY_ERROR", 3);
+//支付状态:支付进行
+define ( "PAY_PROGRESS", 4);
+//支付状态:支付无效
+define ( "PAY_INVALID", 5);
+
+class Payment
+{
+	/**
+	 * @brief 创建支付类实例
+	 * @param $payment_id int 支付方式ID
+	 * @return 返回支付插件类对象
+	 */
+	public static function createPaymentInstance($payment_id)
+	{
+		$paymentRow = self::getPaymentById($payment_id);
+
+		if($paymentRow && isset($paymentRow['class_name']) && $paymentRow['class_name'])
+		{
+			$class_name = $paymentRow['class_name'];
+			$classPath  = IWeb::$app->getBasePath().'plugins/payments/pay_'.$class_name.'/'.$class_name.'.php';
+			if(file_exists($classPath))
+			{
+				require_once($classPath);
+				return new $class_name($payment_id);
+			}
+			else
+			{
+				IError::show(403,'支付接口类'.$class_name.'没有找到');
+			}
+		}
+		else
+		{
+			IError::show(403,'支付方式不存在');
+		}
+	}
+
+	/**
+	 * @brief 根据支付方式配置编号  获取该插件的详细配置信息
+	 * @param $payment_id int    支付方式ID
+	 * @param $key        string 字段
+	 * @return 返回支付插件类对象
+	 */
+	public static function getPaymentById($payment_id,$key = '')
+	{
+		$paymentDB  = new IModel('payment');
+		$paymentRow = $paymentDB->getObj('id = '.$payment_id);
+
+		if($key)
+		{
+			return isset($paymentRow[$key]) ? $paymentRow[$key] : '';
+		}
+		return $paymentRow;
+	}
+
+	/**
+	 * @brief 根据支付方式配置编号  获取该插件的配置信息
+	 * @param $payment_id int    支付方式ID
+	 * @param $key        string 字段
+	 * @return 返回支付插件类对象
+	 */
+	public static function getConfigParam($payment_id,$key = '')
+	{
+		$payConfig = self::getPaymentById($payment_id,'config_param');
+		if($payConfig)
+		{
+			$payConfig = JSON::decode($payConfig);
+			return isset($payConfig[$key]) ? $payConfig[$key] : '';
+		}
+		return '';
+	}
+
+	/**
+	 * @brief 获取订单中的支付信息 M:必要信息; R表示店铺; P表示用户;
+	 * @param $payment_id int    支付方式ID
+	 * @param $type       string 信息获取方式 order:订单支付;recharge:在线充值;
+	 * @param $argument   mix    参数
+	 * @return array 支付提交信息
+	 */
+	public static function getPaymentInfo($payment_id,$type,$argument)
+	{
+		//最终返回值
+		$payment = array();
+
+		//初始化配置参数
+		$paymentInstance = Payment::createPaymentInstance($payment_id);
+		$configParam = $paymentInstance->configParam();
+		foreach($configParam as $key => $val)
+		{
+			$payment[$key] = '';
+		}
+
+		//获取公共信息
+		$paymentRow = self::getPaymentById($payment_id,'config_param');
+		if($paymentRow)
+		{
+			$paymentRow = JSON::decode($paymentRow);
+			foreach($paymentRow as $key => $item)
+			{
+				$payment[$key] = $item;
+			}
+		}
+
+		if($type == 'order')
+		{
+			$orderIdArray = $argument;
+			$M_Amount     = 0;
+			$M_OrderNO    = array();
+			foreach($orderIdArray as $key => $order_id)
+			{
+				//获取订单信息
+				$orderObj = new IModel('order');
+				$orderRow = $orderObj->getObj('id = '.$order_id.' and status = 1');
+				if(empty($orderRow))
+				{
+					IError::show(403,'订单状态不正确,请到用户中心的订单列表查看');
+				}
+
+				//判断商品库存
+				$orderGoodsDB   = new IModel('order_goods');
+				$orderGoodsList = $orderGoodsDB->query('order_id = '.$order_id);
+				foreach($orderGoodsList as $key => $val)
+				{
+					if(!goods_class::checkStore($val['goods_nums'],$val['goods_id'],$val['product_id']))
+					{
+						IError::show(403,'商品库存不足无法支付,请重新下单');
+					}
+				}
+
+				//如果是活动订单检查其条件
+				if($orderRow['type'] > 0 && $promo = array_search($orderRow['type'],Active::$typeToIdMapping))
+				{
+					$ac_type    = $val['product_id'] > 0 ? "product"          : "goods";
+					$ac_id      = $val['product_id'] > 0 ? $val['product_id'] : $val['goods_id'];
+					$ac_buy_num = $val['goods_nums'];
+
+			    	$activeObject = new Active($promo,$orderRow['active_id'],$orderRow['user_id'],$ac_id,$ac_type,$ac_buy_num);
+			    	$activeResult = $activeObject->checkValid($orderRow['id']);
+			    	if($activeResult && is_string($activeResult))
+			    	{
+			    		IError::show(403,$activeResult);
+			    	}
+				}
+
+				$M_Amount   += $orderRow['order_amount'];
+				$M_OrderNO[] = $orderRow['order_no'];
+			}
+
+			$payment['M_Remark']    = $orderRow['postscript'];
+			$payment['M_OrderId']   = $orderRow['id'];
+			$payment['M_OrderNO']   = $orderRow['order_no'];
+			$payment['M_Amount']    = $M_Amount;
+			$payment['M_BatchOrderNO'] = join("_",$M_OrderNO);
+
+			//用户信息
+			$payment['P_Mobile']    = $orderRow['mobile'];
+			$payment['P_Name']      = $orderRow['accept_name'];
+			$payment['P_PostCode']  = $orderRow['postcode'];
+			$payment['P_Telephone'] = $orderRow['telphone'];
+			$payment['P_Address']   = $orderRow['address'];
+
+			//订单批量结算缓存机制
+			Order_Class::setBatch($payment['M_OrderNO'],$M_OrderNO);
+		}
+		else if($type == 'recharge')
+		{
+			if(IWeb::$app->getController()->user['user_id'] == null)
+			{
+				IError::show(403,'请登录系统');
+			}
+
+			if(!isset($argument['account']) || $argument['account'] <= 0)
+			{
+				IError::show(403,'请填入正确的充值金额');
+			}
+
+			$rechargeObj = new IModel('online_recharge');
+			$reData      = array(
+				'user_id'     => IWeb::$app->getController()->user['user_id'],
+				'recharge_no' => Order_Class::createOrderNum(),
+				'account'     => $argument['account'],
+				'time'        => ITime::getDateTime(),
+				'payment_name'=> $argument['paymentName'],
+			);
+			$rechargeObj->setData($reData);
+			$r_id = $rechargeObj->add();
+
+			//充值时用户id跟随交易号一起发送
+			$payment['M_OrderNO'] = 'recharge'.$reData['recharge_no'];
+			$payment['M_OrderId'] = $r_id;
+			$payment['M_Amount']  = $reData['account'];
+		}
+
+		$siteConfigObj = new Config("site_config");
+		$site_config   = $siteConfigObj->getInfo();
+
+		//交易信息
+		$payment['M_Time']      = time();
+		$payment['M_Paymentid'] = $payment_id;
+
+		//店铺信息
+		$payment['R_Address']   = isset($site_config['address']) ? $site_config['address'] : '';
+		$payment['R_Name']      = isset($site_config['name'])    ? $site_config['name']    : '';
+		$payment['R_Mobile']    = isset($site_config['mobile'])  ? $site_config['mobile']  : '';
+		$payment['R_Telephone'] = isset($site_config['phone'])   ? $site_config['phone']   : '';
+
+		return $payment;
+	}
+
+	//更新在线充值
+	public static function updateRecharge($recharge_no)
+	{
+		$rechargeObj = new IModel('online_recharge');
+		$rechargeRow = $rechargeObj->getObj('recharge_no = "'.$recharge_no.'"');
+		if(empty($rechargeRow))
+		{
+			return false;
+		}
+
+		if($rechargeRow['status'] == 1)
+		{
+			return true;
+		}
+
+		$dataArray = array(
+			'status' => 1
+		);
+
+		$rechargeObj->setData($dataArray);
+		$result = $rechargeObj->update('recharge_no = "'.$recharge_no.'"');
+
+		if($result == '')
+		{
+			return false;
+		}
+
+		$money    = $rechargeRow['account'];
+		$user_id  = $rechargeRow['user_id'];
+		$pay_name = $rechargeRow['payment_name'];
+		$userObj  = new IModel('user');
+		$userRow  = $userObj->getObj('id = '.$user_id);
+		$username = $userRow['username'];
+
+		$log = new AccountLog();
+		$config=array(
+			'user_id'  => $user_id,
+			'event'    => 'recharge',
+			'note'     => '用户['.$username.']通过 '.$pay_name.' 在线充值',
+			'num'      => $money,
+		);
+		return $log->write($config);
+	}
+
+	/**
+	 * @brief 搜集退款信息
+	 * @param int   $payment_id 支付方式ID
+	 * @param array $orderRow   订单数据
+	 * @param array $refundRow  退款单数据
+	 * @return array
+	 */
+	public static function getRefundInfo($payment_id,$orderRow,$refundsRow)
+	{
+        //最终返回值
+        $payment = array();
+
+        //初始化配置参数
+        $paymentInstance = Payment::createPaymentInstance($payment_id);
+        $configParam = $paymentInstance->configParam();
+        foreach($configParam as $key => $val)
+        {
+            $payment[$key] = '';
+        }
+
+        //获取公共信息
+        $paymentRow = self::getPaymentById($payment_id,'config_param');
+        if($paymentRow)
+        {
+            $paymentRow = JSON::decode($paymentRow);
+            foreach($paymentRow as $key => $item)
+            {
+                $payment[$key] = $item;
+            }
+        }
+
+        $payment['M_RefundId']      = $refundsRow['id'];
+        $payment['M_Refundfee']     = $refundsRow['amount'];
+        $payment['M_RefundNo']      = $orderRow['order_no']."M".$refundsRow['id'];
+        $payment['M_OrderNO']       = $orderRow['order_no'];
+        $payment['M_Amount']        = $orderRow['order_amount'];
+        $payment['M_TransactionId'] = $orderRow['trade_no'];
+
+        //交易信息
+        $payment['M_Time']      = time();
+        $payment['M_Paymentid'] = $payment_id;
+
+        return $payment;
+	}
+}

+ 156 - 0
src/classes/paymentplugin.php

@@ -0,0 +1,156 @@
+<?php
+/**
+ * @copyright Copyright(c) 2011 aircheng.com
+ * @file paymentplugin.php
+ * @brief 支付插件基类
+ * @author chendeshan
+ * @date 2013/5/7 20:07:59
+ * @version 1.0.0
+ */
+
+ /**
+ * @class PaymentPlugin
+ * @brief 支付插件抽象类
+ */
+abstract class paymentPlugin
+{
+	public $method              = "post";//表单提交模式
+	public $name                = null;  //支付插件名称
+	public $version             = 1.0;   //版本
+	public $callbackUrl         = '';    //支付完成后,同步回调地址
+	public $serverCallbackUrl   = '';    //支付完成后,异步通知地址
+	public $merchantCallbackUrl = '';	 //支付中断返回
+	public $refundCallbackUrl   = '';    //退款完成后,回调通知地址
+
+	/**
+	* @brief 构造函数
+	* @param $payment_id 支付方式ID
+	*/
+	public function __construct($payment_id)
+	{
+		//回调函数地址
+		$this->callbackUrl         = IUrl::getHost().IUrl::creatUrl("/block/callback/_id/".$payment_id);
+		//回调业务处理地址
+		$this->serverCallbackUrl   = IUrl::getHost().IUrl::creatUrl("/block/server_callback/_id/".$payment_id);
+		//中断支付返回
+		$this->merchantCallbackUrl = IUrl::getHost().IUrl::creatUrl("/block/merchant_callback/_id/".$payment_id);
+		//退款成功后的回调地址
+		$this->refundCallbackUrl   = IUrl::getHost().IUrl::creatUrl("/block/refund_callback/_id/".$payment_id);
+	}
+
+	/**
+	 * @brief 记录支付平台的付款交易号
+	 * @param $orderNo string 订单编号
+	 * @param $tradeNo string 交易流水号
+	 * @return boolean
+	 */
+	protected function recordTradeNo($orderNo,$tradeNo)
+	{
+		$orderDB   = new IModel('order');
+		$moreOrder = Order_Class::getBatch($orderNo);
+		if($moreOrder)
+		{
+			foreach($moreOrder as $key => $val)
+			{
+				$orderDB->setData(array('trade_no' => $tradeNo));
+				$orderDB->update('order_no = "'.$key.'"');
+			}
+		}
+	}
+
+	/**
+	 * @brief 记录支付平台的退款交易号
+	 * @param $refund_id int 商城退款单ID
+	 * @param $tradeNo string 交易流水号
+	 * @return boolean
+	 */
+	protected function recordRefundTradeNo($refund_id,$tradeNo)
+	{
+        $refundment_docDB = new IModel('refundment_doc');
+        $refundment_docDB->setData(array('trade_no' => $tradeNo));
+        return $refundment_docDB->update('id ='.$refund_id);
+	}
+
+	/**
+	 * @brief 开始支付
+	 */
+	public function doPay($sendData)
+	{
+		$backUrl = IUrl::creatUrl('/ucenter/index');
+echo <<< OEF
+		<!DOCTYPE html>
+		<html lang="zh-CN">
+			<head></head>
+			<body>
+				<p>please wait...</p>
+				<form action="{$this->getSubmitUrl()}" method="{$this->method}">
+OEF;
+					foreach($sendData as $key => $item)
+					{
+echo <<< OEF
+					<input type='hidden' name='{$key}' value='{$item}' />
+OEF;
+					}
+echo <<< OEF
+				</form>
+			</body>
+			<script type='text/javascript'>
+				if(history.replaceState)
+				{
+					history.replaceState(null, null, "{$backUrl}");
+				}
+				window.document.forms[0].submit();
+			</script>
+		</html>
+OEF;
+	}
+
+	/**
+	 * @brief 返回配置参数
+	 */
+	public function configParam()
+	{
+		return array(
+			'M_PartnerId'  => '商户ID号',
+			'M_PartnerKey' => '商户KEY密钥',
+		);
+	}
+
+	/**
+	 * 异步通知停止
+	 */
+	abstract public function notifyStop();
+
+	/**
+	 * 获取提交地址
+	 * @return string Url提交地址
+	 */
+	abstract public function getSubmitUrl();
+
+	/**
+	 * 获取要发送的数据数组结构
+	 * @param $payment array 要传递的支付信息
+	 * @return array
+	 */
+	abstract public function getSendData($paymentInfo);
+
+	/**
+	 * 同步支付回调
+	 * @param $ExternalData array  支付接口回传的数据
+	 * @param $paymentId    int    支付接口ID
+	 * @param $money        float  交易金额
+	 * @param $message      string 信息
+	 * @param $orderNo      string 订单号
+	 */
+	abstract public function callback($ExternalData,&$paymentId,&$money,&$message,&$orderNo);
+
+	/**
+	 * 同步支付回调
+	 * @param $ExternalData array  支付接口回传的数据
+	 * @param $paymentId    int    支付接口ID
+	 * @param $money        float  交易金额
+	 * @param $message      string 信息
+	 * @param $orderNo      string 订单号
+	 */
+	abstract public function serverCallback($ExternalData,&$paymentId,&$money,&$message,&$orderNo);
+}

+ 283 - 0
src/classes/photoupload.php

@@ -0,0 +1,283 @@
+<?php
+/**
+ * @copyright (c) 2011 aircheng.com
+ * @file photoupload.php
+ * @brief 图片上传防止重复类
+ * @author chendeshan
+ * @date 2010-12-16
+ * @version 0.6
+ */
+
+/**
+ * @class PhotoUpload
+ * @brief 图片上传防止重复类
+ */
+class PhotoUpload
+{
+	private $dir         = 'upload'; //图片存储的目录名称
+	private $iterance    = true;     //防止图片重复提交开关
+	private $thumbWidth  = array();  //缩略图宽度
+	private $thumbHeight = array();  //缩略图高度
+	private $thumbKey    = array();  //缩略图返回键名
+
+	//构造函数
+	function __construct($dir = '')
+	{
+		//设置默认路径地址
+		if($dir == '')
+		{
+			$dir = $this->hashDir();
+		}
+
+		$this->setDir($dir);
+	}
+
+	/**
+	 * @brief 获取图片散列目录
+	 * @return string
+	 */
+	public function hashDir()
+	{
+		$dir  = isset(IWeb::$app->config['upload']) ? IWeb::$app->config['upload'] : $this->dir;
+		$dir .= '/'.date('Y/m/d');
+		return $dir;
+	}
+
+	/**
+	 * @brief 防止图片重复提交
+	 * @param bool $bool true:开启;false:关闭
+	 */
+	public function setIterance($bool)
+	{
+		$this->iterance = $bool;
+	}
+
+	/**
+	 * @brief 设置上传的目录
+	 * @param string $dir
+	 */
+	public function setDir($dir)
+	{
+		$this->dir = $dir;
+	}
+
+	/**
+	 * @brief 设置缩略图宽度和高度
+	 * @param int    $width  生成缩略图宽度;
+	 * @param int    $height 生成缩略图高度;
+	 * @param string $key    返回缩略图键名;
+	 */
+	public function setThumb($width,$height,$key = 'thumb')
+	{
+		$this->thumbWidth[]  = intval($width);
+		$this->thumbHeight[] = intval($height);
+
+		if(in_array($key,$this->thumbKey))
+		{
+			$thumbCount = count($this->thumbKey) + 1;
+			$key = $key.$thumbCount;
+		}
+
+		$this->thumbKey[] = $key;
+	}
+
+	//防止图片文件重复提交机制
+	private function checkIterance($file,$photoObj)
+	{
+		//如果关闭了图片重复提交机制
+		if($this->iterance == false)
+			return null;
+
+		$fileMD5  = null;    //上传图片的md5值(默认)
+		$photoRow = array(); //图库里照片信息(默认)
+		$result   = array(); //结果
+
+		if(is_file($file))
+		{
+			//生成文件md5码
+			$fileMD5 = md5_file($file);
+		}
+
+		if($fileMD5 != null)
+		{
+    		//根据md5值取得图像数据
+    		$where = "id = '".$fileMD5."'";
+    		$photoRow = $photoObj->getObj($where);
+		}
+
+		//设置了缩略图
+		if(isset($photoRow['img']))
+		{
+			if(is_file($photoRow['img']))
+			{
+				$result['img'] = $photoRow['img'];
+				$result['flag']= 1;
+
+				if($this->thumbWidth && $this->thumbHeight && $this->thumbKey)
+				{
+					foreach($this->thumbWidth as $thumbWidth_Key => $thumbWidth_Val)
+					{
+						//获取此宽度和高度应有的缩略图名
+				        $fileExt       = IFile::getFileSuffix($photoRow['img']);
+				        $thumbFileName = str_replace('.'.$fileExt,'_'.$this->thumbWidth[$thumbWidth_Key].'_'.$this->thumbHeight[$thumbWidth_Key].'.'.$fileExt,$photoRow['img']);
+
+						if(is_file($thumbFileName))
+						{
+							$result['thumb'][$this->thumbKey[$thumbWidth_Key]] = $thumbFileName;
+							unset($this->thumbKey[$thumbWidth_Key]);
+						}
+					}
+
+					//重新生成系统中不存在的此宽高的缩略图
+					foreach($this->thumbKey as $thumbKey_key => $thumbKey_val)
+					{
+						$thumbExtName = '_'.$this->thumbWidth[$thumbKey_key].'_'.$this->thumbHeight[$thumbKey_key];
+						$thumbName    = $this->thumb($photoRow['img'],$this->thumbWidth[$thumbKey_key],$this->thumbHeight[$thumbKey_key],$thumbExtName);
+						$result['thumb'][$this->thumbKey[$thumbKey_key]] = $thumbName;
+					}
+				}
+				return $result;
+			}
+			else
+			{
+				$photoObj->del('id = "'.$photoRow['id'].'"');
+				return null;
+			}
+		}
+		else
+		{
+			return null;
+		}
+	}
+
+	/**
+	 * @brief 图片信息入库
+	 * @param array $insertData 要插入数据
+	 		  object $photoObj  图库对象
+	 */
+	private function insert($insertData,$photoObj)
+	{
+		if($this->iterance == true && !$photoObj->getObj('id = "'.$insertData['id'].'"'))
+		{
+			$photoObj->setData($insertData);
+			$photoObj->add();
+		}
+	}
+
+	/**
+	 * @brief 生成$fileName文件的缩略图,位置与$fileName相同
+	 * @param string  $fileName 要生成缩略图的目标文件
+	 * @param int     $width    缩略图宽度
+	 * @param int     $height   缩略图高度
+	 * @param string  $extName  缩略图文件名附加值
+	 * @param string  $saveDir  缩略图存储目录
+	 */
+	public static function thumb($fileName,$width,$height,$extName = '_thumb',$saveDir = '')
+	{
+		return Thumb::get($fileName,$width,$height);
+	}
+
+	/**
+	 * @brief 执行图片上传
+	 * @param boolean $isForge 是否伪造数据提交
+	 * @return array key:控件名; val:图片路径名;
+	 */
+	public function run($isForge = false)
+	{
+		//创建图片模型对象
+		$photoObj = new IModel('goods_photo');
+
+		//已经存在的图片文件数据
+		$photoArray = array();
+
+		//过滤图库中已经存在的图片
+		foreach($_FILES as $key => $val)
+		{
+			//上传的所有临时文件
+			$tmpFile = isset($_FILES[$key]['tmp_name']) ? $_FILES[$key]['tmp_name'] : null;
+
+			//没有找到匹配的控件
+			if($tmpFile == null)
+				continue;
+
+			if(is_array($tmpFile))
+			{
+				foreach($tmpFile as $tmpKey => $tmpVal)
+				{
+					$result = $this->checkIterance($tmpVal,$photoObj);
+					if($result != null)
+					{
+						$photoArray[$key][$tmpKey] = $result;
+						unset($_FILES[$key]['name'][$tmpKey]);
+						unset($_FILES[$key]['tmp_name'][$tmpKey]);
+					}
+				}
+			}
+			else
+			{
+				$result = $this->checkIterance($tmpFile,$photoObj);
+				if($result!=null)
+				{
+					$photoArray[$key] = $result;
+					unset($_FILES[$key]);
+				}
+			}
+		}
+
+		//图片上传
+		$upObj = new IUpload();
+		$upObj->isForge = $isForge;
+		$upObj->setDir($this->dir);
+		$upState = $upObj->execute();
+
+		//检查上传状态
+		foreach($upState as $key => $rs)
+		{
+			if(count($_FILES[$key]['name']) > 1)
+				$isArray = true;
+			else
+				$isArray = false;
+
+			foreach($rs as $innerKey => $val)
+			{
+				if($val['flag']==1)
+				{
+					//上传成功后图片信息
+					$fileName = $val['dir'].$val['name'];
+					$fileMD5  = md5_file($fileName);
+
+					$rs[$innerKey]['img'] = $fileName;
+
+					$insertData = array(
+						'id'  => $fileMD5,
+						'img' => $fileName
+					);
+
+					//将图片信息入库
+					$this->insert($insertData,$photoObj);
+
+					if($this->thumbWidth && $this->thumbHeight && $this->thumbKey)
+					{
+						//重新生成系统中不存在的此宽高的缩略图
+						foreach($this->thumbKey as $thumbKey_key => $thumbKey_val)
+						{
+							$thumbExtName = '_'.$this->thumbWidth[$thumbKey_key].'_'.$this->thumbHeight[$thumbKey_key];
+							$thumbName    = $this->thumb($fileName,$this->thumbWidth[$thumbKey_key],$this->thumbHeight[$thumbKey_key],$thumbExtName);
+							$rs[$innerKey]['thumb'][$this->thumbKey[$thumbKey_key]] = $thumbName;
+						}
+					}
+				}
+
+				if($isArray == true)
+				{
+					$photoArray[$key] = $rs;
+				}
+				else
+				{
+					$photoArray[$key] = $rs[0];
+				}
+			}
+		}
+		return $photoArray;
+	}
+}

+ 412 - 0
src/classes/plugin.php

@@ -0,0 +1,412 @@
+<?php
+/**
+ * @copyright Copyright(c) 2016 aircheng.com
+ * @file plugin.php
+ * @brief 插件核心类
+ * @note 观察者模式,注册事件,触发事件
+ * @author nswe
+ * @date 2016/2/28 10:57:26
+ * @version 4.4
+ */
+class plugin extends IInterceptorBase
+{
+	//默认开启的插件列表
+	private static $defaultList = array("_verification","_goodsCategoryWidget","_authorization","_userInfo","_initData");
+
+	//已经注册监听
+	private static $_listen = array();
+
+	//加载插件
+	public static function init()
+	{
+		$pluginList = array();
+
+		//加载默认插件
+		foreach(self::$defaultList as $val)
+		{
+			$pluginList[]= array('class_name' => $val);
+		}
+
+		//查询自定义插件
+		$pluginDB     = new IModel('plugin');
+		$customPlugin = $pluginDB->query("is_open = 1","class_name","sort asc");
+		$pluginList   = array_merge($pluginList,$customPlugin);
+		foreach($pluginList as $key => $val)
+		{
+			$className = $val['class_name'];
+			$classFile = self::path().$className."/".$className.".php";
+			if(is_file($classFile))
+			{
+				include_once($classFile);
+				$pluginObj = new $className();
+				$pluginObj->reg();
+			}
+		}
+		unset($pluginList);
+	}
+
+	/**
+	 * @brief 注册事件
+	 * @param string $event 事件
+	 * @param object ro function $classObj 类实例 或者 匿名函数
+	 * @param string $method 方法名字
+	 */
+	public static function reg($param,$classObj,$method = "")
+	{
+		$eventArray = explode(',',$param);
+		foreach($eventArray as $event)
+		{
+			if(!isset(self::$_listen[$event]))
+			{
+				self::$_listen[$event] = array();
+			}
+			self::$_listen[$event][] = array($classObj,$method);
+		}
+	}
+
+	/**
+	 * @brief 显示已注册事件
+	 * @param string $event 事件名称
+	 * @return array
+	 */
+	public static function get($event = '')
+	{
+		if($event)
+		{
+			if( isset(self::$_listen[$event]) )
+			{
+				return self::$_listen[$event];
+			}
+			return null;
+		}
+		return self::$_listen;
+	}
+
+	/**
+	 * @brief 触发事件支持多个参数
+	 * @param string $event 事件
+	 * @notice 可以调用匿名函数和方法
+	 */
+	public static function trigger($event)
+	{
+		$params = func_get_args();
+		array_shift($params);
+
+		$result = array();
+		if(isset(self::$_listen[$event]))
+		{
+			foreach(self::$_listen[$event] as $key => $val)
+			{
+				if(stripos($event,"on") === 0)
+				{
+					unset(self::$_listen[$event][$key]);
+				}
+
+				list($pluginObj,$pluginMethod) = $val;
+				$result[$key] = is_callable($pluginObj) ? call_user_func_array($pluginObj,$params):call_user_func_array(array($pluginObj,$pluginMethod),$params);
+			}
+		}
+		return isset($result[1]) ? $result : current($result);
+	}
+
+	/**
+	 * @brief 插件物理路径
+	 * @return string 路径字符串
+	 */
+	public static function path()
+	{
+		return IWeb::$app->getBasePath()."plugins/";
+	}
+
+	/**
+	 * @brief 插件WEB路径
+	 * @return string 路径字符串
+	 */
+	public static function webPath()
+	{
+		return IUrl::creatUrl('')."plugins/";
+	}
+
+	/**
+	 * @brief 获取全部插件
+	 * @param string $name 插件名字,如果为空则获取全部插件信息
+	 * @return array 插件信息 array(
+		"name"        => 插件名字,
+		"description" => 插件描述,
+		"explain"     => 使用说明,
+		"class_name"  => 插件ID,
+		"is_open"     => 是否开启,
+		"is_install"  => 是否安装,
+		"config_name" => 默认插件参数结构,
+		"config_param"=> 已经保存的插件参数,
+		"sort"        => 排序,
+	 )
+	 */
+	public static function getItems($name = '')
+	{
+		$result = array();
+		$dirRes = opendir(self::path());
+
+		//遍历目录读取配置文件
+		$pluginDB = new IModel('plugin');
+		while( false !== ($dir = readdir($dirRes)) )
+		{
+			if($dir[0] == "." || $dir[0] == "_")
+			{
+				continue;
+			}
+
+			if($name && $result)
+			{
+				break;
+			}
+
+			if($name && $dir != $name)
+			{
+				continue;
+			}
+
+			$pluginIndex = self::path().$dir."/".$dir.".php";
+			if(is_file($pluginIndex))
+			{
+				include_once($pluginIndex);
+				if(get_parent_class($dir) == "pluginBase")
+				{
+					$class_name   = $dir;
+					$pluginRow    = $pluginDB->getObj('class_name = "'.$class_name.'"');
+					$is_open      = $pluginRow ? $pluginRow['is_open'] : 0;
+					$is_install   = $pluginRow ? 1                     : 0;
+					$sort         = $pluginRow ? $pluginRow['sort']    : 99;
+					$config_param = array();
+					if($pluginRow && $pluginRow['config_param'])
+					{
+						$config_param = JSON::decode($pluginRow['config_param']);
+					}
+					$result[$dir] = array(
+						"name"        => $class_name::name(),
+						"description" => $class_name::description(),
+						"explain"     => $class_name::explain(),
+						"class_name"  => $class_name,
+						"is_open"     => $is_open,
+						"is_install"  => $is_install,
+						"config_name" => $class_name::configName(),
+						"config_param"=> $config_param,
+						"sort"        => $sort,
+					);
+				}
+			}
+		}
+
+		if(!$name)
+		{
+			return $result;
+		}
+		return isset($result[$name]) ? $result[$name] : array();
+	}
+
+	/**
+	 * @brief 系统内置的所有事件触发
+	 */
+	public static function onCreateApp(){plugin::init();plugin::trigger("onCreateApp");}
+	public static function onFinishApp(){plugin::trigger("onFinishApp");}
+
+	public static function onBeforeCreateController($ctrlId){plugin::trigger("onBeforeCreateController",$ctrlId);plugin::trigger("onBeforeCreateController@".$ctrlId);}
+	public static function onCreateController($ctrlObj){plugin::trigger("onCreateController");plugin::trigger("onCreateController@".$ctrlObj->getId());}
+	public static function onFinishController($ctrlObj){plugin::trigger("onFinishController");plugin::trigger("onFinishController@".$ctrlObj->getId());}
+
+	public static function onBeforeCreateAction($ctrlObj,$actionId){plugin::trigger("onBeforeCreateAction",$actionId);plugin::trigger("onBeforeCreateAction@".$ctrlObj->getId());plugin::trigger("onBeforeCreateAction@".$ctrlObj->getId()."@".$actionId);}
+	public static function onCreateAction($ctrlObj,$actionObj){plugin::trigger("onCreateAction");plugin::trigger("onCreateAction@".$ctrlObj->getId());plugin::trigger("onCreateAction@".$ctrlObj->getId()."@".$actionObj->getId());}
+	public static function onFinishAction($ctrlObj,$actionObj){plugin::trigger("onFinishAction");plugin::trigger("onFinishAction@".$ctrlObj->getId());plugin::trigger("onFinishAction@".$ctrlObj->getId()."@".$actionObj->getId());}
+
+	public static function onCreateView($ctrlObj,$actionObj){plugin::trigger("onCreateView");plugin::trigger("onCreateView@".$ctrlObj->getId());plugin::trigger("onCreateView@".$ctrlObj->getId()."@".$actionObj->getId());}
+	public static function onFinishView($ctrlObj,$actionObj){plugin::trigger("onFinishView");plugin::trigger("onFinishView@".$ctrlObj->getId());plugin::trigger("onFinishView@".$ctrlObj->getId()."@".$actionObj->getId());}
+
+	public static function onPhpShutDown(){plugin::trigger("onPhpShutDown");}
+}
+
+/**
+ * @brief 插件基类,所有插件必须继承此类
+ * @notice 必须实现3个抽象方法: reg(),name(),description()
+ */
+abstract class pluginBase extends IInterceptorBase
+{
+	//插件的WEB目录
+	public $webPath = "";
+
+	//插件的物理路径
+	public $path = "";
+
+	//错误信息
+	protected $error = array();
+
+	//注册事件接口,内部通过调用payment::reg(事件,对象实例,方法);
+	public function reg(){}
+
+	/**
+	 * @brief 默认插件参数信息,写入到plugin表config_param字段
+	 * @return array("字段名" => array(
+		 "name"    => "文字显示",
+		 "type"    => "数据类型【text,radio,checkbox,select】",
+		 "pattern" => "数据校验【int,float,date,datetime,required,正则表达式】",
+		 "value"   => "1,数组:枚举数据【radio,checkbox,select】的预设值,array(名字=>数据); 2,字符串:【text】默认数据",
+		 "info"    => "解释说明信息"
+		))
+	 */
+	public static function configName()
+	{
+		return array();
+	}
+
+	/**
+	 * @brief 插件安装
+	 * @return boolean
+	 */
+	public static function install()
+	{
+		return true;
+	}
+
+	/**
+	 * @brief 插件卸载
+	 * @return boolean
+	 */
+	public static function uninstall()
+	{
+		return true;
+	}
+
+	/**
+	 * @brief 插件名字
+	 * @return string
+	 */
+	public static function name()
+	{
+		return "插件名称";
+	}
+
+	/**
+	 * @brief 插件功能描述
+	 * @return string
+	 */
+	public static function description()
+	{
+		return "插件描述";
+	}
+
+	/**
+	 * @brief 插件使用说明
+	 * @return string
+	 */
+	public static function explain()
+	{
+		return "";
+	}
+
+	/**
+	 * @brief 获取DB中录入的配置参数
+	 * @return array
+	 */
+	public function config()
+	{
+		$className= get_class($this);
+		$pluginDB = new IModel('plugin');
+		$dataRow  = $pluginDB->getObj('class_name = "'.$className.'"');
+		if($dataRow && $dataRow['config_param'])
+		{
+			return JSON::decode($dataRow['config_param']);
+		}
+		return array();
+	}
+
+	/**
+	 * @brief 返回错误信息
+	 * @return array
+	 */
+	public function getError()
+	{
+		return $this->error ? join("\r\n",$this->error) : "";
+	}
+
+	/**
+	 * @brief 写入错误信息
+	 * @return array
+	 */
+	public function setError($error)
+	{
+		$this->error[] = $error;
+	}
+
+	/**
+	 * @brief 插件视图渲染有布局
+	 * @param string $view 视图名字
+	 * @param array  $data 视图里面的数据
+	 */
+	public function redirect($view,$data = array())
+	{
+		$__className         = get_class($this);
+		$__pluginViewPath    = plugin::path().$__className."/".$view;
+		$__pluginWebViewPath = plugin::webPath().$__className."/".$view;
+		$__commonVar         = array("_viewPath" => dirname($__pluginViewPath),"_webPath" => dirname($__pluginWebViewPath));
+
+		//根据主题方案生成runtime目录,防止不同主题的插件视图冲突
+		$themeDir         = self::controller()->getThemeDir();
+		$__pluginRuntime  = $themeDir ? plugin::path().$themeDir."/".$__className."/".$view : "";
+
+		if($__pluginRuntime)
+		{
+			$__pluginRuntime = str_replace(IWeb::$app->getBasePath(),IWeb::$app->getRuntimePath(),$__pluginRuntime);
+		}
+		self::controller()->setRenderData($__commonVar);
+		$this->action = new IViewAction(self::controller(),IReq::get('action'));
+		$this->action->run($__pluginViewPath,$data,$__pluginRuntime);
+	}
+
+	/**
+	 * @brief 插件视图渲染去掉布局
+	 * @param string $view 视图名字
+	 * @param array  $data 视图里面的数据
+	 */
+	public function view($view,$data = array())
+	{
+		self::controller()->layout = false;
+		$this->redirect($view,$data);
+	}
+
+	/**
+	 * @brief 插件物理目录
+	 * @param string 插件路径地址
+	 */
+	public function path()
+	{
+		return $this->path ? $this->path : plugin::path().get_class($this)."/";
+	}
+
+	/**
+	 * @brief 插件WEB目录
+	 * @param string 插件路径地址
+	 */
+	public function webPath()
+	{
+		return $this->webPath ? $this->webPath : plugin::webPath().get_class($this)."/";
+	}
+}
+
+/**
+ * @brief iWebShop分词接口
+ */
+interface wordsPart_inter
+{
+	/**
+	 * @brief 运行分词
+	 * @param string $content 要分词的内容
+	 * @return array 词语
+	 */
+	public function run($content);
+
+	/**
+	 * @brief 处理规范统一的结果集
+	 * @param string $result 要处理的返回值
+	 * @return array 返回结果 array('result' => 'success 或者 fail','data' => array('分词数据'))
+	 */
+	public function response($result);
+}

+ 89 - 0
src/classes/point.php

@@ -0,0 +1,89 @@
+<?php
+/**
+ * @copyright (c) 2011 [group]
+ * @file pointlog.php
+ * @brief 积分日志记录处理类
+ * @author chendeshan
+ * @date 2011-6-15 14:58:39
+ * @version 0.6
+ */
+class Point
+{
+	//错误信息
+	private $error  = '';
+
+	/**
+	 * @brief 积分操作的构造函数
+	 * @param array $config => array('user_id' => 用户ID , 'point' => 积分增减(正,负区分) , 'log' => 日志记录内容)
+	 */
+	public function update($config)
+	{
+		if(!isset($config['user_id']) || intval($config['user_id']) <= 0)
+		{
+			$this->error = '用户ID不能为空';
+		}
+		else if(!isset($config['point']) || intval($config['point']) == 0)
+		{
+			$this->error = '积分格式不正确';
+		}
+		else if(!isset($config['log']))
+		{
+			$this->error = '积分日志内容不正确';
+		}
+		else
+		{
+			$is_success = $this->editPoint($config['user_id'],$config['point']);
+			if($is_success)
+			{
+				if(!$this->writeLog($config))
+				{
+					$this->error = '记录日志失败';
+				}
+			}
+			else
+			{
+				$this->error = '积分更新失败';
+			}
+		}
+
+		return $this->error == '' ? true:false;
+	}
+
+	//返回错误信息
+	public function getError()
+	{
+		return $this->error;
+	}
+
+	/**
+	 * @brief 日志记录
+	 * @param array $config => array('user_id' => 用户ID , 'point' => 积分增减(正,负区分) , 'log' => 日志记录内容)
+	 */
+	private function writeLog($config)
+	{
+		//修改pointLog表
+		$poinLogObj    = new IModel('point_log');
+		$pointLogArray = array(
+			'user_id' => $config['user_id'],
+			'datetime'=> ITime::getDateTime(),
+			'value'   => $config['point'],
+			'intro'   => $config['log'],
+		);
+		$poinLogObj->setData($pointLogArray);
+		return $poinLogObj->add();
+	}
+
+	/**
+	 * @brief 积分更新
+	 * @param int $user_id 用户ID
+	 * @param int $point   积分数(正,负)
+	 */
+	private function editPoint($user_id,$point)
+	{
+		$memberObj   = new IModel('member');
+		$memberArray = array('point' => 'point + '.$point);
+		$memberObj->setData($memberArray);
+		return $memberObj->update('user_id = '.$user_id,'point');
+	}
+
+}

+ 400 - 0
src/classes/prorule.php

@@ -0,0 +1,400 @@
+<?php
+/**
+ * @copyright (c) 2011 aircheng.com
+ * @file ProRule.php
+ * @brief 促销规则处理类
+ * @author chendeshan
+ * @date 2011-03-10
+ * @version 0.6
+ */
+
+/**
+ * @class ProRule
+ * @brief 促销活动规则奖励
+          奖励方式分为 (1)现金奖励,(2)赠品奖励。
+          (1)现金奖励就是直接减少订单总额中的金钱数
+          (2)赠品奖励就是订单支持成功后,系统自动发送的赠品
+ */
+class ProRule
+{
+	//商品总金额
+	private $sum;
+
+	//用户组
+	private $user_group = null;
+
+	//现金促销规则奖励仅一次 true:1次;false:多次不限
+	public $isCashOnce = true;
+
+	//赠品促销规则奖励仅一次 true:1次;false:多次不限
+	public $isGiftOnce = false;
+
+	//现金促销规则奖励方式 1减金额 2奖励折扣
+	private $cash_award_type = array(1,2);
+
+	//赠品促销规则奖励方式 3赠送积分 4赠送代金券 5赠送赠品 6免运费 8赠送经验值
+	private $gift_award_type = array(3,4,5,6,8);
+
+	//商家ID
+	private $seller_id = 0;
+
+	/**
+	 * @brief 构造函数 初始化商品金额
+	 * @param float $sum       商品金额
+	 * @param int   $seller_id 商家ID
+	 */
+	public function __construct($sum = 0,$seller_id = 0)
+	{
+		//商品金额必须为数字
+		if(!is_numeric($sum))
+		{
+			IError::show(403,'order sum must a num');
+		}
+		$this->sum       = $sum;
+		$this->seller_id = $seller_id;
+	}
+
+	/**
+	 * @brief 设置用户组
+	 * @param string 用户组
+	 */
+	public function setUserGroup($groupId)
+	{
+		$this->user_group = $groupId;
+	}
+
+	/**
+	 * @brief 获取现金促销规则优惠后的金额
+	 * @return float 优惠后金额
+	 */
+	public function getSum()
+	{
+		//获取现金奖励信息
+		$cashInfo = $this->getAwardInfo($this->cash_award_type,$this->isCashOnce);
+
+		if(!empty($cashInfo))
+		{
+			//执行现金奖励运算
+			return $this->cashAction($cashInfo);
+		}
+		else
+		{
+			return $this->sum;
+		}
+	}
+
+	/**
+	 * @brief 进行赠品促销规则的奖励
+	 * @param int $user_id 用户的ID值
+	 */
+	public function setAward($user_id)
+	{
+		//获取赠品奖励信息
+		$giftInfo = $this->getAwardInfo($this->gift_award_type,$this->isGiftOnce);
+		return $this->giftAction($giftInfo,$user_id);
+	}
+
+	/**
+	 * @brief 获取促销规则的数据
+	 * @return array plan:活动方案名称; info:具体促销信息;
+	 */
+	public function getInfo()
+	{
+		$explain  = array();
+
+		$giftInfo = $this->getAwardInfo($this->gift_award_type,$this->isGiftOnce);
+		$cashInfo = $this->getAwardInfo($this->cash_award_type,$this->isCashOnce);
+
+		$allInfo  = array_merge($cashInfo,$giftInfo);
+
+		//增加商户名标识
+		$hostTag = "";
+		if($this->seller_id)
+		{
+			$sellerDB = new IModel('seller');
+			$sellerRow= $sellerDB->getObj('id = '.$this->seller_id);
+			$hostTag  = "【".$sellerRow['true_name']."】";
+		}
+		foreach($allInfo as $key => $val)
+		{
+			$explain[$key]['plan'] = $hostTag.$val['name'];
+			$explain[$key]['info'] = $this->typeExplain($val['award_type'],$val['condition'],$val['award_value']);
+		}
+		return $explain;
+	}
+
+	/**
+	 * @brief 奖励类型解释
+	 * @param int 类型id值
+	 * @param string 满足条件
+	 * @param string 奖励数据
+	 * @return string 类型说明
+	 */
+	private function typeExplain($awardType,$condition,$awardValue)
+	{
+		switch($awardType)
+		{
+			case "1":
+			{
+				return '购物满¥'.$condition.' 优惠¥'.$awardValue;
+			}
+			break;
+
+			case "2":
+			{
+				return '购物满¥'.$condition.' 优惠'.$awardValue.'%';
+			}
+			break;
+
+			case "3":
+			{
+				return '购物满¥'.$condition.' 增加'.$awardValue.'积分';
+			}
+			break;
+
+			case "4":
+			{
+				$ticketObj = new IModel('ticket');
+				$where     = 'id = '.$awardValue;
+				$ticketRow = $ticketObj->getObj($where);
+				return '购物满¥'.$condition.' 立得¥'.$ticketRow['value'].'代金券';
+			}
+			break;
+
+			case "5":
+			{
+				return '购物满¥'.$condition.' 送赠品';
+			}
+			break;
+
+			case "6":
+			{
+				return '购物满¥'.$condition.' 免运费';
+			}
+			break;
+
+			case "8":
+			{
+				return '购物满¥'.$condition.' 立加'.$awardValue.'经验';
+			}
+			break;
+
+			default:
+			{
+				return null;
+			}
+			break;
+		}
+	}
+
+	/**
+	 * @brief 是否减免订单的运费
+	 * @return bool true:减免; false:不减免
+	 */
+	public function isFreeFreight()
+	{
+		$proList = $this->satisfyPromotion(6);
+		if(!empty($proList))
+		{
+			return true;
+		}
+		else
+		{
+			return false;
+		}
+	}
+
+	/**
+	 * @brief 根据商品金额获取所满足的$award_type类别促销规则信息
+	 * @param int $award_type 奖励类别 1减金额 2奖励折扣 3赠送积分 4赠送代金券 5赠送赠品 6免运费 8赠送经验
+	 * @return array 促销规则信息
+	 */
+	private function satisfyPromotion($award_type = null)
+	{
+		$datetime = ITime::getDateTime();
+		$proObj   = new IModel('promotion');
+		$where    = '`condition` between 0 and '.$this->sum.' and type = 0 and is_close = 0 and start_time <= "'.$datetime.'" and end_time >= "'.$datetime.'" and seller_id = '.$this->seller_id;
+
+		//奖励类别分析
+		if($award_type != null)
+		{
+			$where.=' and award_type in ('.$award_type.')';
+		}
+
+		//用户组
+		if($this->user_group != null)
+		{
+			$where.=' and (user_group = "all" or FIND_IN_SET('.$this->user_group.',user_group))';
+		}
+		else
+		{
+			$where.=' and user_group = "all" ';
+		}
+		$proList = $proObj->query($where,'*','CAST( `condition` as signed ) desc');
+		return $proList;
+	}
+
+	/**
+	 * @brief 现金促销规则奖励操作
+	 * @param array 现金促销规则奖励信息
+	 * @return float 处理后金额
+	 */
+	private function cashAction($cashArray)
+	{
+		$sum = $this->sum;
+		foreach($cashArray as $val)
+		{
+			$award_type  = $val['award_type'];
+			$award_value = $val['award_value'];
+
+			switch($award_type)
+			{
+				//减少总额数
+				case "1":
+				{
+					$sum = $sum - $award_value;
+				}
+				break;
+
+				//减少百分比
+				case "2":
+				{
+					$sum = $sum - ($sum * ($award_value/100));
+				}
+				break;
+			}
+		}
+		return $sum;
+	}
+
+	/**
+	 * @brief 赠品促销规则奖励操作
+	 * @param array 赠品促销规则奖励信息
+	 */
+	private function giftAction($giftArray,$user_id)
+	{
+		$giftInfo = '';
+		foreach($giftArray as $key => $val)
+		{
+			$award_type  = $val['award_type'];
+			$award_value = $val['award_value'];
+			switch($award_type)
+			{
+				//积分
+				case "3":
+				{
+					$pointConfig = array(
+						'user_id' => $user_id,
+						'point'   => $award_value,
+						'log'     => $val['name'],
+					);
+					$pointObj = new Point;
+					$pointObj->update($pointConfig);
+				}
+				break;
+
+				//代金券
+				case "4":
+				{
+					/*(1)修改prop表*/
+					$ticketObj = new IModel('ticket');
+					$where     = 'id = '.$award_value;
+					$ticketRow = $ticketObj->getObj($where);
+
+					//奖励的红包没有过期
+					$time = ITime::getDateTime();
+					if(($time > $ticketRow['start_time']) && ($time < $ticketRow['end_time']))
+					{
+						$dataArray = array(
+							'condition' => $award_value,
+							'name'      => $ticketRow['name'],
+							'card_name' => 'T'.IHash::random(8),
+							'card_pwd'  => IHash::random(8),
+							'value'     => $ticketRow['value'],
+							'start_time'=> $ticketRow['start_time'],
+							'end_time'  => $ticketRow['end_time'],
+							'is_send'   => 1,
+						);
+						$propObj = new IModel('prop');
+						$propObj->setData($dataArray);
+						$insert_id = $propObj->add();
+
+						/*(2)修改member表*/
+						$memberObj = new IModel('member');
+						$memberArray = array('prop' => "CONCAT(IFNULL(prop,''),'{$insert_id},')");
+						$memberObj->setData($memberArray);
+						$memberObj->update('user_id = '.$user_id,'prop');
+						$giftInfo .= "【代金券号:".$dataArray['card_name']."】";
+					}
+				}
+				break;
+
+				//赠送经验
+				case "8":
+				{
+					plugin::trigger('expUpdate',$user_id,$award_value);
+				}
+				break;
+			}
+		}
+		return $giftInfo;
+	}
+
+	/**
+	 * @brief 获取奖励信息
+	 * @param array $award_type 奖励类型数组值
+	 * @param bool  $is_once    奖励方案是否允许叠加
+	 * @return array            奖励信息
+	 */
+	private function getAwardInfo($award_type,$is_once)
+	{
+		$awardInfo = array();
+
+		//获取所有现金促销规则奖励信息
+		$award_type_str = join(',',$award_type);
+		$allAwardInfo   = $this->satisfyPromotion($award_type_str);
+
+		//当现金奖励仅为一次时,奖励优惠最大化
+		if(!empty($allAwardInfo))
+		{
+			if($is_once == true)
+			{
+				$awardInfo[0] = current($allAwardInfo);
+			}
+			else
+			{
+				$awardInfo = $allAwardInfo;
+			}
+		}
+		return $awardInfo;
+	}
+
+	//根据ID获取促销活动数据
+	public function getPromotionByIds($ids)
+	{
+		$proObj  = new IModel('promotion');
+		$where   = 'id in ('.$ids.')';
+		return $proObj->query($where,'*','CAST( `condition` as signed ) desc');
+	}
+
+	//获取促销规则IDS串
+	public function getAwardIds($award_type = '',$is_once = '')
+	{
+		$result    = array();
+		$award_type= $award_type ? $award_type : $this->gift_award_type;
+		$is_once   = $is_once    ? $is_once    : $this->isGiftOnce;
+		$data      = $this->getAwardInfo($award_type,$is_once);
+		foreach($data as $key => $val)
+		{
+			$result[] = $val['id'];
+		}
+		return join(',',$result);
+	}
+
+	//根据ID奖励执行
+	public function setAwardByIds($ids,$user_id)
+	{
+		$giftArray = $this->getPromotionByIds($ids);
+		return $this->giftAction($giftArray,$user_id);
+	}
+}

+ 87 - 0
src/classes/report.php

@@ -0,0 +1,87 @@
+<?php
+/**
+ * @copyright (c) 2014 aircheng
+ * @file report.php
+ * @brief 导出excel类库
+ * @author dabao
+ * @date 2014/11/28 22:09:43
+ * @version 1.0.0
+
+ * @update 4.6
+ * @date 2016/9/15 23:30:28
+ * @author nswe
+ * @content 重构了写入方式和方法
+ */
+class report
+{
+	//文件名
+	private $fileName = 'user';
+
+	//数据内容
+	private $_data    = "";
+
+	//构造函数
+	public function __construct($fileName = '')
+	{
+		$this->setFileName($fileName);
+	}
+
+	//设置要导出的文件名
+	public function setFileName($fileName)
+	{
+		$this->fileName = $fileName;
+	}
+
+	/**
+	 * @brief 写入内容操作,每次存入一行
+	 * @param $data array 一维数组
+	 */
+	public function setTitle($data = array())
+	{
+		array_walk($data,function(&$val,$key)
+		{
+			$val = "<th style='text-align:center;background-color:green;color:#fff;font-size:12px;vnd.ms-excel.numberformat:@'>".$val."</th>";
+		});
+		$this->_data .= "<tr>".join($data)."</tr>";
+	}
+
+	/**
+	 * @brief 写入标题操作
+	 * @param $data array  数据
+	 */
+	public function setData($data = array())
+	{
+		array_walk($data,function(&$val,$key)
+		{
+			$val = "<td style='text-align:center;font-size:12px;vnd.ms-excel.numberformat:@'>".$val."</td>";
+		});
+		$this->_data .= "<tr>".join($data)."</tr>";
+	}
+
+	//开始下载
+	public function toDownload($data = '')
+	{
+		// Redirect output to a client’s web browser (Excel5)
+		header('Content-Type: application/vnd.ms-excel');
+		header('Content-Disposition: attachment;filename='.$this->fileName.'_'.date('Y-m-d').'.xls');
+		header('Cache-Control: max-age=0');
+		// If you're serving to IE 9, then the following may be needed
+		header('Cache-Control: max-age=1');
+
+		// If you're serving to IE over SSL, then the following may be needed
+		header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
+		header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
+		header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
+		header ('Pragma: public'); // HTTP/1.0
+
+		$result = $data ? $data : "<table border='1'>".$this->_data."</table>";
+echo <<< OEF
+<html>
+	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
+	<body>
+	{$result}
+	</body>
+</html>
+OEF;
+	}
+}

+ 42 - 0
src/classes/safestrategy.php

@@ -0,0 +1,42 @@
+<?php
+/**
+ * check website safe strategy
+ * @date 2013/9/8 17:00:46
+ * @author nswe
+ */
+class safeStrategy
+{
+	private $safeInfo = array();
+
+	/**
+	 * constructor
+	 */
+	public function __construct()
+	{
+	}
+
+	/**
+	 * start check website safe options and return a array
+	 * @return array
+	 */
+	public function check()
+	{
+		$this->cInstall();
+		return $this->safeInfo;
+	}
+
+	/**
+	 * check the install dir whether exists
+	 * @return boolean
+	 */
+	private function cInstall()
+	{
+		$appBasePath = IWeb::$app->getBasePath();
+		$installPath = $appBasePath . 'install';
+
+		if(file_exists($installPath))
+		{
+			$this->safeInfo[] = array('content' => '您的安装目录(install目录)没有删除,为了商店安全,请尽快删除或者重新命名');
+		}
+	}
+}

+ 355 - 0
src/classes/search_goods.php

@@ -0,0 +1,355 @@
+<?php
+/**
+ * @brief 检索商品类
+ * @date 2013/12/1 18:34:35
+ * @author chendeshan
+ */
+class search_goods
+{
+	//商品检索的属性过滤 array(key => array(id,name,value))
+	public static $attrSearch = array();
+
+	//商品检索的品牌过滤 array(key => array(id,name))
+	public static $brandSearch = array();
+
+	//商品检索的价格过滤
+	public static $priceSearch = array();
+
+	/**
+	 * @brief [条件检索url处理]对于query url中已经存在的数据进行删除;没有的参数进行添加
+	 * @param string or array $queryKey 字段名称
+	 * @param string or array $queryVal 字段值
+	 */
+	public static function searchUrl($queryKey,$queryVal = '')
+	{
+		if(is_array($queryKey))
+		{
+			$condition = array();
+			foreach($queryKey as $key => $colum)
+			{
+				$columValue = is_array($queryVal) ? $queryVal[$key] : $queryVal;
+				$condition[]= $colum."=".$columValue;
+			}
+			$condition = join("&",$condition);
+		}
+		else
+		{
+			$condition = $queryKey."=".$queryVal;
+		}
+
+		//生成解析本次要检索的条件
+		parse_str($condition,$inputArray);
+
+		//解析当前URL已经存在的条件
+		$queryArray  = array();
+		$orgUrl      = IUrl::getUri();
+		$parseUrlArr = parse_url($orgUrl);
+		if(isset($parseUrlArr['query']) && $parseUrlArr['query'])
+		{
+			parse_str($parseUrlArr['query'], $queryArray);
+		}
+
+		//对条件进行替换产生最终的条件结果
+		$resultQuery = array_replace_recursive($queryArray,$inputArray);
+		$resultQuery = IFilter::emptyArray($resultQuery);
+
+		//产生跳转的URL地址
+		$parseUrlArr['query'] = "?".http_build_query($resultQuery);
+		return join($parseUrlArr);
+	}
+
+	/**
+	 * @brief 获取排列顺序: asc,desc
+	 * @param string 排列字段 sort,new...来自 self::getOrderType()
+	 * @return string asc:正序;desc:倒序
+	 */
+	public static function getOrderBy($order)
+	{
+		$issetOrder = IReq::get('order');
+		$issetBy    = IReq::get('by');
+		if($order == $issetOrder && $issetBy == "asc")
+		{
+			return "desc";
+		}
+		return "asc";
+	}
+
+	/**
+	 * @brief 获取总的排序方式
+	 * @return array(代号 => 名字)
+	 */
+	public static function getOrderType()
+	{
+		return array('sale' =>'销量','cpoint' =>'评分','price'=>'价格','new'=>'最新上架');
+	}
+
+	/**
+	 * @brief 商品检索,可以直接读取 $_GET 全局变量:attr,order,brand,min_price,max_price
+	 *        在检索商品过程中计算商品结果中的进一步属性和规格的筛选
+	 * @param mixed $defaultWhere string(条件) or array('search' => '模糊查找','category_extend' => '商品分类ID','字段' => 对应数据)
+	 * @param int $limit 读取数量
+	 * @param bool $isCondition 是否筛选出商品的属性,价格等数据
+	 * @return IQuery
+	 */
+	public static function find($defaultWhere = '',$limit = 21,$isCondition = true)
+	{
+		//排序字段
+		$orderArray = array();
+
+		//开始查询
+		$goodsObj           = new IQuery("goods as go");
+		$goodsObj->page     = isset($_GET['page']) ? intval($_GET['page']) : 1;
+		$goodsObj->fields   = 'go.id,go.name,go.sell_price,go.market_price,go.store_nums,go.img,go.sale,go.grade,go.comments,go.favorite';
+		$goodsObj->pagesize = $limit;
+		$goodsObj->group    = 'go.id';
+
+		/*where条件拼接*/
+		//(1),当前产品分类
+		$where = array('go.is_del = 0');
+		$join  = array();
+
+		//(2),商品属性,规格筛选
+		$attrCond  = array();
+		$attrArray = IReq::get('attr') ? IFilter::act(IReq::get('attr')) : array();
+		if($attrArray)
+		{
+			foreach($attrArray as $attId => $attVal)
+			{
+				$attId = IFilter::act($attId,'int');
+				if($attId && $attVal && !preg_match("|\s+|",$attVal))
+				{
+					$attrCond[] = 'attribute_id = '.$attId.' and FIND_IN_SET("'.$attVal.'",attribute_value)';
+				}
+			}
+
+			if($attrCond)
+			{
+				$temp = array();
+				foreach($attrCond as $key => $val)
+				{
+					$temp[] = " SELECT goods_id FROM goods_attribute as t{$key} WHERE {$val} ";
+				}
+				$join[]  = "left join (select goods_id from (".join(" UNION ALL ",$temp).") as temp group by temp.goods_id having count(*) > {$key}) as ga on ga.goods_id = go.id";
+				$where[] = "ga.goods_id is NOT NULL";
+			}
+		}
+
+		//(3),处理defaultWhere条件 goods, category_extend
+		if($defaultWhere)
+		{
+			//兼容array 和 string 数据类型的goods条件筛选
+			$goodsCondArray = array();
+			if(is_string($defaultWhere))
+			{
+				$goodsCondArray[] = $defaultWhere;
+			}
+			else if(is_array($defaultWhere))
+			{
+				foreach($defaultWhere as $key => $val)
+				{
+					if($val === '' || $val === null)
+					{
+						continue;
+					}
+
+					//商品分类检索
+					if($key == 'category_extend')
+					{
+						//没有点击搜索属性 $attrCond
+						if($val)
+						{
+							$join[]  = "left join category_extend as ce on ce.goods_id = go.id";
+							$where[] = "ce.category_id in (".$val.")";
+						}
+					}
+					//搜索词模糊
+					else if($key == 'search')
+					{
+						$wordWhere     = array();
+						$wordLikeOrder = array();
+
+						//进行分词
+						if(IString::getStrLen($defaultWhere['search']) >= 4 || IString::getStrLen($defaultWhere['search']) <= 100)
+						{
+							$wordData = plugin::trigger("onSearchGoodsWordsPart",$defaultWhere['search']);
+							if(isset($wordData['data']) && count($wordData['data']) >= 1)
+							{
+								foreach($wordData['data'] as $word)
+								{
+									$wordWhere[]     = ' go.name like "%'.$word.'%" ';
+									$wordLikeOrder[] = $word;
+								}
+
+								//分词排序
+								if($wordLikeOrder)
+								{
+									$orderTempArray = array();
+									foreach($wordLikeOrder as $key => $val)
+									{
+										$orderTempArray[] = "(CASE WHEN go.name LIKE '%".$val."%' THEN ".$key." ELSE 100 END)";
+									}
+									$orderArray[] = " (".join('+',$orderTempArray).") asc ";
+								}
+							}
+						}
+
+						//存在分词结果
+						if($wordWhere)
+						{
+							$goodsCondArray[] = join(" and ",$wordWhere).' or find_in_set("'.$defaultWhere['search'].'",go.search_words)';
+						}
+						else
+						{
+							$goodsCondArray[] = ' go.name like "%'.$defaultWhere['search'].'%" or find_in_set("'.$defaultWhere['search'].'",go.search_words) ';
+						}
+					}
+					//其他条件
+					else
+					{
+						$goodsCondArray[] = $key.' = "'.$val.'"';
+					}
+				}
+			}
+
+			//goods 条件
+			if($goodsCondArray)
+			{
+				$where[] = "(".join(" and ",$goodsCondArray).")";
+			}
+		}
+
+		//商品属性进行检索
+		if($isCondition == true)
+		{
+			/******属性 开始******/
+			$attrTemp            = array();
+			$goodsAttrDB         = new IQuery('goods_attribute as goAttr');
+			$goodsAttrDB->fields = "goAttr.attribute_id,goAttr.attribute_value,att.name";
+			$goodsAttrDB->join   = "left join goods as go on go.id = goAttr.goods_id left join attribute as att on att.id = goAttr.attribute_id ".join("  ",$join);
+			$goodsAttrDB->where  = join(" and ",$where)." and att.search = 1";
+			$goodsAttrData       = $goodsAttrDB->find();
+			foreach($goodsAttrData as $key => $val)
+			{
+				//属性存在
+				if($val['attribute_id'] && $val['name'] && $val['attribute_value'])
+				{
+					if(!isset($attrTemp[$val['name']]))
+					{
+						$attrTemp[$val['name']] = array(
+							'id'    => $val['attribute_id'],
+							'name'  => $val['name'],
+							'value' => array(),
+						);
+					}
+					else if($attrTemp[$val['name']]['id'] != $val['attribute_id'])
+					{
+						continue;
+					}
+
+					$checkSelectedArray = explode(",",$val['attribute_value']);//有复选情况
+					foreach($checkSelectedArray as $k => $v)
+					{
+						if(!in_array( $v,$attrTemp[$val['name']]['value'] ))
+						{
+							$attrTemp[$val['name']]['value'][] = $v;
+						}
+					}
+				}
+			}
+			self::$attrSearch = $attrTemp;
+			/******属性 结束******/
+
+			/******品牌 开始******/
+			$brandQuery        = new IQuery('brand as b');
+			$brandQuery->join  = "left join goods as go on go.brand_id = b.id ".join("  ",$join);
+			$brandQuery->where = join(" and ",$where);
+			$brandQuery->order = "b.sort asc";
+			$brandQuery->fields= "distinct b.id,b.name";
+			$brandQuery->limit = 10;
+			self::$brandSearch = $brandQuery->find();
+			/******品牌 结束******/
+
+			/******价格 开始******/
+			$priceDB = new IQuery('goods as go');
+			$priceDB->fields = "sell_price";
+			$priceDB->join   = join(" ",$join);
+			$priceDB->where  = join(" and ",array_slice($where,1));
+			$priceDB->limit  = 1;
+
+			//最小价格
+			$priceDB->order = "sell_price asc";
+			$minPriceData = $priceDB->find();
+			$minPrice     = $minPriceData ? $minPriceData[0]['sell_price'] : 0;
+
+			//最大价格
+			$priceDB->order = "sell_price desc";
+			$maxPriceData = $priceDB->find();
+			$maxPrice     = $maxPriceData ? $maxPriceData[0]['sell_price'] : 0;
+
+			//计算价格区间
+			self::$priceSearch = goods_class::getGoodsPrice($minPrice,$maxPrice);
+			/******价格 结束******/
+		}
+
+		//(4),商品价格
+		$where[] = floatval(IReq::get('min_price')) ? 'go.sell_price >= '.floatval(IReq::get('min_price')) : '';
+		$where[] = floatval(IReq::get('max_price')) ? 'go.sell_price <= '.floatval(IReq::get('max_price')) : '';
+
+		//(5),商品品牌
+		$where[] = IReq::get('brand') ? 'go.brand_id = '.intval(IReq::get('brand')) : '';
+
+		//排序类别
+		$order = IReq::get('order');
+		$by    = IReq::get('by') == "desc" ? "desc" : "asc";
+		if($order == null)
+		{
+			//获取配置信息
+			$siteConfigObj = new Config("site_config");
+			$site_config   = $siteConfigObj->getInfo();
+			$order         = isset($site_config['order_by']) ? $site_config['order_by'] :'';
+		}
+
+		switch($order)
+		{
+			//销售量
+			case "sale":
+			{
+				$orderArray[] = ' go.sale '.$by;
+			}
+			break;
+
+			//评分
+			case "cpoint":
+			{
+				$orderArray[] = ' go.grade '.$by;
+			}
+			break;
+
+			//最新上架
+			case "new":
+			{
+				$orderArray[] = ' go.id '.$by;
+			}
+			break;
+
+			//价格
+			case "price":
+			{
+				$orderArray[] = ' go.sell_price '.$by;
+			}
+			break;
+
+			//根据排序字段
+			default:
+			{
+				$orderArray[] = ' go.sort asc ';
+			}
+		}
+
+		//设置IQuery类的各个属性
+		$goodsObj->join  = join(" ",array_filter($join));
+		$goodsObj->where = join(" and ",array_filter($where));
+		$goodsObj->order = join(',',array_filter($orderArray));
+		return $goodsObj;
+	}
+}

+ 166 - 0
src/classes/seller_mess.php

@@ -0,0 +1,166 @@
+<?php
+/**
+ * @copyright (c) 2011 aircheng.com
+ * @file seller_mess.php
+ * @brief 商户消息的管理
+ * @author qfsoft
+ * @date 2016/03/06 20:30:10
+ * @version 4.4
+ */
+class seller_mess
+{
+	//商户信息数据库实例
+	private $sellerDB = null;
+
+	//商户id
+	private $seller_id = '';
+
+	//商户消息ID
+	private $messageIds = '';
+
+	/**
+	 * @brief 构造函数 商户id
+	 * @param string $seller_id 商户id
+	 */
+	function __construct($seller_id)
+	{
+		$this->seller_id  = $seller_id;
+		$this->sellerDB = new IModel('seller');
+		$sellerRow      = $this->sellerDB->getObj('id = '.$seller_id);
+		$this->messageIds = $sellerRow['seller_message_ids'];
+	}
+
+	/**
+	 * 直接发站内信到商户
+	 * @param string $sellerIds 商户Id的串
+	 * @param array $content 消息内容  array('title' => '标题','content' => '内容')
+	 */
+	public static function send($sellerIds, $content)
+	{
+		set_time_limit(0);
+
+		$data = array(
+			'title'   => $content['title'],
+			'content' => $content['content'],
+			'time'    => ITime::getDateTime(),
+		);
+
+		$msgDB = new IModel("seller_message");
+		$msgDB->setData($data);
+		$id = $msgDB->add();
+
+		if($id === false)
+		{
+			return false;
+		}
+		else
+		{
+			$db = IDBFactory::getDB();
+			$tableName = IWeb::$app->config['DB']['tablePre']."seller";
+			if ($sellerIds)
+			{
+				$sql = "UPDATE `{$tableName}` SET seller_message_ids = CONCAT( IFNULL(seller_message_ids,'') ,'{$id},') WHERE id in ({$sellerIds})";
+			}
+			else
+			{
+				$sql = "UPDATE `{$tableName}` SET seller_message_ids = CONCAT( IFNULL(seller_message_ids,'') ,'{$id},')";
+			}
+			return $db->query($sql);
+		}
+	}
+
+	/**
+	 * @brief 获得seller表中的seller_message_ids,去掉 '-' 和最后的 ','
+	 * @return string 返回所有商户消息id的字符串
+	 */
+	public function getAllMsgIds()
+	{
+		return str_replace('-','',trim($this->messageIds,','));
+	}
+
+	/**
+	 * @brief 判断seller_message_id是否已经读过
+	 * @param int $messageId seller_message的id
+	 * @return boolean 返回true为已读,false为未读
+	 */
+	public function is_read($messageId)
+	{
+		if(strpos(','.trim($this->messageIds,',').',',',-'.$messageId.',') === false)
+		{
+			return false;
+		}
+		return true;
+	}
+
+	/**
+	 * @brief 将messageId写入seller表中
+	 * @param int $messageId seller_message的id
+	 * @param int $read 0:未读(追加到用户id串后面),1:已读(把用户id串增加'-'负号)
+	 * @return int or boolean
+	 */
+	public function writeMessage($messageId,$read = 0)
+	{
+		if($read == 1)
+		{
+			$tempIds = ','.trim($this->messageIds,',').',';
+			if(strpos($tempIds,','.$messageId.',') === false)
+			{
+				return false;
+			}
+			$tempIds = str_replace(','.$messageId.',',',-'.$messageId.',',$tempIds);
+			$this->messageIds = trim($tempIds,',').',';
+		}
+		else
+		{
+			$this->messageIds .= $messageId.',';
+		}
+		return $this->save();
+	}
+
+	/**
+	 * @brief 存储消息串
+	 * @return boolean
+	 */
+	private function save()
+	{
+		$this->sellerDB->setData(array('seller_message_ids' => $this->messageIds));
+		return $this->sellerDB->update('id='.$this->seller_id);
+	}
+
+	/**
+	 * @brief 删除seller表中的messageId数据
+	 * @param $messageId string 要删除的消息ID值
+	 * @return string message_ids结果字符串
+	 */
+	public function delMessage($messageId)
+	{
+		$tempIds = str_replace(','.$messageId.',','',','.trim($this->messageIds,',').',');
+		$tempIds = str_replace(',-'.$messageId.',','',','.trim($tempIds,',').',');
+		$tempIds = trim($tempIds,',').',';
+		$this->messageIds = $tempIds;
+		return $this->save();
+	}
+
+	/**
+	 * @brief 获取未读的商户消息数
+	 * @return int 消息数量
+	 */
+	public function needReadNum()
+	{
+		$tempIds = ','.trim($this->messageIds,',').',';
+		preg_match_all('|,\d+|',$tempIds,$result);
+		return count(current($result));
+	}
+
+	//读取消息
+	public function read($id)
+	{
+		$wholeIds = $this->getAllMsgIds();
+		if(strpos(",".$wholeIds.",",",".$id.",") === false)
+		{
+			return null;
+		}
+		$msgDB = new IModel("seller_message");
+		return $msgDB->getObj('id = '.$id);
+	}
+}

+ 148 - 0
src/classes/sendmail.php

@@ -0,0 +1,148 @@
+<?php
+/**
+ * @copyright (c) 2014 aircheng.com
+ * @file sendmail.php
+ * @brief 邮件发送接口
+ * @author chendeshan
+ * @date 2014/11/28 23:22:59
+ * @version 2.9
+ */
+class SendMail
+{
+	private $config = array();//邮件配置信息
+	private $smtp   = null;   //邮件发送对象
+	private $error  = '';     //错误信息
+
+	//构造函数
+	public function __construct($site_config = null)
+	{
+		if($site_config == null)
+		{
+			$siteConfigObj = new Config("site_config");
+			$site_config   = $siteConfigObj->getInfo();
+			$this->config  = $site_config;
+		}
+		else
+		{
+			$this->config  = $site_config;
+		}
+
+		if($this->checkEmailConf($site_config))
+		{
+			$phpMailerDir = IWEB_PATH.'core/util/phpmailer/PHPMailerAutoload.php';
+			include_once($phpMailerDir);
+
+			//创建实例
+			$this->smtp = new PHPMailer();
+			$this->smtp->Timeout = 60;
+			$this->smtp->SMTPSecure = $site_config['email_safe'];
+			$this->smtp->isHTML();
+
+			//使用系统mail函数发送
+			if(isset($site_config['email_type']) && $site_config['email_type']=='2')
+			{
+				$this->smtp->isMail();
+			}
+			//使用外部SMTP服务器发送
+			else
+			{
+				$this->smtp->isSMTP();
+				$this->smtp->SMTPAuth = true;
+				$this->smtp->Host     = $site_config['smtp'];
+				$this->smtp->Port     = $site_config['smtp_port'];
+				$this->smtp->Username = $site_config['smtp_user'];
+				$this->smtp->Password = $site_config['smtp_pwd'];
+			}
+		}
+		else
+		{
+			$this->error = "邮箱配置参数填写不完整";
+		}
+	}
+
+	//获取错误信息
+	public function getError()
+	{
+		return $this->smtp ? $this->smtp->ErrorInfo : $this->error;
+	}
+
+	/**
+	 * @brief 检查邮件配置信息的合法性
+	 * @parms $site_config array 配置信息
+	 * @return bool true:成功;false:失败;
+	 */
+	public function checkEmailConf($site_config)
+	{
+		if(isset($site_config['email_type']) && isset($site_config['mail_address']))
+		{
+			if($site_config['email_type'] == 1)
+			{
+				$mustConfig = array('smtp','smtp_user','smtp_pwd','smtp_port');
+				foreach($mustConfig as $val)
+				{
+					if(!isset($site_config[$val]) || $site_config[$val] == '')
+					{
+						return false;
+					}
+				}
+				return true;
+			}
+			else
+			{
+				return true;
+			}
+		}
+		else
+		{
+			return false;
+		}
+	}
+
+	/**
+	 * @brief 邮件发送
+	 * @parms  $to      string 收件人
+	 * @parms  $title   string 标题
+	 * @parms  $content string 内容
+	 * @parms  $bcc     string 抄送收件人以";"分隔开
+	 * @return bool true:成功;false:失败;
+	 */
+	public function send($to,$title,$content,$bcc = '')
+	{
+		if(is_object($this->smtp))
+		{
+			$this->smtp->FromName= isset($this->config['name']) ? $this->config['name'] : 'iWebShop';
+			$this->smtp->From    = $this->config['mail_address'];
+			$this->smtp->Subject = $title;
+			$this->smtp->Body    = $content;
+
+			//收件人
+			$tempToEmail = explode(';',$to);
+			foreach($tempToEmail as $key => $val)
+			{
+				$this->smtp->addAddress($val);
+			}
+
+			//抄送人
+			if($bcc)
+			{
+				$tempBccEmail = explode(';',$bcc);
+				foreach($tempBccEmail as $key => $val)
+				{
+					$this->smtp->addBCC($val);
+				}
+			}
+
+			return $this->smtp->send();
+		}
+		else
+		{
+			return false;
+		}
+	}
+
+	//获取配置信息
+	public function getConfigItem($key)
+	{
+		return isset($this->config[$key]) ? $this->config[$key] : null;
+	}
+}

+ 152 - 0
src/classes/sitehelp.php

@@ -0,0 +1,152 @@
+<?php
+/**
+ * 关于系统帮助
+ * @author walu
+ * @package iwebshop
+ */
+class SiteHelp
+{
+	public static function get_help_by_id($id)
+	{
+		if(!is_array($id))
+		{
+			$id=array($id);
+		}
+
+		if(!$id)
+			return array();
+
+		foreach($id as $key => $value)
+		{
+			$id[$key]=intval($value);
+		}
+		$id=implode( "," , array_unique($id)   );
+		$tb_help=new IModel('help');
+		$list=$tb_help->query("id IN ({$id})");
+		return Util::array_rekey($list,'id');
+	}
+
+	public static function help_edit($data)
+	{
+		if(!isset($data['name']) || $data['name']===null || !preg_match('!^.{1,50}$!u',$data['name']) )
+		{
+			return array('flag'=>false,'data'=>'标题不能为空,且不能超过50个文字');
+		}
+		$data['name'] = htmlspecialchars($data['name'],ENT_QUOTES);
+
+		if(!isset($data['cat_id']) || $data['cat_id']===null)
+		{
+			return array('flag'=>false,'data'=>'分类不能为空');
+		}
+
+		$data['cat_id']  = intval($data['cat_id']);
+		$data['content'] = IFilter::act($data['content'],'text');
+		$data['sort']    = abs(intval($data['sort']));
+		$data['dateline']= ITime::getNow();
+
+		$id = $data['id'];
+		unset($data['id']);
+
+		$tb_help = new IModel("help");
+		$tb_help->setData($data);
+
+		if(!$id)
+		{
+			$tb_help->setData($data);
+			$tb_help->add();
+		}
+		else
+		{
+			$tb_help->update("id={$id}");
+		}
+		return array('flag'=>true,'data'=>'success');
+
+	}
+
+	public static function help_del($id)
+	{
+		if(!is_array($id))
+		{
+			$id = array($id);
+		}
+		$id = IFilter::act($id,'int');
+		$id = implode(",",$id);
+		$tb_help = new IModel("help");
+		$tb_help->del("id IN ({$id})");
+		return array('flag'=>true,'data'=>'success');
+	}
+
+	public static function get_cat_by_id($id)
+	{
+		if(!is_array($id))
+		{
+			$id=array($id);
+		}
+
+		if(!$id)
+			return array();
+
+		foreach($id as $key => $value)
+		{
+			$id[$key]=intval($value);
+		}
+		$id=implode( "," , array_unique($id)   );
+		$tb_help_cat=new IModel('help_category');
+		$list=$tb_help_cat->query("id IN ({$id})");
+		return Util::array_rekey($list,'id');
+	}
+
+	public static function cat_edit($arr)
+	{
+		if(!isset($arr['id']) || $arr['id']===null || !preg_match("![0-9]+!",$arr['id']) )
+		{
+			unset($arr['id']);
+		}
+
+		if($arr['name']===null || !preg_match('!^.{1,10}$!u',$arr['name']))
+		{
+			return array('flag'=>false,'data'=>'分类名称不能超过十个文字');
+		}
+
+		$arr['name'] = htmlspecialchars($arr['name'],ENT_QUOTES);
+		$arr['sort'] = intval($arr['sort']);
+		$arr['position_left'] = intval($arr['position_left'])==1?1:0;
+		$arr['position_foot'] = intval($arr['position_foot'])==1?1:0;
+
+		$tb_help_category = new IModel("help_category");
+		$tb_help_category->setData($arr);
+		if(isset($arr['id']))
+		{
+			$id=intval($arr['id']);
+			unset($arr['id']);
+			$tb_help_category->update("id={$id}");
+		}
+		else
+		{
+			$tb_help_category->add($arr);
+		}
+		return array('flag'=>true,'data'=>"编辑成功");
+	}
+
+	public static function mod_cat_position($id,$position,$value)
+	{
+		$id = intval($id);
+		$value = intval($value)==1?1:0;
+
+		if($position!='left' && $position!='foot')
+			return array('flag'=>false,'data'=>'错误的位置');
+
+		$tb_help_category = new IModel("help_category");
+		$tb_help_category->setData( array("position_{$position}"=>$value) );
+		$tb_help_category->update("id={$id}");
+		return array('flag'=>true);
+	}
+
+	public static function del_cat($id)
+	{
+		$id = intval($id);
+		$tb_help_category = new IModel("help_category");
+		$result = $tb_help_category->del("id={$id}");
+		return array('flag'=>$result);
+	}
+}

+ 74 - 0
src/classes/sitemaps.php

@@ -0,0 +1,74 @@
+<?php
+/**
+ * @copyright Copyright(c) 2011 aircheng.com
+ * @file
+ * @brief
+ * @author webning
+ * @date 2011-01-21
+ * @version 0.6
+ * @note
+ */
+/**
+ * @brief SiteMaps
+ * @class SiteMaps
+ * @note
+ */
+class SiteMaps
+{
+	private $siteMapsFile;
+    /**
+     * @brief 构造函数
+     */
+	public function __construct()
+	{
+		$this->siteMapsFile = IWeb::$app->getBasePath().'sitemaps.xml';
+	}
+    /**
+     * @brief 生成系统的siteMaps.xml文件
+     * @param mixed $maps
+     * @param string $xsl
+     */
+	function create($maps,$xsl='')
+	{
+		$siteMaps = new IXML();
+		if($xsl!='')$siteMaps->setStylesheet($xsl);
+		$siteMaps->addNode('/','sitemapindex','','xmlns=http://www.sitemaps.org/schemas/sitemap/0.9;xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance;xsi:schemaLocation=http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/siteindex.xsd');
+		if(is_array($maps))
+		{
+			foreach($maps as $key => $value)
+			{
+				$num = $key+1;
+				$siteMaps->addNode("/sitemapindex",'sitemap','');
+				$siteMaps->addNode('/sitemapindex/sitemap['.$num.']','loc',$value['loc']);
+				$siteMaps->addNode('/sitemapindex/sitemap['.$num.']','lastmod',$value['lastmod']);
+			}
+		}
+		$siteMaps->save($this->siteMapsFile);
+	}
+    /**
+     * @brief 创建系统的map文件
+     * @return String
+     */
+	public static function create_map($items,$filename,$xsl)
+	{
+		$siteMaps = new IXML();
+		if($xsl!='')$siteMaps->setStylesheet($xsl);
+		$siteMaps->addNode('/','urlset','','xmlns=http://www.sitemaps.org/schemas/sitemap/0.9;xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance;xsi:schemaLocation=http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/siteindex.xsd');
+		if(is_array($items))
+		{
+			foreach($items as $key => $value)
+			{
+				$num = $key+1;
+				$siteMaps->addNode("/urlset",'url','');
+				$siteMaps->addNode('/urlset/url['.$num.']','loc',$value['loc']);
+				$siteMaps->addNode('/urlset/url['.$num.']','lastmod',$value['lastmod']);
+				$siteMaps->addNode('/urlset/url['.$num.']','changefreq','monthly');
+				$siteMaps->addNode('/urlset/url['.$num.']','priority','0.8');
+				$siteMaps->addNode('/urlset/url['.$num.']','data','');
+				$siteMaps->addNode('/urlset/url['.$num.']/data','display','');
+			}
+		}
+		$siteMaps->save(IWeb::$app->getBasePath().$filename);
+	}
+}
+?>

+ 120 - 0
src/classes/smstemplate.php

@@ -0,0 +1,120 @@
+<?php
+/**
+ * @copyright (c) 2011 aircheng.com
+ * @file smstemplate.php
+ * @brief 短信发送模板
+ * @author chendeshan
+ * @date 2014/8/11 9:51:51
+ * @version 2.9
+ */
+
+ /**
+ * @class smsTemplate
+ * @brief 短信发送模板
+ */
+class smsTemplate
+{
+	//短信模板信息不存在
+	public static function __callStatic($funcname, $arguments)
+	{
+		return "";
+	}
+
+	/**
+	 * @brief 订单发货的信息模板
+	 * @param array $data 替换的数据
+	 */
+	public static function sendGoods($data = null)
+	{
+		$templateString = "您好{user_name},订单号:{order_no},已由{sendor}发货,物流公司:{delivery_company},物流单号:{delivery_no}";
+		return strtr($templateString,$data);
+	}
+
+	/**
+	 * @brief 手机找回密码模板
+	 * @param array $data 替换的数据
+	 */
+	public static function findPassword($data = null)
+	{
+		$templateString = "您的验证码为:{mobile_code},请注意保管!";
+		return strtr($templateString,$data);
+	}
+
+	/**
+	 * @brief 手机短信校验码
+	 * @param array $data 替换的数据
+	 */
+	public static function checkCode($data = null)
+	{
+		$templateString = "您的验证码为:{mobile_code},请注意保管!";
+		return strtr($templateString,$data);
+	}
+
+	/**
+	 * @brief 自提点确认短信
+	 * @param array $data 替换的数据
+	 */
+	public static function takeself($data = null)
+	{
+		$templateString = "您的订单号:{orderNo},{name}自提地址:{address},领取验证码:{mobile_code},请尽快领取";
+		return strtr($templateString,$data);
+	}
+
+	/**
+	 * @brief 商户注册提示管理员
+	 * @param array $data 替换的数据
+	 */
+	public static function sellerReg($data = null)
+	{
+		$templateString = "{true_name},申请加盟到平台,请尽快登录后台进行处理";
+		return strtr($templateString,$data);
+	}
+
+	/**
+	 * @brief 商户处理结果
+	 * @param array $data 替换的数据
+	 */
+	public static function sellerCheck($data = null)
+	{
+		$templateString = "您申请的加盟商状态已经被修改为:{result}状态,请登录您的商户后台查看具体的详情";
+		return strtr($templateString,$data);
+	}
+
+	/**
+	 * @brief 订单付款通知管理员
+	 */
+	public static function payFinishToAdmin($data = null)
+	{
+		$templateString = "商城订单:{orderNo},已经付款,请尽快登录后台进行处理";
+		return strtr($templateString,$data);
+	}
+
+	/**
+	 * @brief 订单付款通知管理员
+	 */
+	public static function payFinishToUser($data = null)
+	{
+		$templateString = "您的订单号:{orderNo},已付款成功,稍后我们会尽快为您服务";
+		return strtr($templateString,$data);
+	}
+
+	/**
+	 * @brief 到货通知模板
+	 * @param array $data 替换的数据
+	 */
+	public static function notify($data = null)
+	{
+		$templateString = "尊敬的用户,您需要购买的 <{goodsName}> 现已全面到货,机不可失,从速购买!{url}; 退订回N";
+		return strtr($templateString,$data);
+	}
+
+	/**
+	 * @brief 订单已被自提信息模板
+	 * @param array $data 替换的数据
+	 */
+	public static function takeselfGoods($data = null)
+	{
+		$templateString = "您好{user_name},订单号:{order_no},在{takeself}已经成功提货";
+		return strtr($templateString,$data);
+	}
+}

+ 353 - 0
src/classes/statistics.php

@@ -0,0 +1,353 @@
+<?php
+/**
+ * @copyright (c) 2014 aircheng
+ * @file statistics.php
+ * @brief 统计分析类库
+ * @author nswe
+ * @date 2014/7/27 11:09:43
+ * @version 1.0.0
+ */
+class statistics
+{
+	//日期单位
+	public static $dateUnit = '';
+
+	//日期格式
+	public static $format = 'Y-m-d';
+
+	/**
+	 * @brief 日期的智能处理
+	 * @param string $start 开始日期 Y-m-d
+	 * @param string $end   结束日期 Y-m-d
+	 */
+	public static function dateParse($start = '',$end = '')
+	{
+		//默认没有时间条件,查询之前7天的数据
+		if(!$start && !$end)
+		{
+			$diffSec = 86400 * 6;
+			$beforeDate = ITime::pass(-$diffSec,self::$format);
+			return array($beforeDate,ITime::getNow(self::$format));
+		}
+
+		//有时间条件
+		if($start && $end)
+		{
+			return array($start,$end);
+		}
+		else if($start)
+		{
+			return array($start,$start);
+		}
+		else if($end)
+		{
+			return array($end,$end);
+		}
+	}
+
+	/**
+	 * @brief 根据条件分组
+	 * @param int 相差的秒数
+	 * @return string y年,m月,d日
+	 */
+	private static function groupByCondition($diffSec)
+	{
+		$diffSec = abs($diffSec);
+		//按天分组,小于30个天
+		if($diffSec <= 86400 * 30)
+		{
+			return 'd';
+		}
+		//按月分组,小于24个月
+		else if($diffSec <= 86400 * 30 * 24)
+		{
+			return 'm';
+		}
+		//按年分组
+		else
+		{
+			return 'y';
+		}
+	}
+
+	/**
+	 * @brief 处理条件
+	 * @param IQuery $db 数据库IQuery对象
+	 * @param string $timeCols 时间字段名称
+	 * @param string $start 开始日期 Y-m-d
+	 * @param string $end   结束日期 Y-m-d
+	 */
+	private static function ParseCondition($db,$timeCols = 'time',$start = '',$end = '')
+	{
+		$result     = array();
+
+		//获取时间段
+		$date       = self::dateParse($start,$end);
+		$startArray = explode('-',$date[0]);
+		$endArray   = explode('-',$date[1]);
+		$diffSec    = ITime::getDiffSec($date[0],$date[1]);
+
+		switch(self::groupByCondition($diffSec))
+		{
+			//按照年
+			case "y":
+			{
+				$startCondition = $startArray[0];
+				$endCondition   = $endArray[0]+1;
+				$db->fields .= ',DATE_FORMAT(`'.$timeCols.'`,"%Y") as xValue';
+				$db->group   = "DATE_FORMAT(`".$timeCols."`,'%Y') having `".$timeCols."` >= '{$startCondition}' and `".$timeCols."` < '{$endCondition}'";
+			}
+			break;
+
+			//按照月
+			case "m":
+			{
+				$startCondition = $startArray[0].'-'.$startArray[1];
+				$endCondition   = $endArray[1] == 12 ? ($endArray[0]+1) : $endArray[0].'-'.($endArray[1]+1);
+				$db->fields .= ',DATE_FORMAT(`'.$timeCols.'`,"%Y-%m") as xValue';
+				$db->group   = "DATE_FORMAT(`".$timeCols."`,'%Y-%m') having `".$timeCols."` >= '{$startCondition}' and `".$timeCols."` < '{$endCondition}'";
+			}
+			break;
+
+			//按照日
+			case "d":
+			{
+				$startCondition = $startArray[0].'-'.$startArray[1].'-'.$startArray[2];
+				$endCondition   = $endArray[0].'-'.$endArray[1].'-'.$endArray[2].' 23:59:59';
+				$db->fields .= ',DATE_FORMAT(`'.$timeCols.'`,"%m-%d") as xValue';
+				$db->group   = "DATE_FORMAT(`".$timeCols."`,'%Y-%m-%d') having `".$timeCols."` >= '{$startCondition}' and `".$timeCols."` < '{$endCondition}'";
+			}
+			break;
+		}
+		$data = $db->find();
+		foreach($data as $key => $val)
+		{
+			$result[$val['xValue']] = intval($val['yValue']);
+		}
+		return $result;
+	}
+
+	/**
+	 * @brief 统计注册用户的数据
+	 * @param string $start 开始日期 Y-m-d
+	 * @param string $end   结束日期 Y-m-d
+	 * @return array array(日期时间 => 注册的人数);
+	 */
+	public static function userReg($start = '',$end = '')
+	{
+		$db = new IQuery('member');
+		$db->fields = 'count(*) as yValue,`time`';
+		return self::ParseCondition($db,'time',$start,$end);
+	}
+
+	/**
+	 * @brief 统计平均消费数据,读取 已经支付的订单状态,总金额/总订单量
+	 * @param string $start 开始日期 Y-m-d
+	 * @param string $end   结束日期 Y-m-d
+	 * @return array array(日期时间 => 消费金额);
+	 */
+	public static function spandAvg($start = '',$end = '')
+	{
+		$db = new IQuery('order');
+		$db->fields = 'sum(order_amount)/count(*) as yValue,`create_time`';
+		$db->where  = 'pay_status = 1';
+		return self::ParseCondition($db,'create_time',$start,$end);
+	}
+
+	/**
+	 * @brief 统计销售额数据
+	 * @param string $start 开始日期 Y-m-d
+	 * @param string $end   结束日期 Y-m-d
+	 * @return array key => 日期时间,value => 销售金额
+	 */
+	public static function spandAmount($start = '',$end = '')
+	{
+		$db = new IQuery('order');
+		$db->fields = 'sum(order_amount) as yValue,`create_time`';
+		$db->where  = 'pay_status = 1';
+		return self::ParseCondition($db,'create_time',$start,$end);
+	}
+
+	/**
+	 * @brief 获取商家销售额统计数据
+	 * @param int $seller_id 商家ID
+	 * @param string $start 开始日期 Y-m-d
+	 * @param string $end   结束日期 Y-m-d
+	 * @return array key => 日期时间,value => 销售金额
+	 */
+	public static function sellerAmount($seller_id,$start = '',$end = '')
+	{
+		$db = new IQuery('order');
+		$db->fields = 'sum(order_amount) as yValue,`create_time`';
+		$db->where  = "seller_id = {$seller_id} and pay_status = 1";
+		return self::ParseCondition($db,'create_time',$start,$end);
+	}
+
+	/**
+	 * @brief 获取商品统计数据
+	 * @param int $seller_id 商家ID
+	 * @return int
+	 */
+	public static function goodsCount($seller_id = '')
+	{
+		$where = "is_del != 1";
+		if($seller_id)
+		{
+			$where .= " and seller_id = {$seller_id} ";
+		}
+
+		$goodsDB = new IModel('goods');
+		$data = $goodsDB->getObj($where,'count(*) as num');
+		return isset($data['num']) ? $data['num'] : 0;
+	}
+
+	/**
+	 * @brief 等待商品咨询回复数量
+	 * @param int $seller_id 商家ID
+	 * @return int
+	 */
+	public static function referWaitCount($seller_id = '')
+	{
+		$where = "re.goods_id = go.id and re.status = 0";
+		if($seller_id)
+		{
+			$where .= " and go.seller_id = {$seller_id}";
+		}
+		$goodsDB = new IModel('refer as re,goods as go');
+		$data = $goodsDB->getObj($where,'count(*) as num');
+		return isset($data['num']) ? $data['num'] : 0;
+	}
+
+	/**
+	 * @brief 商品评论数量
+	 * @param int $seller_id 商家ID
+	 * @return int
+	 */
+	public static function commentCount($seller_id = '')
+	{
+		$where = "status = 1";
+		if($seller_id)
+		{
+			$where .= " and seller_id = {$seller_id}";
+		}
+		$goodsDB = new IModel('comment');
+		$data = $goodsDB->getObj($where,'count(*) as num');
+		return isset($data['num']) ? $data['num'] : 0;
+	}
+
+	/**
+	 * @brief 商品评论等待回复数量
+	 * @param int $seller_id 商家ID
+	 * @return int
+	 */
+	public static function commentWaitCount($seller_id = '')
+	{
+		$where = "status = 1 and recomment_time = 0";
+		if($seller_id)
+		{
+			$where .= " and seller_id = {$seller_id}";
+		}
+		$goodsDB = new IModel('comment');
+		$data = $goodsDB->getObj($where,'count(*) as num');
+		return isset($data['num']) ? $data['num'] : 0;
+	}
+
+	/**
+	 * @brief 商户的商品销售量
+	 * @param int $seller_id 商家ID
+	 * @return int
+	 */
+	public static function sellCountSeller($seller_id)
+	{
+		$sellerDB = new IModel('seller');
+		$dataRow = $sellerDB->getObj("id = {$seller_id}",'sale');
+		return isset($dataRow['sale']) ? intval($dataRow['sale']) : 0;
+	}
+
+	/**
+	 * @brief 商户的评分
+	 * @param int $seller_id 商家ID
+	 * @return int
+	 */
+	public static function gradeSeller($seller_id)
+	{
+		$sellerDB = new IModel('seller');
+		$dataRow = $sellerDB->getObj("id = {$seller_id}",'(grade/comments) as num');
+		return isset($dataRow['num']) ? round($dataRow['num']) : 0;
+	}
+
+	/**
+	 * @brief 统计用户待评论数据
+	 * @param int $user_id 用户ID
+	 * @return int
+	 */
+	public static function countUserWaitComment($user_id)
+	{
+		$commentDB = new IModel('comment');
+		$data      = $commentDB->getObj('user_id = '.$user_id.' and status = 0','count(id) as num');
+		return $data['num'];
+	}
+
+	/**
+	 * @brief 统计用户待付款数据
+	 * @param int $user_id 用户ID
+	 * @return int
+	 */
+	public static function countUserWaitPay($user_id)
+	{
+		$orderDB = new IModel('order');
+		$data    = $orderDB->getObj('user_id = '.$user_id.' and status = 1 and if_del = 0','count(id) as num');
+		return $data['num'];
+	}
+
+	/**
+	 * @brief 统计用户待确认数据
+	 * @param int $user_id 用户ID
+	 * @return int
+	 */
+	public static function countUserWaitCommit($user_id)
+	{
+		$orderDB = new IModel('order');
+		$data    = $orderDB->getObj('user_id = '.$user_id.' and status = 2 and distribution_status = 1 and if_del = 0','count(id) as num');
+		return $data['num'];
+	}
+
+	/**
+	 * @brief 统计用户待退款的申请
+	 * @param int $user_id 用户ID
+	 * @return int
+	 */
+	public static function countUserWaitRefund($user_id)
+	{
+		$orderDB = new IModel('refundment_doc');
+		$data    = $orderDB->getObj('user_id = '.$user_id.' and if_del = 0 and pay_status = 0','count(id) as num');
+		return $data['num'];
+	}
+
+	/**
+	 * @brief 统计退款申请的数量
+	 * @param int $seller_id
+	 */
+	public static function refundsCount($seller_id = '')
+	{
+		$refundDB = new IQuery('refundment_doc');
+		$where = 'pay_status = 0 and if_del = 0';
+		if($seller_id)
+		{
+			$where .= ' and seller_id = '.$seller_id;
+		}
+		$refundDB->where  = $where;
+		$refundDB->fields = 'count(*) as num';
+		$data = $refundDB->find();
+		return $data[0]['num'];
+	}
+
+	//[代金券]获取代金券数量
+	public static function getTicketCount($id)
+	{
+		$propObj   = new IModel('prop');
+		$where     = '`condition` = "'.$id.'"';
+		$propCount = $propObj->getObj($where,'count(*) as count');
+		return $propCount['count'];
+	}
+}

+ 139 - 0
src/classes/themeroute.php

@@ -0,0 +1,139 @@
+<?php
+/**
+ * @copyright (c) 2014 aircheng
+ * @file themeroute.php
+ * @brief 主题皮肤选择路由类
+ * @author nswe
+ * @date 2014/7/15 18:50:48
+ * @version 2.6
+ *
+ */
+class themeroute extends IInterceptorBase
+{
+	/**
+	 * @brief theme和skin进行选择
+	 */
+	public static function onCreateController($controller)
+	{
+		/**
+		 * 对于theme和skin的判断流程
+		 * 1,直接从URL中获取是否已经设定了方案__theme,__skin
+		 * 2,从cookie获取数据
+		 */
+		$urlTheme = IReq::get('__theme');
+		$urlSkin  = IReq::get('__skin');
+
+		if($urlTheme && $urlSkin && preg_match('|^\w+$|',$urlTheme) && preg_match('|^\w+$|',$urlSkin))
+		{
+			ISafe::set('__theme',$theme = $urlTheme);
+			ISafe::set('__skin',$skin  = $urlSkin);
+		}
+		elseif(ISafe::get('__theme') && ISafe::get('__skin'))
+		{
+			$theme = ISafe::get('__theme');
+			$skin  = ISafe::get('__skin');
+		}
+
+		if(isset($theme) && isset($skin))
+		{
+			$themePath = IWeb::$app->getViewPath().$theme."/".$controller->getId();
+			if(is_dir($themePath))
+			{
+				$controller->theme = $theme;
+				$controller->skin  = $skin;
+			}
+		}
+	}
+
+	/**
+	 * @brief 检查主题方案是否被应用
+	 * @param string $plan 方案名称
+	 * @return boolean
+	 */
+	public static function isThemeUsed($plan)
+	{
+		if(isset(IWeb::$app->config['theme']))
+		{
+			if(is_array(IWeb::$app->config['theme']))
+			{
+				foreach(IWeb::$app->config['theme'] as $client => $themeList)
+				{
+					if(array_key_exists($plan,$themeList))
+					{
+						return $themeList;
+					}
+				}
+			}
+		}
+		return false;
+	}
+
+	/**
+	 * @brief 检查皮肤方案是否被应用
+	 * @param string $theme 主题名称
+	 * @param string $plan 方案名称
+	 * @return boolean
+	 */
+	public static function isSkinUsed($theme,$plan)
+	{
+		$themeList = self::isThemeUsed($theme);
+		if($themeList)
+		{
+			if(in_array($plan,$themeList))
+			{
+				return true;
+			}
+		}
+		return false;
+	}
+
+	/**
+	 * @brief 获取主题方案的类型
+	 * @param string $theme 主题方案
+	 * @return 主题类型编号; 网站前台:site;后台管理:system;商家管理:seller;
+	 */
+    public static function themeType($theme)
+    {
+    	$list = array("site","system","seller");
+    	foreach($list as $key => $checkController)
+    	{
+    		$dirname = IWeb::$app->getViewPath().$theme."/".$checkController;
+    		if(is_dir($dirname))
+    		{
+				return $checkController;
+    		}
+    	}
+    	return "";
+    }
+
+	/**
+	 * @brief 根据主题类型编号返回名字字符串
+	 * @param string $type 主题类型名字
+	 * @return string 主题名称名字字符串
+	 */
+    public static function themeTypeTxt($type)
+    {
+    	$data = array("site" => "网站前台","system" => "后台管理","seller" => "商家管理");
+    	return isset($data[$type]) ? $data[$type] : "";
+    }
+
+	/**
+	 * @brief 获取不同类型主题方案的列表
+	 * @param string $type 主题类型
+	 * @return 主题列表; 网站前台:site;后台管理:system;商家管理:seller;
+	 */
+    public static function themeTypeList($type)
+    {
+    	$result   = array();
+    	$allTheme = Config::getSitePlan('theme');
+    	foreach($allTheme as $theme => $item)
+    	{
+    		if(self::themeType($theme) == $type)
+    		{
+    			$item['skin']   = Config::getSitePlan('skin',$theme);
+    			$result[$theme] = $item;
+    		}
+    	}
+    	return $result;
+    }
+}

+ 88 - 0
src/classes/thumb.php

@@ -0,0 +1,88 @@
+<?php
+/**
+ * @brief 动态生成缩略图类
+ */
+class Thumb
+{
+	//缩略图路径
+	public static $thumbDir = "runtime/_thumb/";
+
+	/**
+	 * @brief 获取缩略图物理路径
+	 */
+	public static function getThumbDir()
+	{
+		return IWeb::$app->getBasePath().self::$thumbDir;
+	}
+
+	/**
+	 * @brief 生成缩略图
+	 * @param string $imgSrc 图片路径
+	 * @param int $width 图片宽度
+	 * @param int $height 图片高度
+	 * @return string WEB图片路径名称
+	 */
+    public static function get($imgSrc,$width=100,$height=100)
+    {
+		//远程图片
+		if(strpos($imgSrc,"http") === 0)
+		{
+			$urlArray = parse_url($imgSrc);
+			if(!isset($urlArray['path']))
+			{
+				return;
+			}
+			//根据URL生成要保存的唯一路径
+			$extPad  = "";
+			$fileExt = pathinfo($imgSrc,PATHINFO_EXTENSION);
+			if($fileExt == "")
+			{
+				$extPad = ".jpg";
+			}
+			else if(!in_array(strtolower($fileExt),array("jpg","png","gif","tbi")))
+			{
+				return;
+			}
+			$dirname  = dirname($urlArray['path']);
+			$downFile = self::getThumbDir().trim($dirname,"/")."/".basename($imgSrc).$extPad;
+
+			//如果系统不存在此路径则直接下载
+			if(!is_file($downFile))
+			{
+				$ch = curl_init($imgSrc);
+				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+
+				$fileRes = new IFile($downFile,"w+");
+				$result  = $fileRes->write(curl_exec($ch));
+				if(!$result)
+				{
+					throw new IException($downFile." download fail");
+				}
+			}
+			$sourcePath = $downFile;
+		}
+		//本地图片
+		else
+		{
+			$sourcePath = IWeb::$app->getBasePath().$imgSrc;
+			if(is_file($sourcePath) == false)
+			{
+				return;
+			}
+			$dirname = dirname($imgSrc);
+		}
+
+		//缩略图文件名
+		$preThumb      = "{$width}_{$height}_";
+		$thumbFileName = $preThumb.basename($sourcePath);
+
+		//缩略图目录
+		$thumbDir    = self::getThumbDir().trim($dirname,"/")."/";
+		$webThumbDir = self::$thumbDir.trim($dirname,"/")."/";
+		if(is_file($thumbDir.$thumbFileName) == false)
+		{
+			IImage::thumb($sourcePath,$width,$height,$preThumb,$thumbDir);
+		}
+		return $webThumbDir.$thumbFileName;
+    }
+}

+ 52 - 0
src/classes/ticket.php

@@ -0,0 +1,52 @@
+<?php
+/**
+ * @brief 代金券类库
+ */
+class ticket
+{
+	/**
+	 * @brief 获取代金券状态数值
+	 * @param array $ticketRow 代金券数据
+	 * @return int 状态码 -1:已使用;-2:已禁用;-3:临时锁定;-4:已过期;1:可使用;
+	 */
+	public static function status($ticketRow)
+	{
+    	if($ticketRow['is_userd']==1)
+    	{
+    		return -1;
+    	}
+
+    	if($ticketRow['is_close']==1)
+    	{
+			return -2;
+    	}
+
+    	if($ticketRow['is_close']==2)
+    	{
+    		return -3;
+    	}
+
+    	if(ITime::getDateTime() > $ticketRow['end_time'])
+    	{
+    		return -4;
+    	}
+    	return 1;
+	}
+
+	/**
+	 * @brief 获取代金券的状态文字
+	 * @param int $status 状态码
+	 * @return string 状态文字
+	 */
+	public static function statusText($status)
+	{
+		$mapping = array(
+			"-1" => "已使用",
+			"-2" => "已禁用",
+			"-3" => "临时锁定",
+			"-4" => "已过期",
+			"1"  => "可使用",
+		);
+		return isset($mapping[$status]) ? $mapping[$status] : "未知";
+	}
+}

+ 594 - 0
src/classes/util.php

@@ -0,0 +1,594 @@
+<?php
+/**
+ * @copyright Copyright(c) 2011 aircheng.com
+ * @file util.php
+ * @brief 公共函数类
+ * @author kane
+ * @date 2011-01-13
+ * @version 0.6
+ * @note
+ */
+
+ /**
+ * @class Util
+ * @brief 公共函数类
+ */
+class Util
+{
+	/**
+	 * @brief 显示错误信息(dialog框)
+	 * @param string $message	错误提示字符串
+	 */
+	public static function showMessage($message)
+	{
+		echo '<script type="text/javascript">art.dialog.tips("'.$message.'")</script>';
+		exit;
+	}
+
+	/**
+	 * 处理二维数组
+	 *
+	 * 根据第二维某个索引的值来设置相应的第一维数组的key
+	 * 如原来是
+	 * array(array('id'=>'a','data'=>'') ,array('id'=>1000,'data'=>'')  )
+	 * 按照id索引处理后:
+	 * array('a'=>array('id'=>'a','data'=>'') ,1000=>array('id'=>1000,'data'=>'')  )
+	 *
+	 * @author walu
+	 * @param array $arr	待处理的二维数组
+	 * @param array $key	获取第二维值的索引
+	 * @return array
+	 */
+	public static function array_rekey($arr,$key='id')
+	{
+		$fun_re=array();
+		foreach($arr as $value)
+		{
+			$fun_re[$value[$key]]=$value;
+		}
+		return $fun_re;
+	}
+	//字符串拼接
+	public static function joinStr($id)
+	{
+		if(is_array($id))
+		{
+			$where = "id in (".join(',',$id).")";
+		}
+		else
+		{
+			$where = 'id = '.$id;
+		}
+		return $where;
+	}
+
+	/**
+	 * 商品价格格式化
+	 * @param $price float 商品价
+	 * @return float 格式化后的价格
+	 */
+	public static function priceFormat($price)
+	{
+		return round($price,2);
+	}
+
+	/**
+	 * 检索自动执行
+	 * @param array $search 查询拼接规则, key(字段) => like,likeValue(数据)
+	 */
+	public static function search($search)
+	{
+		$where = array(1);
+		if($search && is_array($search))
+		{
+			//like子句处理
+			if(isset($search['like']) && $search['likeValue'])
+			{
+				$search['like']      = IFilter::act($search['like'],"strict");
+				$search['likeValue'] = IFilter::act($search['likeValue']);
+
+				$where[] = $search['like']." like '%".$search['likeValue']."%' ";
+			}
+			unset($search['like']);
+			unset($search['likeValue']);
+
+			//自定义子句处理
+			foreach($search as $key => $val)
+			{
+				$key = IFilter::act($key,'strict');
+				$val = IFilter::act($val,'strict');
+
+				if($val === '' || $key === '' || $val == 'favicon.ico')
+				{
+					continue;
+				}
+
+				if( strpos($key,'num') !== false || in_array($val[0],array("<",">","=")) )
+				{
+					$where[] = $key." ".$val;
+				}
+				else
+				{
+					$where[] = $key."'".$val."'";
+				}
+			}
+		}
+		return join(" and ",$where);
+	}
+
+	/**
+	 * @brief 获取$_GET指定的参数
+	 * @param $urlKey 参数名称
+	 * @return mixed
+	 */
+	public static function getUrlParam($urlKey)
+	{
+		$tempGet = $_GET;
+		foreach($tempGet as $key => $val)
+		{
+			if($key != $urlKey)
+			{
+				unset($tempGet[$key]);
+			}
+		}
+		return $tempGet;
+	}
+
+	/**
+	 * @brief 计算折扣率
+	 * @param $originalPrice float 原价
+	 * @param $nowPrice float 现价
+	 * @return float 折扣数
+	 */
+	public static function discount($originalPrice,$nowPrice)
+	{
+		if($originalPrice >= $nowPrice)
+		{
+			return round($nowPrice/$originalPrice,2)*10;
+		}
+		return "";
+	}
+
+	/**
+	 * 商品检索
+	 * @param array $search 条件数组
+	 * @return string 拼接的WHERE条件语句
+	 */
+	public static function goodsSearch($search)
+	{
+		if (!$search)
+		{
+			return '';
+		}
+		$where = array();
+
+		// 商品名称
+		if(isset($search['name']))
+		{
+			$name = IFilter::act($search['name'], 'string');
+			if ('' != $name)
+			{
+				$where[] = "go.name like '%".$name."%' ";
+			}
+		}
+
+		// 商品货号
+		if (isset($search['goods_no']) && !empty($search['goods_no']))
+		{
+			$goods_no = IFilter::act($search['goods_no'], 'string');
+			if ('' != $goods_no)
+			{
+				$where[] = "go.goods_no like '%".$goods_no."%' ";
+			}
+		}
+
+		// 商品分类
+		if (isset($search['category_id']) && !empty($search['category_id']))
+		{
+			$category_id = IFilter::act($search['category_id'], 'int');
+			if (0 < $category_id)
+			{
+				$where[] = "ce.category_id='$category_id' ";
+			}
+		}
+
+		// 商品状态
+		if (isset($search['is_del']) && '' != $search['is_del'])
+		{
+			$is_del = IFilter::act($search['is_del'], 'int');
+			if (in_array($is_del, array(0,2,3)))
+			{
+				$where[] = "go.is_del='$is_del' ";
+			}
+		}
+
+		// 商品库存
+		if (isset($search['store_nums']) && '' != $search['store_nums'])
+		{
+			$store_nums = IFilter::act($search['store_nums'], 'int');
+			switch ($store_nums)
+			{
+				case 0:
+					// 无货
+					$where[] = "go.store_nums<1 ";
+					break;
+				case 1:
+					// 低于10
+					$where[] = "go.store_nums>=1 and go.store_nums<10 ";
+					break;
+				case 2:
+					// 10-100
+					$where[] = "go.store_nums>=10 and go.store_nums<100 ";
+					break;
+				case 3:
+					// 100以上
+					$where[] = "go.store_nums>100 ";
+					break;
+			}
+		}
+
+		// 商品品牌
+		if (isset($search['brand_id']) && '' != $search['brand_id'])
+		{
+			$brand_id = IFilter::act($search['brand_id'], 'int');
+			if (0 < $brand_id)
+			{
+				$where[] = "go.brand_id='$brand_id' ";
+			}
+		}
+
+		// 商品价格
+		if (isset($search['sell_price_start']) && '' != $search['sell_price_start'])
+		{
+			$sell_price_start = IFilter::act($search['sell_price_start'], 'float');
+		}
+		else
+		{
+			$sell_price_start = 0;
+		}
+		if (isset($search['sell_price_end']) && '' != $search['sell_price_end'])
+		{
+			$sell_price_end = IFilter::act($search['sell_price_end'], 'float');
+		}
+		else
+		{
+			$sell_price_end = 0;
+		}
+		if (0 == $sell_price_start && 0 == $sell_price_end)
+		{
+			// 无效条件
+		}
+		else
+		{
+			if ($sell_price_start == $sell_price_end)
+			{
+				$where[] = "go.sell_price='$sell_price_start' ";
+			}
+			elseif ($sell_price_start > $sell_price_end)
+			{
+				$where[] = "go.sell_price between $sell_price_end and $sell_price_start ";
+			}
+			else
+			{
+				$where[] = "go.sell_price between $sell_price_start and $sell_price_end ";
+			}
+		}
+
+		// 创建时间
+		if (isset($search['create_time_start']) && '' != $search['create_time_start'])
+		{
+			$create_time_start = IFilter::act($search['create_time_start'], 'string');
+			// 验证日期
+			$is_check_create_time_start = ITime::checkDateTime($create_time_start);
+		}
+		else
+		{
+			$is_check_create_time_start = false;
+		}
+		if (isset($search['create_time_end']) && '' != $search['create_time_end'])
+		{
+			$create_time_end = IFilter::act($search['create_time_end'], 'string');
+			// 验证日期
+			$is_check_create_time_end = ITime::checkDateTime($create_time_end);
+		}
+		else
+		{
+			$is_check_create_time_end = false;
+		}
+		if ($is_check_create_time_start && $is_check_create_time_end)
+		{
+			if ($create_time_start == $create_time_end)
+			{
+				$where[] = "go.create_time between '".$create_time_start." 00:00:00' and '".$create_time_start." 23:59:59' ";
+			}
+			else
+			{
+				$difference = ITime::getDiffSec($create_time_start.' 00:00:00', $create_time_end.' 00:00:00');
+				if (0 < $difference)
+				{
+					$where[] = "go.create_time between '".$create_time_end." 00:00:00' and '".$create_time_start." 23:59:59' ";
+				}
+				else
+				{
+					$where[] = "go.create_time between '".$create_time_start." 00:00:00' and '".$create_time_end." 23:59:59' ";
+				}
+			}
+		}
+		elseif ($is_check_create_time_start && false == $is_check_create_time_end)
+		{
+			$where[] = "go.create_time between '".$create_time_start." 00:00:00' and '".$create_time_start." 23:59:59' ";
+		}
+		elseif (false == $is_check_create_time_start && $is_check_create_time_end)
+		{
+			$where[] = "go.create_time between '".$create_time_end." 00:00:00' and '".$create_time_end." 23:59:59' ";
+		}
+		else
+		{
+			// 无效条件
+		}
+
+		return implode(" and ", $where);
+	}
+
+	/**
+	 * 订单检索
+	 * @param array $search 条件数组
+	 * @return string 拼接的WHERE条件语句
+	 */
+	public static function orderSearch($search)
+	{
+		if (!$search)
+		{
+			return '';
+		}
+		$where = array();
+
+		// 订单号
+		if (isset($search['order_no']) && '' != $search['order_no'])
+		{
+			$order_no = IFilter::act($search['order_no'], 'string');
+			if ('' != $order_no)
+			{
+				$where[] = "o.order_no='$order_no' ";
+			}
+		}
+
+		// 收货人
+		if (isset($search['accept_name']) && '' != $search['accept_name'])
+		{
+			$accept_name = IFilter::act($search['accept_name'], 'string');
+			if ('' != $accept_name)
+			{
+				$where[] = "o.accept_name='$accept_name' ";
+			}
+		}
+
+		// 支付状态
+		if (isset($search['pay_status']) && '' != $search['pay_status'])
+		{
+			$pay_status = IFilter::act($search['pay_status'], 'int');
+			if (in_array($pay_status, array(0,1,2)))
+			{
+				$where[] = "o.pay_status='$pay_status' ";
+			}
+		}
+
+		// 发货状态
+		if (isset($search['distribution_status']) && '' != $search['distribution_status'])
+		{
+			$distribution_status = IFilter::act($search['distribution_status'], 'int');
+			if (in_array($distribution_status, array(0,1,2)))
+			{
+				$where[] = "o.distribution_status='$distribution_status' ";
+			}
+		}
+
+		// 订单状态
+		if (isset($search['status']) && '' != $search['status'])
+		{
+			$status = IFilter::act($search['status'], 'int');
+			if (in_array($status, array(1,2,3,4,5)))
+			{
+				$where[] = "o.status='$status' ";
+			}
+		}
+
+		// 订单总额
+		if (isset($search['order_amount_start']) && '' != $search['order_amount_start'])
+		{
+			$order_amount_start = IFilter::act($search['order_amount_start'], 'float');
+		}
+		else
+		{
+			$order_amount_start = 0;
+		}
+		if (isset($search['order_amount_end']) && '' != $search['order_amount_end'])
+		{
+			$order_amount_end = IFilter::act($search['order_amount_end'], 'float');
+		}
+		else
+		{
+			$order_amount_end = 0;
+		}
+		if (0 == $order_amount_start && 0 == $order_amount_end)
+		{
+			// 无效条件
+		}
+		else
+		{
+			if ($order_amount_start == $order_amount_end)
+			{
+				$where[] = "o.order_amount='$order_amount_start' ";
+			}
+			elseif ($order_amount_start > $order_amount_end)
+			{
+				$where[] = "o.order_amount between $order_amount_end and $order_amount_start ";
+			}
+			else
+			{
+				$where[] = "o.order_amount between $order_amount_start and $order_amount_end ";
+			}
+		}
+
+		// 下单时间
+		if (isset($search['create_time_start']) && '' != $search['create_time_start'])
+		{
+			$create_time_start = IFilter::act($search['create_time_start'], 'string');
+			// 验证日期
+			$is_check_create_time_start = ITime::checkDateTime($create_time_start);
+		}
+		else
+		{
+			$is_check_create_time_start = false;
+		}
+		if (isset($search['create_time_end']) && '' != $search['create_time_end'])
+		{
+			$create_time_end = IFilter::act($search['create_time_end'], 'string');
+			// 验证日期
+			$is_check_create_time_end = ITime::checkDateTime($create_time_end);
+		}
+		else
+		{
+			$is_check_create_time_end = false;
+		}
+		if ($is_check_create_time_start && $is_check_create_time_end)
+		{
+			if ($create_time_start == $create_time_end)
+			{
+				$where[] = "o.create_time between '".$create_time_start." 00:00:00' and '".$create_time_start." 23:59:59' ";
+			}
+			else
+			{
+				$difference = ITime::getDiffSec($create_time_start.' 00:00:00', $create_time_end.' 00:00:00');
+				if (0 < $difference)
+				{
+					$where[] = "o.create_time between '".$create_time_end." 00:00:00' and '".$create_time_start." 23:59:59' ";
+				}
+				else
+				{
+					$where[] = "o.create_time between '".$create_time_start." 00:00:00' and '".$create_time_end." 23:59:59' ";
+				}
+			}
+		}
+		elseif ($is_check_create_time_start && false == $is_check_create_time_end)
+		{
+			$where[] = "o.create_time between '".$create_time_start." 00:00:00' and '".$create_time_start." 23:59:59' ";
+		}
+		elseif (false == $is_check_create_time_start && $is_check_create_time_end)
+		{
+			$where[] = "o.create_time between '".$create_time_end." 00:00:00' and '".$create_time_end." 23:59:59' ";
+		}
+		else
+		{
+			// 无效条件
+		}
+
+		// 发货时间
+		if (isset($search['send_time_start']) && '' != $search['send_time_start'])
+		{
+			$send_time_start = IFilter::act($search['send_time_start'], 'string');
+			// 验证日期
+			$is_check_send_time_start = ITime::checkDateTime($send_time_start);
+		}
+		else
+		{
+			$is_check_send_time_start = false;
+		}
+		if (isset($search['send_time_end']) && '' != $search['send_time_end'])
+		{
+			$send_time_end = IFilter::act($search['send_time_end'], 'string');
+			// 验证日期
+			$is_check_send_time_end = ITime::checkDateTime($send_time_end);
+		}
+		else
+		{
+			$is_check_send_time_end = false;
+		}
+		if ($is_check_send_time_start && $is_check_send_time_end)
+		{
+			if ($send_time_start == $send_time_end)
+			{
+				$where[] = "o.send_time between '".$send_time_start." 00:00:00' and '".$send_time_start." 23:59:59' ";
+			}
+			else
+			{
+				$difference = ITime::getDiffSec($send_time_start.' 00:00:00', $send_time_end.' 00:00:00');
+				if (0 < $difference)
+				{
+					$where[] = "o.send_time between '".$send_time_end." 00:00:00' and '".$send_time_start." 23:59:59' ";
+				}
+				else
+				{
+					$where[] = "o.send_time between '".$send_time_start." 00:00:00' and '".$send_time_end." 23:59:59' ";
+				}
+			}
+		}
+		elseif ($is_check_send_time_start && false == $is_check_send_time_end)
+		{
+			$where[] = "o.send_time between '".$send_time_start." 00:00:00' and '".$send_time_start." 23:59:59' ";
+		}
+		elseif (false == $is_check_send_time_start && $is_check_send_time_end)
+		{
+			$where[] = "o.send_time between '".$send_time_end." 00:00:00' and '".$send_time_end." 23:59:59' ";
+		}
+		else
+		{
+			// 无效条件
+		}
+
+		// 完成时间
+		if (isset($search['completion_time_start']) && '' != $search['completion_time_start'])
+		{
+			$completion_time_start = IFilter::act($search['completion_time_start'], 'string');
+			// 验证日期
+			$is_check_completion_time_start = ITime::checkDateTime($completion_time_start);
+		}
+		else
+		{
+			$is_check_completion_time_start = false;
+		}
+		if (isset($search['completion_time_end']) && '' != $search['completion_time_end'])
+		{
+			$completion_time_end = IFilter::act($search['completion_time_end'], 'string');
+			// 验证日期
+			$is_check_completion_time_end = ITime::checkDateTime($completion_time_end);
+		}
+		else
+		{
+			$is_check_completion_time_end = false;
+		}
+		if ($is_check_completion_time_start && $is_check_completion_time_end)
+		{
+			if ($completion_time_start == $completion_time_end)
+			{
+				$where[] = "o.completion_time between '".$completion_time_start." 00:00:00' and '".$completion_time_start." 23:59:59' ";
+			}
+			else
+			{
+				$difference = ITime::getDiffSec($completion_time_start.' 00:00:00', $completion_time_end.' 00:00:00');
+				if (0 < $difference)
+				{
+					$where[] = "o.completion_time between '".$completion_time_end." 00:00:00' and '".$completion_time_start." 23:59:59' ";
+				}
+				else
+				{
+					$where[] = "o.completion_time between '".$completion_time_start." 00:00:00' and '".$completion_time_end." 23:59:59' ";
+				}
+			}
+		}
+		elseif ($is_check_completion_time_start && false == $is_check_completion_time_end)
+		{
+			$where[] = "o.completion_time between '".$completion_time_start." 00:00:00' and '".$completion_time_start." 23:59:59' ";
+		}
+		elseif (false == $is_check_completion_time_start && $is_check_completion_time_end)
+		{
+			$where[] = "o.completion_time between '".$completion_time_end." 00:00:00' and '".$completion_time_end." 23:59:59' ";
+		}
+		else
+		{
+			// 无效条件
+		}
+
+		return implode(" and ", $where);
+	}
+}

+ 2 - 0
src/config/.htaccess

@@ -0,0 +1,2 @@
+Order deny,allow
+Deny from all

+ 67 - 0
src/config/config.php

@@ -0,0 +1,67 @@
+<?php return array (
+  'logs' => 
+  array (
+    'path' => 'backup/logs',
+    'type' => 'file',
+  ),
+  'DB' => 
+  array (
+    'type' => 'mysqli',
+    'tablePre' => 'iwebshop_',
+    'read' => 
+    array (
+      0 => 
+      array (
+        'host' => 'localhost:3306',
+        'user' => 'shop',
+        'passwd' => 'Shopabc-123',
+        'name' => 'shop',
+      ),
+    ),
+    'write' => 
+    array (
+      'host' => 'localhost:3306',
+      'user' => 'shop',
+      'passwd' => 'Shopabc-123',
+      'name' => 'shop',
+    ),
+  ),
+  'interceptor' => 
+  array (
+    0 => 'themeroute@onCreateController',
+    1 => 'layoutroute@onCreateView',
+    2 => 'plugin',
+  ),
+  'langPath' => 'language',
+  'viewPath' => 'views',
+  'skinPath' => 'skin',
+  'classes' => 'classes.*',
+  'rewriteRule' => 'url',
+  'theme' => 
+  array (
+    'pc' => 
+    array (
+      'sysdefault' => 'green',
+      'sysseller' => 'green',
+      'default' => 'blue',
+    ),
+    'mobile' => 
+    array (
+      'sysdefault' => 'default',
+      'sysseller' => 'default',
+      'default' => 'blue',
+    ),
+  ),
+  'timezone' => 'Etc/GMT-8',
+  'upload' => 'upload',
+  'dbbackup' => 'backup/database',
+  'safe' => 'cookie',
+  'lang' => 'zh_sc',
+  'debug' => '0',
+  'configExt' => 
+  array (
+    'site_config' => 'config/site_config.php',
+  ),
+  'encryptKey' => '65abe4cfbabea8c25f7c15e08e757573',
+  'authorizeCode' => '20170830491243158',
+)?>

+ 35 - 0
src/config/config_default.php

@@ -0,0 +1,35 @@
+<?php
+return array(
+	'logs'=>array(
+		'path'=>'backup/logs',
+		'type'=>'file'
+	),
+	'DB'=>array(
+		'type'=>'mysqli',
+        'tablePre'=>'{TABLE_PREFIX}',
+		'read'=>array(
+			array('host'=>'{DB_R_ADDRESS}','user'=>'{DB_R_USER}','passwd'=>'{DB_R_PWD}','name'=>'{DB_R_NAME}'),
+		),
+
+		'write'=>array(
+			'host'=>'{DB_W_ADDRESS}','user'=>'{DB_W_USER}','passwd'=>'{DB_W_PWD}','name'=>'{DB_W_NAME}',
+		),
+	),
+	'interceptor' => array('themeroute@onCreateController','layoutroute@onCreateView','plugin'),
+	'langPath' => 'language',
+	'viewPath' => 'views',
+	'skinPath' => 'skin',
+    'classes' => 'classes.*',
+    'rewriteRule' =>'url',
+	'theme' => array('pc' => array('default' => 'default','sysdefault' => 'green','sysseller' => 'green'),'mobile' => array('mobile' => 'default','sysdefault' => 'default','sysseller' => 'default')),
+	'timezone'	=> 'Etc/GMT-8',
+	'upload' => 'upload',
+	'dbbackup' => 'backup/database',
+	'safe' => 'cookie',
+	'lang' => 'zh_sc',
+	'debug'=> '0',
+	'configExt'=> array('site_config'=>'config/site_config.php'),
+	'encryptKey'=>'{ENCRYPTKEY}',
+	'authorizeCode' => '20170830491243158',
+);
+?>

+ 44 - 0
src/config/site_config.php

@@ -0,0 +1,44 @@
+<?php return array (
+  'email_type' => '1',
+  'email_safe' => '',
+  'mail_address' => '',
+  'smtp' => '',
+  'smtp_user' => '',
+  'smtp_pwd' => '',
+  'smtp_port' => '',
+  'order_by' => 'new',
+  'name' => '中网B2C商城',
+  'url' => 'http://zwshop.ds-bay.com',
+  'master' => '',
+  'qq' => '',
+  'email' => '',
+  'mobile' => '',
+  'phone' => '',
+  'address' => '',
+  'site_footer_code' => '<div class="footer" style="text-align:center"><p class="links"><a href="">关于我们</a>|<a href="">常见问题</a>|<a href="">安全交易</a>|<a href="">购买流程</a>|<a href="">如何付款</a>|<a href="">联系我们</a>|<a href="">合作提案</a></p><p class="copyright">Powered by <a href="http://www.aircheng.com">iWebShop</a></p>Copyright © 2005-2014 <a class="copyys" target="_blank" href="http://www.miibeian.gov.cn/">鲁ICP备01000010号</a></div>',
+  'tax' => '10',
+  'stockup_time' => '1',
+  'index_seo_title' => '中网B2C商城系统',
+  'index_seo_keywords' => '开源商城系统,开源网店系统,开源电子商务,商城系统源码,多用户商城源码',
+  'index_seo_description' => '中网B2C商城系统',
+  'goods_no_pre' => 'SD',
+  'commission' => '',
+  'store_num_warning' => '1',
+  'reg_option' => '0',
+  'guide_name' => 
+  array (
+    0 => '产品官网',
+    1 => '食品酒类',
+    2 => '化妆品',
+    3 => '商家管理',
+    4 => '后台管理',
+  ),
+  'guide_link' => 
+  array (
+    0 => 'http://zwshop.ds-bay.com/',
+    1 => 'http://zwshop.ds-bay.com/',
+    2 => 'http://zwshop.ds-bay.com/',
+    3 => 'seller/index',
+    4 => 'systemadmin/index',
+  ),
+)?>

+ 2 - 0
src/controllers/.htaccess

@@ -0,0 +1,2 @@
+Order deny,allow
+Deny from all

+ 700 - 0
src/controllers/block.php

@@ -0,0 +1,700 @@
+<?php
+/**
+ * @brief 公共模块
+ * @class Block
+ */
+class Block extends IController
+{
+	public $layout='';
+
+	public function init()
+	{
+
+	}
+
+ 	/**
+	 * @brief Ajax获取规格值
+	 */
+	function spec_value_list()
+	{
+		// 获取POST数据
+		$spec_id = IFilter::act(IReq::get('id'),'int');
+
+		//初始化spec商品模型规格表类对象
+		$specObj = new IModel('spec');
+		//根据规格编号 获取规格详细信息
+		$specData = $specObj->getObj("id = ".$spec_id." and is_del = 0");
+		if($specData)
+		{
+			echo JSON::encode($specData);
+		}
+		else
+		{
+			//返回失败标志
+			echo '';
+		}
+	}
+
+	//列出筛选商品
+	function goods_list()
+	{
+		//商品检索条件
+		$show_num    = IFilter::act( IReq::get('show_num'),'int');
+		$keywords    = IFilter::act( IReq::get('keywords') );
+		$cat_id      = IFilter::act( IReq::get('category_id'),'int');
+		$min_price   = IFilter::act( IReq::get('min_price'),'float');
+		$max_price   = IFilter::act( IReq::get('max_price'),'float');
+		$goods_no    = IFilter::act( IReq::get('goods_no'));
+		$is_products = IFilter::act( IReq::get('is_products'),'int');
+		$seller_id   = IFilter::act( IReq::get('seller_id'),'int');
+		$goods_id    = IFilter::act( IReq::get('goods_id'),'int');
+
+		//货号处理 商品货号或者货品货号2种情况
+		if($goods_no)
+		{
+			$productDB   = new IModel('products');
+			$productData = $productDB->query("products_no = '".$goods_no."'");
+			if($productData)
+			{
+				foreach($productData as $key => $item)
+				{
+					$goods_id .= ",".$item['goods_id'];
+				}
+				//找到货品后清空货号数据
+				$goods_no = "";
+			}
+		}
+
+		//查询条件
+		$table_name = 'goods as go';
+		$fields     = 'go.id as goods_id,go.name,go.img,go.store_nums,go.goods_no,go.sell_price,go.spec_array';
+
+		$where   = 'go.is_del = 0';
+		$where  .= $goods_id  ? ' and go.id          in ('.$goods_id.')' : '';
+		$where  .= $seller_id ? ' and go.seller_id    = '.$seller_id     : '';
+		$where  .= $goods_no  ? ' and go.goods_no     = "'.$goods_no.'"' : '';
+		$where  .= $min_price ? ' and go.sell_price  >= '.$min_price     : '';
+		$where  .= $max_price ? ' and go.sell_price  <= '.$max_price     : '';
+		$where  .= $keywords  ? ' and go.name like    "%'.$keywords.'%"' : '';
+
+		//分类筛选
+		if($cat_id)
+		{
+			$table_name .= ' ,category_extend as ca ';
+			$where      .= " and ca.category_id = {$cat_id} and go.id = ca.goods_id ";
+		}
+
+		//获取商品数据
+		$goodsDB = new IModel($table_name);
+		$data    = $goodsDB->query($where,$fields,'go.id desc',$show_num);
+
+		//包含货品信息
+		if($is_products)
+		{
+			if($data)
+			{
+				$goodsIdArray = array();
+				foreach($data as $key => $val)
+				{
+					//有规格有货品
+					if($val['spec_array'])
+					{
+						$goodsIdArray[$key] = $val['goods_id'];
+						unset($data[$key]);
+					}
+				}
+
+				if($goodsIdArray)
+				{
+					$productFields = "pro.goods_id,go.name,go.img,pro.id as product_id,pro.products_no as goods_no,pro.spec_array,pro.sell_price,pro.store_nums";
+					$productDB     = new IModel('goods as go,products as pro');
+					$productDate   = $productDB->query('go.id = pro.goods_id and pro.goods_id in('.join(',',$goodsIdArray).')',$productFields);
+					$data = array_merge($data,$productDate);
+				}
+			}
+		}
+
+		$this->data = $data;
+		$this->type = IFilter::act(IReq::get('type'));//页面input的type类型,比如radio,checkbox
+		$this->redirect('goods_list');
+	}
+	/**
+	 * @brief 获取地区
+	 */
+	public function area_child()
+	{
+		$parent_id = intval(IReq::get("aid"));
+		$areaDB    = new IModel('areas');
+		$data      = $areaDB->query("parent_id=$parent_id",'*','sort asc');
+		echo JSON::encode($data);
+	}
+
+    //[公共方法]通过解析products,goods表中的spec_array转化为格式:key:规格名称;value:规格值
+    public static function show_spec($specJson,$param = array())
+    {
+    	$specArray = JSON::decode($specJson);
+    	$spec      = array();
+    	if($specArray)
+    	{
+    		$imgSize = isset($param['size']) ? $param['size'] : 20;
+	    	foreach($specArray as $val)
+	    	{
+	    		//goods表规格数据
+	    		if(is_array($val['value']))
+	    		{
+	    			foreach($val['value'] as $tip => $sval)
+	    			{
+	    				if(!isset($spec[$val['name']]))
+	    				{
+	    					$spec[$val['name']] = array();
+	    				}
+
+	    				list($tip,$specVal) = each($sval);
+
+			    		if($val['type'] == 1)
+			    		{
+			    			$spec[$val['name']][] = $specVal;
+			    		}
+			    		else
+			    		{
+			    			$spec[$val['name']][] = strlen($tip) >= 3 ? $tip : '<img src="'.IUrl::creatUrl($specVal).'" style="border: 1px solid #ddd;width:'.$imgSize.'px;height:'.$imgSize.'px;" title="'.$tip.'" />';
+			    		}
+	    			}
+	    			$spec[$val['name']] = join("&nbsp;&nbsp;",$spec[$val['name']]);
+	    		}
+	    		//goods表老版本格式逗号分隔符
+	    		else if(strpos($val['value'],",") && $val['value'] = explode(",",$val['value']))
+	    		{
+	    			foreach($val['value'] as $tip => $sval)
+	    			{
+	    				if(!isset($spec[$val['name']]))
+	    				{
+	    					$spec[$val['name']] = array();
+	    				}
+
+			    		if($val['type'] == 1)
+			    		{
+			    			$spec[$val['name']][] = $sval;
+			    		}
+			    		else
+			    		{
+			    			$spec[$val['name']][] = '<img src="'.IUrl::creatUrl($sval).'" style="border: 1px solid #ddd;width:'.$imgSize.'px;height:'.$imgSize.'px;" />';
+			    		}
+	    			}
+	    			$spec[$val['name']] = join("&nbsp;&nbsp;",$spec[$val['name']]);
+	    		}
+	    		//products表规格数据
+	    		else
+	    		{
+		    		if($val['type'] == 1)
+		    		{
+		    			$spec[$val['name']] = $val['value'];
+		    		}
+		    		else
+		    		{
+		    			$tip = isset($val['tip']) ? $val['tip'] : "";
+		    			$spec[$val['name']] = strlen($tip) >= 3 ? $tip : '<img src="'.IUrl::creatUrl($val['value']).'" style="border: 1px solid #ddd;width:'.$imgSize.'px;height:'.$imgSize.'px;" title="'.$tip.'" />';
+		    		}
+	    		}
+	    	}
+    	}
+    	return $spec;
+    }
+	/**
+	 * @brief 获得配送方式ajax
+	 */
+	public function order_delivery()
+    {
+    	$productId    = IFilter::act(IReq::get("productId"),'int');
+    	$goodsId      = IFilter::act(IReq::get("goodsId"),'int');
+    	$province     = IFilter::act(IReq::get("province"),'int');
+    	$distribution = IFilter::act(IReq::get("distribution"),'int');
+    	$num          = IReq::get("num") ? IFilter::act(IReq::get("num"),'int') : 1;
+		$data         = array();
+		if($distribution)
+		{
+			$data = Delivery::getDelivery($province,$distribution,$goodsId,$productId,$num);
+		}
+		else
+		{
+			$delivery     = new IModel('delivery');
+			$deliveryList = $delivery->query('is_delete = 0 and status = 1');
+			foreach($deliveryList as $key => $item)
+			{
+				$data[$item['id']] = Delivery::getDelivery($province,$item['id'],$goodsId,$productId,$num);
+			}
+		}
+    	echo JSON::encode($data);
+    }
+	/**
+    * @brief 【重要】进行支付支付方法
+    */
+	public function doPay()
+	{
+		//获得相关参数
+		$order_id   = IReq::get('order_id');
+		$recharge   = IReq::get('recharge');
+		$payment_id = IFilter::act(IReq::get('payment_id'),'int');
+
+		if($order_id)
+		{
+			$order_id = explode("_",IReq::get('order_id'));
+			$order_id = IFilter::act($order_id,'int');
+
+			//获取订单信息
+			$orderDB  = new IModel('order');
+			$orderRow = $orderDB->getObj('id = '.current($order_id));
+
+			if(empty($orderRow))
+			{
+				IError::show(403,'要支付的订单信息不存在');
+			}
+
+			//判断订单是否已经支付成功了
+			if($orderRow['pay_status'] == 1)
+			{
+				plugin::trigger('setCallback','/ucenter/order');
+				$this->redirect('/site/success/message/'.urlencode("订单已经支付成功"));
+				return;
+			}
+
+			$payment_id = $orderRow['pay_type'];
+		}
+
+		//获取支付方式类库
+		$paymentInstance = Payment::createPaymentInstance($payment_id);
+
+		//在线充值
+		if($recharge !== null)
+		{
+			$recharge   = IFilter::act($recharge,'float');
+			$paymentRow = Payment::getPaymentById($payment_id);
+
+			//account:充值金额; paymentName:支付方式名字
+			$reData   = array('account' => $recharge , 'paymentName' => $paymentRow['name']);
+			$sendData = $paymentInstance->getSendData(Payment::getPaymentInfo($payment_id,'recharge',$reData));
+		}
+		//订单支付
+		else if($order_id)
+		{
+			$sendData = $paymentInstance->getSendData(Payment::getPaymentInfo($payment_id,'order',$order_id));
+		}
+		else
+		{
+			IError::show(403,'发生支付错误');
+		}
+
+		$paymentInstance->doPay($sendData);
+	}
+
+	/**
+     * @brief 【重要】支付回调[同步]
+	 */
+	public function callback()
+	{
+		//从URL中获取支付方式
+		$payment_id      = IFilter::act(IReq::get('_id'),'int');
+		$paymentInstance = Payment::createPaymentInstance($payment_id);
+
+		if(!is_object($paymentInstance))
+		{
+			IError::show(403,'支付方式不存在');
+		}
+
+		//初始化参数
+		$money   = '';
+		$message = '支付失败';
+		$orderNo = '';
+
+		//执行接口回调函数
+		$callbackData = array_merge($_POST,$_GET);
+		unset($callbackData['controller']);
+		unset($callbackData['action']);
+		unset($callbackData['_id']);
+		$return = $paymentInstance->callback($callbackData,$payment_id,$money,$message,$orderNo);
+
+		//支付成功
+		if($return == 1)
+		{
+			//充值方式
+			if(stripos($orderNo,'recharge') !== false)
+			{
+				$tradenoArray = explode('recharge',$orderNo);
+				$recharge_no  = isset($tradenoArray[1]) ? $tradenoArray[1] : 0;
+				if(payment::updateRecharge($recharge_no))
+				{
+					plugin::trigger('setCallback','/ucenter/account_log');
+					$this->redirect('/site/success/message/'.urlencode("充值成功"));
+					return;
+				}
+				IError::show(403,'充值失败');
+			}
+			else
+			{
+				//订单批量结算缓存机制
+				$moreOrder = Order_Class::getBatch($orderNo);
+				if($money >= array_sum($moreOrder))
+				{
+					foreach($moreOrder as $key => $item)
+					{
+						$order_id = Order_Class::updateOrderStatus($key);
+						if(!$order_id)
+						{
+							IError::show(403,'订单修改失败');
+						}
+					}
+					plugin::trigger('setCallback','/ucenter/order');
+					$this->redirect('/site/success/message/'.urlencode("支付成功"));
+					return;
+				}
+				$message = '付款金额与订单金额不符合';
+			}
+		}
+		//支付失败
+		$message = $message ? $message : '支付失败';
+		IError::show(403,$message);
+	}
+
+	/**
+     * @brief 【重要】支付回调[异步]
+	 */
+	function server_callback()
+	{
+		//从URL中获取支付方式
+		$payment_id      = IFilter::act(IReq::get('_id'),'int');
+		$paymentInstance = Payment::createPaymentInstance($payment_id);
+
+		if(!is_object($paymentInstance))
+		{
+			die('fail');
+		}
+
+		//初始化参数
+		$money   = '';
+		$message = '支付失败';
+		$orderNo = '';
+
+		//执行接口回调函数
+		$callbackData = array_merge($_POST,$_GET);
+		unset($callbackData['controller']);
+		unset($callbackData['action']);
+		unset($callbackData['_id']);
+		$return = $paymentInstance->serverCallback($callbackData,$payment_id,$money,$message,$orderNo);
+
+		//支付成功
+		if($return == 1)
+		{
+			//充值方式
+			if(stripos($orderNo,'recharge') !== false)
+			{
+				$tradenoArray = explode('recharge',$orderNo);
+				$recharge_no  = isset($tradenoArray[1]) ? $tradenoArray[1] : 0;
+				if(payment::updateRecharge($recharge_no))
+				{
+					$paymentInstance->notifyStop();
+				}
+			}
+			else
+			{
+				//订单批量结算缓存机制
+				$moreOrder = Order_Class::getBatch($orderNo);
+				if($money >= array_sum($moreOrder))
+				{
+					foreach($moreOrder as $key => $item)
+					{
+						$order_id = Order_Class::updateOrderStatus($key);
+						if(!$order_id)
+						{
+							throw new IException("异步支付回调修改状态错误,订单ID:".$order_id);
+						}
+					}
+					$paymentInstance->notifyStop();
+				}
+			}
+		}
+		//支付失败
+		else
+		{
+			die('fail');
+		}
+	}
+
+	/**
+     * @brief 【重要】支付中断处理
+	 */
+	public function merchant_callback()
+	{
+		$this->redirect('/ucenter/order');
+	}
+
+	/**
+    * @brief 根据省份名称查询相应的province
+    */
+	public function searchProvince()
+	{
+		$province = IFilter::act(IReq::get('province'));
+
+		$tb_areas = new IModel('areas');
+		$areas_info = $tb_areas->getObj('parent_id = 0 and area_name like "%'.$province.'%"','area_id');
+		$result = array('flag' => 'fail','area_id' => 0);
+		if($areas_info)
+		{
+			$result = array('flag' => 'success','area_id' => $areas_info['area_id']);
+		}
+		echo JSON::encode($result);
+	}
+    //添加实体代金券
+    function add_download_ticket()
+    {
+    	$isError = true;
+
+    	$ticket_num = IFilter::act(IReq::get('ticket_num'));
+    	$ticket_pwd = IFilter::act(IReq::get('ticket_pwd'));
+
+		//代金券状态是否正常
+    	$propObj = new IModel('prop');
+    	$propRow = $propObj->getObj('card_name = "'.$ticket_num.'" and card_pwd = "'.$ticket_pwd.'" and type = 0 and is_userd = 0 and is_send = 1 and is_close = 0 and NOW() between start_time and end_time');
+    	if(!$propRow)
+    	{
+    		$message = '代金券不可用,请确认代金券的卡号密码并且此代金券在有效期内从未被使用过';
+	    	$result = array(
+	    		'isError' => $isError,
+	    		'message' => $message,
+	    	);
+	    	die(JSON::encode($result));
+    	}
+
+    	//代金券是否已经被领取
+    	$memberObj = new IModel('member');
+		$isRev     = $memberObj->query('FIND_IN_SET('.$propRow['id'].',prop)');
+		if($isRev)
+		{
+    		$message = '代金券已经被领取';
+	    	$result = array(
+	    		'isError' => $isError,
+	    		'message' => $message,
+	    	);
+	    	die(JSON::encode($result));
+		}
+
+		//登录用户
+		$isError = false;
+		$message = '添加成功';
+		if($this->user['user_id'])
+		{
+    		$memberRow = $memberObj->getObj('user_id = '.$this->user['user_id'],'prop');
+    		if($memberRow['prop'] == '')
+    		{
+    			$propUpdate = ','.$propRow['id'].',';
+    		}
+    		else
+    		{
+    			$propUpdate = $memberRow['prop'].$propRow['id'].',';
+    		}
+
+    		$dataArray = array('prop' => $propUpdate);
+    		$memberObj->setData($dataArray);
+    		$memberObj->update('user_id = '.$this->user['user_id']);
+		}
+		//游客方式
+		else
+		{
+			ISafe::set("ticket_".$propRow['id'],$propRow['id']);
+		}
+
+    	$result = array(
+    		'isError' => $isError,
+    		'data'    => $propRow,
+    		'message' => $message,
+    	);
+
+    	die(JSON::encode($result));
+    }
+
+	private function alert($msg)
+	{
+		header('Content-type: text/html; charset=UTF-8');
+		echo JSON::encode(array('error' => 1, 'message' => $msg));
+		exit;
+	}
+	/*
+	 * @breif ajax添加商品扩展属性
+	 * */
+	function attribute_init()
+	{
+		$id = IFilter::act(IReq::get('model_id'),'int');
+		$tb_attribute = new IModel('attribute');
+		$attribute_info = $tb_attribute->query('model_id='.$id);
+		echo JSON::encode($attribute_info);
+	}
+
+	//获取商品数据
+	public function getGoodsData()
+	{
+		$id = IFilter::act(IReq::get('id'),'int');
+
+		$productDB = new IQuery('products as p');
+		$productDB->join  = 'left join goods as go on go.id = p.goods_id';
+		$productDB->where = 'go.id = '.$id;
+		$productDB->fields= 'p.*,go.name';
+		$productData = $productDB->find();
+
+		if(!$productData)
+		{
+			$goodsDB   = new IModel('goods');
+			$productData = $goodsDB->query('id = '.$id);
+		}
+		echo JSON::encode($productData);
+	}
+
+	//获取商品的推荐标签数据
+	public function goodsCommend()
+	{
+		//商品字符串的逗号间隔
+		$id = IFilter::act(IReq::get('id'));
+		if($id)
+		{
+			$idArray = explode(",",$id);
+			$idArray = IFilter::act($idArray,'int');
+			$id = join(',',$idArray);
+		}
+
+		$goodsDB = new IModel('goods');
+		$goodsData = $goodsDB->query("id in (".$id.")","id,name");
+
+		$goodsCommendDB = new IModel('commend_goods');
+		foreach($goodsData as $key => $val)
+		{
+			$goodsCommendData = $goodsCommendDB->query("goods_id = ".$val['id']);
+			foreach($goodsCommendData as $k => $v)
+			{
+				$goodsData[$key]['commend'][$v['commend_id']] = 1;
+			}
+		}
+		die(JSON::encode($goodsData));
+	}
+
+	//获取自提点数据
+	public function getTakeselfList()
+	{
+		$id   = IFilter::act(IReq::get('id'),'int');
+		$type = IFilter::act(IReq::get('type'));
+		$takeselfObj = new IQuery('takeself');
+
+		switch($type)
+		{
+			case "province":
+			{
+				$where = "province = ".$id;
+				$takeselfObj->group = 'city';
+			}
+			break;
+
+			case "city":
+			{
+				$where = "city = ".$id;
+				$takeselfObj->group = 'area';
+			}
+			break;
+
+			case "area":
+			{
+				$where = "area = ".$id;
+			}
+			break;
+		}
+
+		$takeselfObj->where = $where;
+		$takeselfList = $takeselfObj->find();
+
+		foreach($takeselfList as $key => $val)
+		{
+			$temp = area::name($val['province'],$val['city'],$val['area']);
+			$takeselfList[$key]['province_str'] = $temp[$val['province']];
+			$takeselfList[$key]['city_str']     = $temp[$val['city']];
+			$takeselfList[$key]['area_str']     = $temp[$val['area']];
+		}
+		die(JSON::encode($takeselfList));
+	}
+
+	//物流轨迹查询
+	public function freight()
+	{
+		$id = IFilter::act(IReq::get('id'),'int');
+
+		if($id)
+		{
+			$tb_freight = new IQuery('delivery_doc as d');
+			$tb_freight->join  = 'left join freight_company as f on f.id = d.freight_id';
+			$tb_freight->where = 'd.id = '.$id;
+			$tb_freight->fields= 'd.*,f.freight_type';
+			$freightData = $tb_freight->find();
+
+			if($freightData)
+			{
+				$freightData = current($freightData);
+				if($freightData['freight_type'] && $freightData['delivery_code'])
+				{
+					$result = freight_facade::line($freightData['freight_type'],$freightData['delivery_code']);
+					if($result['result'] == 'success')
+					{
+						$this->data = $result['data'];
+						$this->redirect('freight');
+						return;
+					}
+					else
+					{
+						die(isset($result['reason']) ? $result['reason'] : '物流接口发生错误');
+					}
+				}
+				else
+				{
+					die('缺少物流信息');
+				}
+			}
+		}
+		die('发货单信息不存在');
+	}
+
+	//收货地址弹出框
+    public function address()
+    {
+    	$user_id = $this->user['user_id'];
+    	$id      = IFilter::act(IReq::get('id'),'int');
+    	if($user_id)
+    	{
+    		if($id)
+    		{
+	    		$addressDB        = new IModel('address');
+	    		$this->addressRow = $addressDB->getObj('user_id = '.$user_id.' and id = '.$id);
+    		}
+    	}
+    	else
+    	{
+			$this->addressRow = ISafe::get('address');
+    	}
+    	$this->redirect('address');
+    }
+
+    //代金券弹出框
+    public function ticket()
+    {
+		$this->prop       = array();
+		$this->sellerInfo = IFilter::act(IReq::get('sellerString'));
+		$user_id          = $this->user['user_id'];
+
+		//获取代金券
+		if($user_id)
+		{
+			$memberObj = new IModel('member');
+			$memberRow = $memberObj->getObj('user_id = '.$user_id,'prop');
+
+			if(isset($memberRow['prop']) && ($propId = trim($memberRow['prop'],',')))
+			{
+				$porpObj = new IModel('prop');
+				$this->prop = $porpObj->query('id in ('.$propId.') and NOW() between start_time and end_time and type = 0 and is_close = 0 and is_userd = 0 and is_send = 1');
+			}
+		}
+		$this->redirect('ticket');
+    }
+}

+ 220 - 0
src/controllers/brand.php

@@ -0,0 +1,220 @@
+<?php
+/**
+ * @class Brand
+ * @brief 品牌模块
+ * @note  后台
+ */
+class Brand extends IController implements adminAuthorization
+{
+	public $checkRight  = 'all';
+    public $layout='admin';
+	private $data = array();
+
+	function init()
+	{
+
+	}
+
+	/**
+	 * @brief 品牌分类添加、修改
+	 */
+	function category_edit()
+	{
+		$category_id = (int)IReq::get('cid');
+		//编辑品牌分类 读取品牌分类信息
+		if($category_id)
+		{
+			$obj_brand_category = new IModel('brand_category');
+			$category_info = $obj_brand_category->getObj('id='.$category_id);
+
+			if($category_info)
+			{
+				$this->catRow = $category_info;
+			}
+			else
+			{
+				$this->redirect('category_list');
+				Util::showMessage("没有找到相关品牌分类!");
+				return;
+			}
+		}
+		$this->redirect('category_edit');
+	}
+
+	/**
+	 * @brief 保存品牌分类
+	 */
+	function category_save()
+	{
+		$id                = IFilter::act(IReq::get('id'),'int');
+		$goods_category_id = IFilter::act(IReq::get('goods_category_id'),'int');
+		$name              = IFilter::act(IReq::get('name'));
+
+		$category_info = array(
+			'name' => $name,
+			'goods_category_id' => $goods_category_id
+		);
+		$tb_brand_category = new IModel('brand_category');
+		$tb_brand_category->setData($category_info);
+
+		//更新品牌分类
+		if($id)
+		{
+			$where = "id=".$id;
+			$tb_brand_category->update($where);
+		}
+		//添加品牌分类
+		else
+		{
+			$tb_brand_category->add();
+		}
+		$this->redirect('category_list');
+	}
+
+	/**
+	 * @brief 删除品牌分类
+	 */
+	function category_del()
+	{
+		$category_id = (int)IReq::get('cid');
+		if($category_id)
+		{
+			$brand_category = new IModel('brand_category');
+			$where = "id=".$category_id;
+			if($brand_category->del($where))
+			{
+				$this->redirect('category_list');
+			}
+			else
+			{
+				$this->redirect('category_list');
+				$msg = "没有找到相关分类记录!";
+				Util::showMessage($msg);
+			}
+		}
+		else
+		{
+			$this->redirect('category_list');
+			$msg = "没有找到相关分类记录!";
+			Util::showMessage($msg);
+		}
+	}
+
+	/**
+	 * @brief 修改品牌
+	 */
+	function brand_edit()
+	{
+		$brand_id = (int)IReq::get('bid');
+		//编辑品牌 读取品牌信息
+		if($brand_id)
+		{
+			$obj_brand = new IModel('brand');
+			$brand_info = $obj_brand->getObj('id='.$brand_id);
+			if($brand_info)
+			{
+				$this->data['brand'] = $brand_info;
+			}
+			else
+			{
+				$this->redirect('category_list');
+				Util::showMessage("没有找到相关品牌分类!");
+				return;
+			}
+		}
+
+		$this->setRenderData($this->data);
+		$this->redirect('brand_edit',false);
+	}
+
+	/**
+	 * @brief 保存品牌
+	 */
+	function brand_save()
+	{
+		$brand_id = IFilter::act(IReq::get('brand_id'),'int');
+		$name = IFilter::act(IReq::get('name'));
+		$sort = IFilter::act(IReq::get('sort'),'int');
+		$url = IFilter::act(IReq::get('url'));
+		$category = IFilter::act(IReq::get('category'),'int');
+		$description = IFilter::act(IReq::get('description'));
+
+		$tb_brand = new IModel('brand');
+		$brand = array(
+			'name'=>$name,
+			'sort'=>$sort,
+			'url'=>$url,
+			'description' => $description,
+		);
+
+		if($category && is_array($category))
+		{
+			$categorys = join(',',$category);
+			$brand['category_ids'] = $categorys;
+		}
+		else
+		{
+			$brand['category_ids'] = '';
+		}
+		if(isset($_FILES['logo']['name']) && $_FILES['logo']['name']!='')
+		{
+			$uploadObj = new PhotoUpload();
+			$uploadObj->setIterance(false);
+			$photoInfo = $uploadObj->run();
+			if(isset($photoInfo['logo']['img']) && file_exists($photoInfo['logo']['img']))
+			{
+				$brand['logo'] = $photoInfo['logo']['img'];
+			}
+		}
+		$tb_brand->setData($brand);
+		if($brand_id)
+		{
+			//保存修改分类信息
+			$where = "id=".$brand_id;
+			$tb_brand->update($where);
+		}
+		else
+		{
+			//添加新品牌
+			$tb_brand->add();
+		}
+		$this->brand_list();
+	}
+
+	/**
+	 * @brief 删除品牌
+	 */
+	function brand_del()
+	{
+		$brand_id = (int)IReq::get('bid');
+		if($brand_id)
+		{
+			$tb_brand = new IModel('brand');
+			$where = "id=".$brand_id;
+			if($tb_brand->del($where))
+			{
+				$this->brand_list();
+			}
+			else
+			{
+				$this->brand_list();
+				$msg = "没有找到相关分类记录!";
+				Util::showMessage($msg);
+			}
+		}
+		else
+		{
+			$this->brand_list();
+			$msg = "没有找到相关品牌记录!";
+			Util::showMessage($msg);
+		}
+	}
+
+	/**
+	 * @brief 品牌列表
+	 */
+	function brand_list()
+	{
+		$this->redirect('brand_list');
+	}
+}

+ 434 - 0
src/controllers/comment.php

@@ -0,0 +1,434 @@
+<?php
+/**
+ * @class Comment
+ * @brief 评论模块
+ * @note  后台
+ */
+class Comment extends IController implements adminAuthorization
+{
+	public $checkRight  = 'all';
+    public $layout='admin';
+	private $data = array();
+
+	function init()
+	{
+
+	}
+
+	function suggestion_list()
+	{
+		$search = IFilter::act(IReq::get('search'),'strict');
+		$where = Util::search($search);
+		$this->data['search'] = $search;
+		$this->data['where'] = $where;
+		$this->setRenderData($this->data);
+		$this->redirect("suggestion_list");
+	}
+
+	/**
+	 * @brief 显示建议信息
+	 */
+	function suggestion_edit()
+	{
+		$id = intval(IReq::get('id'));
+		if(!$id)
+		{
+			$this->comment_list();
+			return false;
+		}
+		$query = new IQuery("suggestion as a");
+		$query->join = "left join user AS b ON a.user_id=b.id";
+		$query->where = "a.id={$id}";
+		$query->fields = "a.*,b.username";
+		$items = $query->find();
+
+		if(is_array($items) && $items)
+		{
+			$this->suggestion = $items[0];
+			$this->redirect('suggestion_edit');
+		}
+		else
+		{
+			$this->suggestion_list();
+		}
+	}
+
+	/**
+	 * @brief 回复建议
+	 */
+	function suggestion_edit_act()
+	{
+		$id = intval(IReq::get('id','post'));
+		$re_content = IFilter::act( IReq::get('re_content','post') ,'string');
+		$tb = new IModel("suggestion");
+		$data = array('admin_id'=>$this->admin['admin_id'],'re_content'=>$re_content,'re_time'=>ITime::getDateTime());
+		$tb->setData($data);
+		$tb->update("id={$id}");
+		$this->redirect("/comment/suggestion_list");
+	}
+
+
+	/**
+	 * @brief 删除要删除的建议
+	 */
+	function suggestion_del()
+	{
+		$suggestion_ids = IReq::get('check');
+		$suggestion_ids = is_array($suggestion_ids) ? $suggestion_ids : array($suggestion_ids);
+		if($suggestion_ids)
+		{
+			$suggestion_ids = IFilter::act($suggestion_ids,'int');
+
+			$ids = implode(',',$suggestion_ids);
+			if($ids)
+			{
+				$tb_suggestion = new IModel('suggestion');
+				$where = "id in (".$ids.")";
+				$tb_suggestion->del($where);
+			}
+		}
+		$this->suggestion_list();
+	}
+
+	/**
+	 * @brief 评论信息列表
+	 */
+	function comment_list()
+	{
+		$search = IFilter::act(IReq::get('search'),'strict');
+		$where = Util::search($search);
+		$this->data['where'] = 'c.status = 1 and '.$where;
+		$this->data['search']= $search;
+		$this->setRenderData($this->data);
+		$this->redirect('comment_list');
+	}
+
+	/**
+	 * @brief 显示评论信息
+	 */
+	function comment_edit()
+	{
+		$cid = IFilter::act(IReq::get('cid'),'int');
+
+		if(!$cid)
+		{
+			$this->comment_list();
+			return false;
+		}
+		$query = new IQuery("comment as c");
+		$query->join = "left join goods as goods on c.goods_id = goods.id left join user as u on c.user_id = u.id";
+		$query->fields = "c.*,u.username,goods.name,goods.seller_id";
+		$query->where = "c.id=".$cid;
+		$items = $query->find();
+
+		if($items)
+		{
+			$this->comment = current($items);
+			$this->redirect('comment_edit');
+		}
+		else
+		{
+			$this->comment_list();
+			$msg = '没有找到相关记录!';
+			Util::showMessage($msg);
+		}
+	}
+
+	/**
+	 * @brief 删除要删除的评论
+	 */
+	function comment_del()
+	{
+		$comment_ids = IReq::get('check');
+		$comment_ids = is_array($comment_ids) ? $comment_ids : array($comment_ids);
+		if($comment_ids)
+		{
+			$comment_ids = IFilter::act($comment_ids,'int');
+			$tb_comment  = new IModel('comment');
+			foreach($comment_ids as $key => $cid)
+			{
+				$commentRow = $tb_comment->getObj('id = '.$cid);
+
+				//同步更新goods表,comments,grade
+				$goodsDB = new IModel('goods');
+				$goodsDB->setData(array(
+					'comments' => 'comments - 1',
+					'grade'    => 'grade - '.$commentRow['point'],
+				));
+				$goodsDB->update('id = '.$commentRow['goods_id'],array('grade','comments'));
+
+				//同步更新seller表,comments,grade
+				$sellerDB = new IModel('seller');
+				$sellerDB->setData(array(
+					'comments' => 'comments - 1',
+					'grade'    => 'grade - '.$commentRow['point'],
+				));
+				$sellerDB->update('id = '.$commentRow['seller_id'],array('grade','comments'));
+
+				//删除评论
+				$tb_comment->del("id = ".$cid);
+			}
+		}
+		$this->comment_list();
+	}
+
+	/**
+	 * @brief 回复评论
+	 */
+	function comment_update()
+	{
+		$id = IFilter::act(IReq::get('id'),'int');
+		$recontent = IFilter::act(IReq::get('recontents'));
+		if($id)
+		{
+			$updateData = array(
+				'recontents' => $recontent,
+				'recomment_time' => ITime::getDateTime(),
+			);
+			$commentDB = new IModel('comment');
+			$commentDB->setData($updateData);
+			$commentDB->update('id = '.$id);
+		}
+		$this->redirect('comment_list');
+	}
+
+	/**
+	 * @brief 讨论信息列表
+	 */
+	function discussion_list()
+	{
+		$search = IFilter::act(IReq::get('search'),'strict');
+		$where = Util::search($search);
+		$this->data['search'] = $search;
+		$this->data['where'] = $where;
+		$this->setRenderData($this->data);
+		$this->redirect('discussion_list');
+	}
+
+	/**
+	 * @brief 显示讨论信息
+	 */
+	function discussion_edit()
+	{
+		$did = intval(IReq::get('did'));
+		if(!$did)
+		{
+			$this->discussion_list();
+			return false;
+		}
+		$query = new IQuery("discussion as d");
+		$query->join = "right join goods as goods on d.goods_id = goods.id left join user as u on d.user_id = u.id";
+		$query->fields = "d.id,d.time,d.contents,u.id as userid,u.username,goods.id as goods_id,goods.name as goods_name";
+		$query->where = "d.id=".$did;
+		$items = $query->find();
+
+		if($items)
+		{
+			$this->discussion = $items[0];
+			$this->redirect('discussion_edit');
+		}
+		else
+		{
+			$this->discussion_list();
+			$msg = '没有找到相关记录!';
+			Util::showMessage($msg);
+		}
+	}
+
+	/**
+	 * @brief 删除讨论信息
+	 */
+	function discussion_del()
+	{
+		$discussion_ids = IReq::get('check');
+		$discussion_ids = is_array($discussion_ids) ? $discussion_ids : array($discussion_ids);
+		if($discussion_ids)
+		{
+			$ids = implode(',',$discussion_ids);
+			if($ids)
+			{
+				$tb_discussion = new IModel('discussion');
+				$where = "id in (".$ids.")";
+				$tb_discussion->del($where);
+			}
+		}
+		$this->discussion_list();
+	}
+
+	/**
+	 * @brief 咨询信息列表
+	 */
+	function refer_list()
+	{
+		$search = IFilter::act(IReq::get('search'),'strict');
+		$where = Util::search($search);
+		$this->data['search'] = $search;
+		$this->data['where'] = $where;
+		$this->setRenderData($this->data);
+		$this->redirect('refer_list');
+	}
+
+	/**
+	 * @brief 删除咨询信息
+	 */
+	function refer_del()
+	{
+		$refer_ids = IReq::get('check');
+		$refer_ids = is_array($refer_ids) ? $refer_ids : array($refer_ids);
+		if($refer_ids)
+		{
+			$refer_ids = IFilter::act($refer_ids,'int');
+			$ids = implode(',',$refer_ids);
+			if($ids)
+			{
+				$tb_refer = new IModel('refer');
+				$where = "id in (".$ids.")";
+				$tb_refer->del($where);
+			}
+		}
+		$this->refer_list();
+	}
+	/**
+	 * @brief 回复咨询信息
+	 */
+	function refer_reply()
+	{
+		$rid     = IFilter::act(IReq::get('refer_id'),'int');
+		$content = IFilter::act(IReq::get('content'),'text');
+
+		if($rid && $content)
+		{
+			$tb_refer = new IModel('refer');
+			$admin_id = $this->admin['admin_id'];//管理员id
+			$data     = array(
+				'answer' => $content,
+				'reply_time' => ITime::getDateTime(),
+				'admin_id' => $admin_id,
+				'status' => 1
+			);
+			$tb_refer->setData($data);
+			$tb_refer->update("id=".$rid);
+		}
+		$this->refer_list();
+	}
+
+	/**
+	 * @brief 会员消息列表
+	 */
+	function message_list()
+	{
+		$tb_user_group = new IModel('user_group');
+		$data_group = $tb_user_group->query();
+		$data_group = is_array($data_group) ? $data_group : array();
+		$group      = array();
+		foreach($data_group as $value)
+		{
+			$group[$value['id']] = $value['group_name'];
+		}
+		$this->data['group'] = $group;
+
+		$this->setRenderData($this->data);
+		$this->redirect('message_list');
+	}
+
+	/**
+	 * @brief 删除会员消息
+	 */
+	function message_del()
+	{
+		$refer_ids = IFilter::act(IReq::get('check'));
+		$refer_ids = is_array($refer_ids) ? $refer_ids : array($refer_ids);
+		if($refer_ids)
+		{
+			$ids = implode(',',$refer_ids);
+			if($ids)
+			{
+				$tb_refer = new IModel('message');
+				$where = "id in (".$ids.")";
+				$tb_refer->del($where);
+			}
+		}
+		$this->message_list();
+	}
+
+	/**
+	 * 发送会员消息
+	 */
+	function message_send()
+	{
+		$this->layout = '';
+		$this->redirect('message_send');
+	}
+
+	/**
+	 * @brief 发送信件
+	 */
+	function start_message()
+	{
+		$toUser  = IFilter::act(IReq::get('toUser'));
+		$title   = IFilter::act(IReq::get('title'));
+		$content = IFilter::act(IReq::get('content'),'text');
+
+		if(!$title || !$content)
+		{
+			die('<script type="text/javascript">parent.startMessageCallback(0);</script>');
+		}
+
+		Mess::sendToUser($toUser,array('title' => $title,'content' => $content));
+		die('<script type="text/javascript">parent.startMessageCallback(1);</script>');
+	}
+
+	/**
+	 * @brief 商户消息列表
+	 */
+	function seller_message_list()
+	{
+		$this->redirect('seller_message_list');
+	}
+
+	/**
+	 * @brief 发送商户消息页面
+	 */
+	function seller_message_send()
+	{
+		$this->layout = '';
+		$this->redirect('seller_message_send');
+	}
+
+	/**
+	 * @brief 发送商户消息
+	 */
+	function start_seller_message()
+	{
+		$toSeller  = IFilter::act(IReq::get('toSeller'));
+		$title   = IFilter::act(IReq::get('title'));
+		$content = IFilter::act(IReq::get('content'),'text');
+
+		if(!$title || !$content)
+		{
+			die('<script type="text/javascript">parent.startMessageCallback(0);</script>');
+		}
+		seller_mess::send($toSeller, array('title' => $title, 'content' => $content));
+		die('<script type="text/javascript">parent.startMessageCallback(1);</script>');
+	}
+
+	/**
+	 * @brief 删除商户消息
+	 */
+	function seller_message_del()
+	{
+		$refer_ids = IReq::get('check');
+		$refer_ids = is_array($refer_ids) ? $refer_ids : array($refer_ids);
+		if($refer_ids)
+		{
+			$ids = implode(',',$refer_ids);
+			if($ids)
+			{
+				$tb_refer = new IModel('seller_message');
+				$where = "id in (".$ids.")";
+				$tb_refer->del($where);
+			}
+		}
+		$this->seller_message_list();
+	}
+}

+ 34 - 0
src/controllers/errors.php

@@ -0,0 +1,34 @@
+<?php
+/**
+ * @copyright (c) 2011 aircheng.com
+ * @file error.php
+ * @brief 错误处理类
+ * @author chendeshan
+ * @date 2010-12-16
+ * @version 0.6
+ */
+class Errors extends IController
+{
+	public function error404()
+	{
+		$heading = '文件不存在';
+		$data    = '请确定要访问的页面在是否存在';
+		$this->redirect('/site/error/?msg='.urlencode($data).'&heading='.urlencode($heading));
+	}
+
+	public function error403($data)
+	{
+		$heading = '操作发生错误';
+		if(is_array($data))
+		{
+			$data = isset($data['message']) ? $data['message'] : '';
+		}
+		$this->redirect('/site/error/?msg='.urlencode($data).'&heading='.urlencode($heading));
+	}
+
+	public function error503()
+	{
+		$data = '您无权限操作此功能';
+		$this->redirect('/block/error/?msg='.urlencode($data));
+	}
+}

+ 927 - 0
src/controllers/goods.php

@@ -0,0 +1,927 @@
+<?php
+/**
+ * @brief 商品模块
+ * @class Goods
+ * @note  后台
+ */
+class Goods extends IController implements adminAuthorization
+{
+	public $checkRight  = 'all';
+    public $layout = 'admin';
+    private $data = array();
+
+	public function init()
+	{
+
+	}
+	/**
+	 * @brief 商品添加中图片上传的方法
+	 */
+	public function goods_img_upload()
+	{
+	 	//调用文件上传类
+		$photoObj = new PhotoUpload();
+		$photo    = current($photoObj->run());
+
+		//判断上传是否成功,如果float=1则成功
+		if($photo['flag'] == 1)
+		{
+			$result = array(
+				'flag'=> 1,
+				'img' => $photo['img']
+			);
+		}
+		else
+		{
+			$result = array('flag'=> $photo['flag']);
+		}
+		echo JSON::encode($result);
+	}
+    /**
+	 * @brief 商品模型添加/修改
+	 */
+    public function model_update()
+    {
+    	// 获取POST数据
+    	$model_id   = IFilter::act(IReq::get("model_id"),'int');
+    	$model_name = IFilter::act(IReq::get("model_name"));
+    	$attribute  = IFilter::act(IReq::get("attr"));
+
+    	//初始化Model类对象
+		$modelObj = new Model();
+
+		//更新模型数据
+		$result = $modelObj->model_update($model_id,$model_name,$attribute);
+
+		if($result)
+		{
+			$this->redirect('model_list');
+		}
+		else
+		{
+			//处理post数据,渲染到前台
+    		$result = $modelObj->postArrayChange($attribute);
+			$this->data = array(
+				'id'         => $model_id,
+				'name'       => $model_name,
+				'model_attr' => $result['model_attr'],
+			);
+    		$this->setRenderData($this->data);
+			$this->redirect('model_edit',false);
+		}
+    }
+	/**
+	 * @brief 商品模型修改
+	 */
+    public function model_edit()
+    {
+    	// 获取POST数据
+    	$id = IFilter::act(IReq::get("id"),'int');
+    	if($id)
+    	{
+    		//初始化Model类对象
+    		$modelObj = new Model();
+    		//获取模型详细信息
+			$model_info = $modelObj->get_model_info($id);
+			//向前台渲染数据
+			$this->setRenderData($model_info);
+    	}
+		$this->redirect('model_edit');
+    }
+
+	/**
+	 * @brief 商品模型删除
+	 */
+    public function model_del()
+    {
+    	//获取POST数据
+    	$id = IFilter::act(IReq::get("id"),'int');
+    	$id = !is_array($id) ? array($id) : $id;
+
+    	if($id)
+    	{
+	    	foreach($id as $key => $val)
+	    	{
+	    		//初始化goods_attribute表类对象
+	    		$goods_attrObj = new IModel("goods_attribute");
+
+	    		//获取商品属性表中的该模型下的数量
+	    		$attrData = $goods_attrObj->query("model_id = ".$val);
+	    		if($attrData)
+	    		{
+	    			$this->redirect('model_list',false);
+	    			Util::showMessage("无法删除此模型,请确认该模型下以及回收站内都无商品");
+	    		}
+
+	    		//初始化Model表类对象
+	    		$modelObj = new IModel("model");
+
+	    		//删除商品模型
+				$result = $modelObj->del("id = ".$val);
+	    	}
+    	}
+		$this->redirect('model_list');
+    }
+
+	/**
+	 * @breif 后台添加为每一件商品添加会员价
+	 * */
+	function member_price()
+	{
+		$this->layout = '';
+
+		$goods_id   = IFilter::act(IReq::get('goods_id'),'int');
+		$product_id = IFilter::act(IReq::get('product_id'),'int');
+		$sell_price = IFilter::act(IReq::get('sell_price'),'float');
+
+		$date = array(
+			'sell_price' => $sell_price
+		);
+
+		if($goods_id)
+		{
+			$where  = 'goods_id = '.$goods_id;
+			$where .= $product_id ? ' and product_id = '.$product_id : '';
+
+			$priceRelationObject = new IModel('group_price');
+			$priceData = $priceRelationObject->query($where);
+			$date['price_relation'] = $priceData;
+		}
+
+		$this->setRenderData($date);
+		$this->redirect('member_price');
+	}
+	/**
+	 * @brief 商品添加和修改视图
+	 */
+	public function goods_edit()
+	{
+		$goods_id = IFilter::act(IReq::get('id'),'int');
+
+		//初始化数据
+		$goods_class = new goods_class();
+
+		//获取所有商品扩展相关数据
+		$data = $goods_class->edit($goods_id);
+
+		if($goods_id && !$data)
+		{
+			die("没有找到相关商品!");
+		}
+
+		$this->setRenderData($data);
+		$this->redirect('goods_edit');
+	}
+	/**
+	 * @brief 保存修改商品信息
+	 */
+	function goods_update()
+	{
+		$id       = IFilter::act(IReq::get('id'),'int');
+		$callback = IReq::get('callback');
+		$callback = strpos($callback,'goods/goods_list') === false ? '' : $callback;
+
+		//检查表单提交状态
+		if(!$_POST)
+		{
+			die('请确认表单提交正确');
+		}
+
+		//初始化商品数据
+		unset($_POST['id']);
+		unset($_POST['callback']);
+
+		$goodsObject = new goods_class();
+		$goodsObject->update($id,$_POST);
+
+		//记录日志
+		$logObj = new log('db');
+		$logObj->write('operation',array("管理员:".ISafe::get('admin_name'),"修改商品信息","商品ID:".$id.",名称:".IFilter::act(IReq::get('name'))));
+
+		$callback ? $this->redirect($callback) : $this->redirect("goods_list");
+	}
+
+	/**
+	 * @brief 删除商品
+	 */
+	function goods_del()
+	{
+		//post数据
+	    $id = IFilter::act(IReq::get('id'),'int');
+
+	    //生成goods对象
+	    $tb_goods = new IModel('goods');
+	    $tb_goods->setData(array('is_del'=>1));
+	    if($id)
+		{
+			$tb_goods->update(Util::joinStr($id));
+		}
+		else
+		{
+			die('请选择要删除的数据');
+		}
+		$this->redirect("goods_list");
+	}
+	/**
+	 * @brief 商品上下架
+	 */
+	function goods_stats()
+	{
+		//post数据
+	    $id   = IFilter::act(IReq::get('id'),'int');
+	    $type = IFilter::act(IReq::get('type'));
+
+	    //生成goods对象
+	    $tb_goods = new IModel('goods');
+	    if($type == 'up')
+	    {
+	    	$updateData = array('is_del' => 0,'up_time' => ITime::getDateTime(),'down_time' => null);
+	    }
+	    else if($type == 'down')
+	    {
+	    	$updateData = array('is_del' => 2,'up_time' => null,'down_time' => ITime::getDateTime());
+	    }
+	    else if($type == 'check')
+	    {
+	    	$updateData = array('is_del' => 3,'up_time' => null,'down_time' => null);
+	    }
+
+	    $tb_goods->setData($updateData);
+
+	    if($id)
+		{
+			$tb_goods->update(Util::joinStr($id));
+		}
+		else
+		{
+			Util::showMessage('请选择要操作的数据');
+		}
+
+		if(IClient::isAjax() == false)
+		{
+			$this->redirect("goods_list");
+		}
+	}
+	/**
+	 * @brief 商品彻底删除
+	 * */
+	function goods_recycle_del()
+	{
+		//post数据
+	    $id = IFilter::act(IReq::get('id'),'int');
+
+	    //生成goods对象
+	    $goods = new goods_class();
+	    if($id)
+		{
+			if(is_array($id))
+			{
+				foreach($id as $key => $val)
+				{
+					$goods->del($val);
+				}
+			}
+			else
+			{
+				$goods->del($id);
+			}
+		}
+
+		$this->redirect("goods_recycle_list");
+	}
+	/**
+	 * @brief 商品还原
+	 * */
+	function goods_recycle_restore()
+	{
+		//post数据
+	    $id = IFilter::act(IReq::get('id'),'int');
+	    //生成goods对象
+	    $tb_goods = new IModel('goods');
+	    $tb_goods->setData(array('is_del'=>0));
+	    if($id)
+		{
+			$tb_goods->update(Util::joinStr($id));
+		}
+		else
+		{
+			Util::showMessage('请选择要删除的数据');
+		}
+		$this->redirect("goods_recycle_list");
+	}
+
+	/**
+	 * @brief 商品列表
+	 */
+	function goods_list()
+	{
+		//搜索条件
+		$search = IReq::get('search');
+		$page   = IReq::get('page') ? IFilter::act(IReq::get('page'),'int') : 1;
+
+		//条件筛选处理
+		list($join,$where) = goods_class::getSearchCondition($search);
+
+		//拼接sql
+		$goodsHandle = new IQuery('goods as go');
+		$goodsHandle->order    = "go.id desc";
+		$goodsHandle->fields   = "distinct go.id,go.name,go.sell_price,go.market_price,go.store_nums,go.img,go.is_del,go.seller_id,go.is_share,go.sort";
+		$goodsHandle->page     = $page;
+		$goodsHandle->where    = $where;
+		$goodsHandle->join     = $join;
+
+		$this->search      = $search;
+		$this->goodsHandle = $goodsHandle;
+		$this->redirect("goods_list");
+	}
+
+	//商品导出 Excel
+	public function goods_report()
+	{
+		//搜索条件
+		$search = IReq::get('search');
+		//条件筛选处理
+		list($join,$where) = goods_class::getSearchCondition($search);
+		//拼接sql
+		$goodsHandle = new IQuery('goods as go');
+		$goodsHandle->order    = "go.id desc";
+		$goodsHandle->fields   = "go.id, go.name,go.sell_price,go.store_nums,go.sale,go.is_del,go.create_time";
+		$goodsHandle->join     = $join;
+		$goodsHandle->where    = $where;
+		$goodsList = $goodsHandle->find();
+
+		//构建 Excel table;
+		$reportObj = new report('goods');
+		$reportObj->setTitle(array("商品名称","分类","售价","库存","销量","发布时间","状态"));
+		foreach($goodsList as $k => $val)
+		{
+			$insertData = array(
+				$val['name'],
+				goods_class::getGoodsCategory($val['id']),
+				$val['sell_price'],
+				$val['store_nums'],
+				$val['sale'],
+				$val['create_time'],
+				goods_class::statusText($val['is_del']),
+			);
+			$reportObj->setData($insertData);
+		}
+		$reportObj->toDownload();
+	}
+
+	/**
+	 * @brief 商品分类添加、修改
+	 */
+	function category_edit()
+	{
+		$category_id = IFilter::act(IReq::get('cid'),'int');
+		if($category_id)
+		{
+			$categoryObj = new IModel('category');
+			$this->categoryRow = $categoryObj->getObj('id = '.$category_id);
+		}
+		$this->redirect('category_edit');
+	}
+
+	/**
+	 * @brief 保存商品分类
+	 */
+	function category_save()
+	{
+		//获得post值
+		$category_id = IFilter::act(IReq::get('id'),'int');
+		$name = IFilter::act(IReq::get('name'));
+		$parent_id = IFilter::act(IReq::get('parent_id'),'int');
+		$visibility = IFilter::act(IReq::get('visibility'),'int');
+		$sort = IFilter::act(IReq::get('sort'),'int');
+		$title = IFilter::act(IReq::get('title'));
+		$keywords = IFilter::act(IReq::get('keywords'));
+		$descript = IFilter::act(IReq::get('descript'));
+
+		$childString = goods_class::catChild($category_id);//父类ID不能死循环设置成其子分类
+		if($parent_id > 0 && stripos(",".$childString.",",",".$parent_id.",") !== false)
+		{
+			$this->redirect('/goods/category_list/_msg/父分类设置错误');
+			return;
+		}
+
+		$tb_category = new IModel('category');
+		$category_info = array(
+			'name'      => $name,
+			'parent_id' => $parent_id,
+			'sort'      => $sort,
+			'visibility'=> $visibility,
+			'keywords'  => $keywords,
+			'descript'  => $descript,
+			'title'     => $title
+		);
+		$tb_category->setData($category_info);
+		if($category_id)									//保存修改分类信息
+		{
+			$where = "id=".$category_id;
+			$tb_category->update($where);
+		}
+		else												//添加新商品分类
+		{
+			$tb_category->add();
+		}
+		$this->redirect('category_list');
+	}
+
+	/**
+	 * @brief 删除商品分类
+	 */
+	function category_del()
+	{
+		$category_id = IFilter::act(IReq::get('cid'),'int');
+		if($category_id)
+		{
+			$tb_category = new IModel('category');
+			$catRow      = $tb_category->getObj('parent_id = '.$category_id);
+
+			//要删除的分类下还有子节点
+			if(!empty($catRow))
+			{
+				$this->category_list();
+				Util::showMessage('无法删除此分类,此分类下还有子分类,或者回收站内还留有子分类');
+				exit;
+			}
+
+			if($tb_category->del('id = '.$category_id))
+			{
+				$tb_category_extend  = new IModel('category_extend');
+				$tb_category_extend->del('category_id = '.$category_id);
+				$this->redirect('category_list');
+			}
+			else
+			{
+				$this->category_list();
+				$msg = "没有找到相关分类记录!";
+				Util::showMessage($msg);
+			}
+		}
+		else
+		{
+			$this->category_list();
+			$msg = "没有找到相关分类记录!";
+			Util::showMessage($msg);
+		}
+	}
+
+	/**
+	 * @brief 商品分类列表
+	 */
+	function category_list()
+	{
+		$isCache = false;
+		$tb_category = new IModel('category');
+		$cacheObj = new ICache('file');
+		$data = $cacheObj->get('sortdata');
+		if(!$data)
+		{
+			$goods = new goods_class();
+			$data = $goods->sortdata($tb_category->query(false,'*','sort asc'));
+			$isCache ? $cacheObj->set('sortdata',$data) : "";
+		}
+		$this->data['category'] = $data;
+		$this->setRenderData($this->data);
+		$this->redirect('category_list',false);
+	}
+
+	//修改规格页面
+	function spec_edit()
+	{
+		$this->layout = '';
+
+		$id        = IFilter::act(IReq::get('id'),'int');
+		$seller_id = IFilter::act(IReq::get('seller_id'),'int');
+
+		$dataRow = array(
+			'id'        => '',
+			'name'      => '',
+			'type'      => '',
+			'value'     => '',
+			'note'      => '',
+			'seller_id' => $seller_id,
+		);
+
+		if($id)
+		{
+			$obj     = new IModel('spec');
+			$dataRow = $obj->getObj("id = {$id}");
+		}
+
+		$this->setRenderData($dataRow);
+		$this->redirect('spec_edit');
+	}
+
+	//增加或者修改规格
+    function spec_update()
+    {
+    	$id         = IFilter::act(IReq::get('id'),'int');
+    	$name       = IFilter::act(IReq::get('name'));
+    	$specType   = IFilter::act(IReq::get('type'));
+    	$showValue  = $specType == 1 ? IReq::get('showText') : IFilter::act(IReq::get('showImage'),'filename');
+    	$note       = IFilter::act(IReq::get('note'));
+    	$seller_id  = IFilter::act(IReq::get('seller_id'),'int');
+    	$valueData  = IReq::get('valueData');
+
+		//组合规格显示数据和数据实际数据
+		$valueData = $valueData ? array_filter($valueData) : "";
+		$showValue = $showValue ? array_filter($showValue) : "";
+    	$value = $valueData && $showValue && count($valueData) == count($showValue) ? array_filter(array_combine($valueData,$showValue)) : "";
+
+		//要插入的数据
+    	if(is_array($value))
+    	{
+    		$value = $value ? IFilter::act(JSON::encode($value)) : '';
+		}
+
+		if(!$value)
+		{
+			die( JSON::encode(array('flag' => 'fail','message' => '规格值和提示信息不能为空或者0,请填写正确文字')) );
+		}
+
+		if(!$name)
+		{
+			die( JSON::encode(array('flag' => 'fail','message' => '规格名称不能为空')) );
+		}
+
+    	$editData = array(
+    		'id'        => $id,
+    		'name'      => $name,
+    		'value'     => $value,
+    		'type'      => $specType,
+    		'note'      => $note,
+    		'seller_id' => $seller_id,
+    	);
+
+		//执行操作
+		$obj = new IModel('spec');
+    	$obj->setData($editData);
+
+    	//更新修改
+    	if($id)
+    	{
+    		$where = 'id = '.$id;
+    		if($seller_id)
+    		{
+    			$where .= ' and seller_id = '.$seller_id;
+    		}
+    		$result = $obj->update($where);
+    	}
+    	//添加插入
+    	else
+    	{
+    		$result = $obj->add();
+    	}
+
+		//执行状态
+    	if($result===false)
+    	{
+			die( JSON::encode(array('flag' => 'fail','message' => '数据库更新失败')) );
+    	}
+    	else
+    	{
+    		//获取自动增加ID 处理返回json便于视图使用
+    		$editData['id']    = $id ? $id : $result;
+    		$editData['id']    = strval($editData['id']);
+    		$editData['value'] = IFilter::stripSlash($editData['value']);
+    		die( JSON::encode(array('flag' => 'success','data' => $editData)) );
+    	}
+    }
+
+	//批量删除规格
+    function spec_del()
+    {
+    	$id = IFilter::act(IReq::get('id'),'int');
+		if($id)
+		{
+			$obj = new IModel('spec');
+			$obj->setData(array('is_del'=>1));
+			$obj->update(Util::joinStr($id));
+			$this->redirect('spec_list');
+		}
+		else
+		{
+			$this->redirect('spec_list',false);
+			Util::showMessage('请选择要删除的规格');
+		}
+    }
+	//彻底批量删除规格
+    function spec_recycle_del()
+    {
+    	$id = IFilter::act(IReq::get('id'),'int');
+		if($id)
+		{
+			$obj = new IModel('spec');
+			$obj->del(Util::joinStr($id));
+			$this->redirect('spec_recycle_list');
+		}
+		else
+		{
+			$this->redirect('spec_recycle_list',false);
+			Util::showMessage('请选择要删除的规格');
+		}
+    }
+	//批量还原规格
+    function spec_recycle_restore()
+    {
+    	$id = IFilter::act(IReq::get('id'),'int');
+		if($id)
+		{
+			$obj = new IModel('spec');
+			$obj->setData(array('is_del'=>0));
+			$obj->update(Util::joinStr($id));
+			$this->redirect('spec_recycle_list');
+		}
+		else
+		{
+			$this->redirect('spec_recycle_list',false);
+			Util::showMessage('请选择要还原的规格');
+		}
+    }
+    //规格图片删除
+    function spec_photo_del()
+    {
+    	$id = IReq::get('id','post');
+    	if(isset($id[0]) && $id[0]!='')
+    	{
+    		$obj = new IModel('spec_photo');
+    		$id_str = '';
+    		foreach($id as $rs)
+    		{
+    			if($id_str!='')
+    			{
+    				$id_str.=',';
+    			}
+    				$id_str.=$rs;
+
+    			$photoRow = $obj->getObj('id = '.$rs,'address');
+    			if(file_exists($photoRow['address']))
+    			{
+    				unlink($photoRow['address']);
+    			}
+    		}
+
+	    	$where = ' id in ('.$id_str.')';
+	    	$obj->del($where);
+	    	$this->redirect('spec_photo');
+    	}
+    	else
+    	{
+    		$this->redirect('spec_photo',false);
+    		Util::showMessage('请选择要删除的id值');
+    	}
+    }
+
+	/**
+	 * @brief 分类排序
+	 */
+	function category_sort()
+	{
+		$category_id = IFilter::act(IReq::get('id'),'int');
+		$sort = IFilter::act(IReq::get('sort'),'int');
+
+		$flag = 0;
+		if($category_id)
+		{
+			$tb_category = new IModel('category');
+			$category_info = $tb_category->getObj('id='.$category_id);
+			if(count($category_info)>0)
+			{
+				if($category_info['sort']!=$sort)
+				{
+					$tb_category->setData(array('sort'=>$sort));
+					if($tb_category->update('id='.$category_id))
+					{
+						$flag = 1;
+					}
+				}
+			}
+		}
+		echo $flag;
+	}
+	/**
+	 * @brief 品牌分类排序
+	 */
+	public function brand_sort()
+	{
+		$brand_id = IFilter::act(IReq::get('id'),'int');
+		$sort = IFilter::act(IReq::get('sort'),'int');
+		$flag = 0;
+		if($brand_id)
+		{
+			$tb_brand = new IModel('brand');
+			$brand_info = $tb_brand->getObj('id='.$brand_id);
+			if(count($brand_info)>0)
+			{
+				if($brand_info['sort']!=$sort)
+				{
+					$tb_brand->setData(array('sort'=>$sort));
+					if($tb_brand->update('id='.$brand_id))
+					{
+						$flag = 1;
+					}
+				}
+			}
+		}
+		echo $flag;
+	}
+
+	//修改排序
+	public function ajax_sort()
+	{
+		$id   = IFilter::act(IReq::get('id'),'int');
+		$sort = IFilter::act(IReq::get('sort'),'int');
+
+		$goodsDB = new IModel('goods');
+		$goodsDB->setData(array('sort' => $sort));
+		$goodsDB->update("id = {$id}");
+	}
+
+	//更新库存
+	public function update_store()
+	{
+		$data     = IFilter::act(IReq::get('data'),'int'); //key => 商品ID或货品ID ; value => 库存数量
+		$goods_id = IFilter::act(IReq::get('goods_id'),'int');//存在即为货品
+		$goodsSum = array_sum($data);
+
+		if(!$data)
+		{
+			die(JSON::encode(array('result' => 'fail','data' => '商品数据不存在')));
+		}
+
+		//货品方式
+		if($goods_id)
+		{
+			$productDB = new IModel('products');
+			foreach($data as $key => $val)
+			{
+				$productDB->setData(array('store_nums' => $val));
+				$productDB->update('id = '.$key);
+			}
+		}
+		else
+		{
+			$goods_id = key($data);
+		}
+
+		$goodsDB = new IModel('goods');
+		$goodsDB->setData(array('store_nums' => $goodsSum));
+		$goodsDB->update('id = '.$goods_id);
+
+		die(JSON::encode(array('result' => 'success','data' => $goodsSum)));
+	}
+
+	//更新商品价格
+	public function update_price()
+	{
+		$data     = IFilter::act(IReq::get('data')); //key => 商品ID或货品ID ; value => 库存数量
+		$goods_id = IFilter::act(IReq::get('goods_id'),'int');//存在即为货品
+
+		if(!$data)
+		{
+			die(JSON::encode(array('result' => 'fail','data' => '商品数据不存在')));
+		}
+
+		//货品方式
+		if($goods_id)
+		{
+			$productDB  = new IModel('products');
+			$updateData = current($data);
+			foreach($data as $pid => $item)
+			{
+				$productDB->setData($item);
+				$productDB->update("id = ".$pid);
+			}
+		}
+		else
+		{
+			$goods_id   = key($data);
+			$updateData = current($data);
+		}
+
+		$goodsDB = new IModel('goods');
+		$goodsDB->setData($updateData);
+		$goodsDB->update('id = '.$goods_id);
+
+		die(JSON::encode(array('result' => 'success','data' => number_format($updateData['sell_price'],2))));
+	}
+
+	//更新商品推荐标签
+	public function update_commend()
+	{
+		$data = IFilter::act(IReq::get('data')); //key => 商品ID或货品ID ; value => commend值 1~4
+		if(!$data)
+		{
+			die(JSON::encode(array('result' => 'fail','data' => '商品数据不存在')));
+		}
+
+		$goodsCommendDB = new IModel('commend_goods');
+
+		//清理旧的commend数据
+		$goodsIdArray = array_keys($data);
+		$goodsCommendDB->del("goods_id in (".join(',',$goodsIdArray).")");
+
+		//插入新的commend数据
+		foreach($data as $id => $commend)
+		{
+			foreach($commend as $k => $value)
+			{
+				if($value > 0)
+				{
+					$goodsCommendDB->setData(array('commend_id' => $value,'goods_id' => $id));
+					$goodsCommendDB->add();
+				}
+			}
+		}
+		die(JSON::encode(array('result' => 'success')));
+	}
+
+	//商品共享
+	public function goods_share()
+	{
+		$idArray = explode(',',IReq::get('id'));
+		$id      = IFilter::act($idArray,'int');
+
+		$goodsDB = new IModel('goods');
+		$goodsData = $goodsDB->query('id in ('.join(',',$id).')');
+
+		foreach($goodsData as $key => $val)
+		{
+			$is_share = $val['is_share'] == 1 ? 0 : 1;
+			$goodsDB->setData(array('is_share' => $is_share));
+			$goodsDB->update('id = '.$val['id'].' and seller_id = 0');
+		}
+	}
+
+	/**
+	 * @brief 商品批量设置
+	 */
+	function goods_setting()
+	{
+		$idArray   = explode(',',IReq::get('id'));
+		$id        = IFilter::act($idArray,'int');
+		$seller_id = IFilter::act(IReq::get('seller_id'),'int');
+
+		if (empty($id))
+		{
+			exit('请选择您要操作的商品');
+		}
+		$data = array();
+		$data['goods_id']  = implode(",", $id);
+		$data['seller_id'] = $seller_id;
+
+		$this->layout = '';
+		$this->setRenderData($data);
+		$this->redirect('goods_setting');
+	}
+
+	/**
+	 * @brief 保存商品批量设置
+	 */
+	function goods_setting_save()
+	{
+		$idArray   = explode(',',IReq::get('goods_id', 'post'));
+		$seller_id = IFilter::act(IReq::get('seller_id'),'int');
+		$idArray   = IFilter::act($idArray,'int');
+
+		if (empty($idArray))
+		{
+			exit('请首先选择您要操作的商品');
+		}
+
+		$goodsObject = new goods_class($seller_id);
+		$goodsObject->multiUpdate($idArray, $_POST);
+		die('<script type="text/javascript">parent.artDialogCallback();</script>');
+	}
+	/**
+	 * @brief 商品分类ajax调整
+	 */
+	public function categoryAjax()
+	{
+		$id        = IFilter::act(IReq::get('id'));
+		$parent_id = IFilter::act(IReq::get('parent_id'));
+		if($id && is_array($id) && $parent_id)
+		{
+			foreach($id as $category_id)
+			{
+				$childString = goods_class::catChild($category_id);//父类ID不能死循环设置成其子分类
+				if($parent_id > 0 && stripos(",".$childString.",",",".$parent_id.",") !== false)
+				{
+					die(JSON::encode(array('result' => 'fail')));
+				}
+			}
+
+			$catDB     = new IModel('category');
+			$catDB->setData(array('parent_id' => $parent_id));
+			$result = $catDB->update('id in ('.join(",",$id).')');
+			if($result)
+			{
+				die(JSON::encode(array('result' => 'success')));
+			}
+		}
+		die(JSON::encode(array('result' => 'fail')));
+	}
+}

+ 1118 - 0
src/controllers/market.php

@@ -0,0 +1,1118 @@
+<?php
+/**
+ * @brief 营销模块
+ * @class Market
+ * @note  后台
+ */
+class Market extends IController implements adminAuthorization
+{
+	public $checkRight  = 'all';
+	public $layout = 'admin';
+
+	function init()
+	{
+
+	}
+
+	//修改代金券状态is_close和is_send
+	function ticket_status()
+	{
+		$status    = IFilter::act(IReq::get('status'));
+		$id        = IFilter::act(IReq::get('id'),'int');
+		$ticket_id = IFilter::act(IReq::get('ticket_id'));
+
+		if(!empty($id) && $status != null && $ticket_id != null)
+		{
+			$ticketObj = new IModel('prop');
+			if(is_array($id))
+			{
+				foreach($id as $val)
+				{
+					$where = 'id = '.$val;
+					$ticketRow = $ticketObj->getObj($where,$status);
+					if($ticketRow[$status]==1)
+					{
+						$ticketObj->setData(array($status => 0));
+					}
+					else
+					{
+						$ticketObj->setData(array($status => 1));
+					}
+					$ticketObj->update($where);
+				}
+			}
+			else
+			{
+				$where = 'id = '.$id;
+				$ticketRow = $ticketObj->getObj($where,$status);
+				if($ticketRow[$status]==1)
+				{
+					$ticketObj->setData(array($status => 0));
+				}
+				else
+				{
+					$ticketObj->setData(array($status => 1));
+				}
+				$ticketObj->update($where);
+			}
+			$this->redirect('ticket_more_list/ticket_id/'.$ticket_id);
+		}
+		else
+		{
+			$this->ticket_id = $ticket_id;
+			$this->redirect('ticket_more_list',false);
+			Util::showMessage('请选择要修改的id值');
+		}
+	}
+
+	//[代金券]添加,修改[单页]
+	function ticket_edit()
+	{
+		$id = IFilter::act(IReq::get('id'),'int');
+		if($id)
+		{
+			$ticketObj       = new IModel('ticket');
+			$where           = 'id = '.$id;
+			$this->ticketRow = $ticketObj->getObj($where);
+		}
+		$this->redirect('ticket_edit');
+	}
+
+	//[代金券]添加,修改[动作]
+	function ticket_edit_act()
+	{
+		$id        = IFilter::act(IReq::get('id'),'int');
+		$ticketObj = new IModel('ticket');
+
+		$dataArray = array(
+			'name'      => IFilter::act(IReq::get('name','post')),
+			'value'     => IFilter::act(IReq::get('value','post')),
+			'start_time'=> IFilter::act(IReq::get('start_time','post')),
+			'end_time'  => IFilter::act(IReq::get('end_time','post')),
+			'point'     => IFilter::act(IReq::get('point','post')),
+		);
+
+		$ticketObj->setData($dataArray);
+		if($id)
+		{
+			$where = 'id = '.$id;
+			$ticketObj->update($where);
+		}
+		else
+		{
+			$ticketObj->add();
+		}
+		$this->redirect('ticket_list');
+	}
+
+	//[代金券]生成[动作]
+	function ticket_create()
+	{
+		$propObj   = new IModel('prop');
+		$prop_num  = intval(IReq::get('num'));
+		$ticket_id = intval(IReq::get('ticket_id'));
+
+		if($prop_num && $ticket_id)
+		{
+			$prop_num  = ($prop_num > 5000) ? 5000 : $prop_num;
+			$ticketObj = new IModel('ticket');
+			$where     = 'id = '.$ticket_id;
+			$ticketRow = $ticketObj->getObj($where);
+
+			for($item = 0; $item < intval($prop_num); $item++)
+			{
+				$dataArray = array(
+					'condition' => $ticket_id,
+					'name'      => $ticketRow['name'],
+					'card_name' => 'T'.IHash::random(8),
+					'card_pwd'  => IHash::random(8),
+					'value'     => $ticketRow['value'],
+					'start_time'=> $ticketRow['start_time'],
+					'end_time'  => $ticketRow['end_time'],
+				);
+
+				//判断code码唯一性
+				$where = 'card_name = \''.$dataArray['card_name'].'\'';
+				$isSet = $propObj->getObj($where);
+				if(!empty($isSet))
+				{
+					$item--;
+					continue;
+				}
+				$propObj->setData($dataArray);
+				$propObj->add();
+			}
+			$logObj = new Log('db');
+			$logObj->write('operation',array("管理员:".$this->admin['admin_name'],"生成了代金券","面值:".$ticketRow['value']."元,数量:".$prop_num."张"));
+		}
+		$this->redirect('ticket_list');
+	}
+
+	//[代金券]删除
+	function ticket_del()
+	{
+		$id = IFilter::act(IReq::get('id'),'int');
+		if(!empty($id))
+		{
+			$ticketObj = new IModel('ticket');
+			$propObj   = new IModel('prop');
+			$propRow   = $propObj->getObj(" `type` = 0 and `condition` = {$id} and (is_close = 2 or (is_userd = 0 and is_send = 1)) ");
+
+			if($propRow)
+			{
+				$this->redirect('ticket_list',false);
+				Util::showMessage('无法删除代金券,其下还有正在使用的代金券');
+				exit;
+			}
+
+			$where = "id = {$id} ";
+			$ticketRow = $ticketObj->getObj($where);
+			if($ticketObj->del($where))
+			{
+				$where = " `type` = 0 and `condition` = {$id} ";
+				$propObj->del($where);
+
+				$logObj = new Log('db');
+				$logObj->write('operation',array("管理员:".$this->admin['admin_name'],"删除了一种代金券","代金券名称:".$ticketRow['name']));
+			}
+			$this->redirect('ticket_list');
+		}
+		else
+		{
+			$this->redirect('ticket_list',false);
+			Util::showMessage('请选择要删除的id值');
+		}
+	}
+
+	//[代金券详细]删除
+	function ticket_more_del()
+	{
+		$id        = IFilter::act(IReq::get('id'),'int');
+		$ticket_id = IFilter::act(IReq::get('ticket_id'),'int');
+		if($id)
+		{
+			$ticketObj = new IModel('ticket');
+			$ticketRow = $ticketObj->getObj('id = '.$ticket_id);
+			$logObj    = new Log('db');
+			$propObj   = new IModel('prop');
+			if(is_array($id))
+			{
+				$idStr = join(',',$id);
+				$where = ' id in ('.$idStr.')';
+				$logObj->write('operation',array("管理员:".$this->admin['admin_name'],"批量删除了实体代金券","代金券名称:".$ticketRow['name'].",数量:".count($id)));
+			}
+			else
+			{
+				$where = 'id = '.$id;
+				$logObj->write('operation',array("管理员:".$this->admin['admin_name'],"删除了1张实体代金券","代金券名称:".$ticketRow['name']));
+			}
+			$propObj->del($where);
+			$this->redirect('ticket_more_list/ticket_id/'.$ticket_id);
+		}
+		else
+		{
+			$this->ticket_id = $ticket_id;
+			$this->redirect('ticket_more_list',false);
+			Util::showMessage('请选择要删除的id值');
+		}
+	}
+
+	//[代金券详细] 列表
+	function ticket_more_list()
+	{
+		$this->ticket_id = IFilter::act(IReq::get('ticket_id'),'int');
+		$this->redirect('ticket_more_list');
+	}
+
+	//[代金券] 输出excel表格
+	function ticket_excel()
+	{
+		//代金券excel表存放地址
+		$ticket_id = IFilter::act(IReq::get('id'));
+
+		if($ticket_id)
+		{
+			$propObj = new IModel('prop');
+			$where   = 'type = 0';
+			$ticket_id_array = is_array($ticket_id) ? $ticket_id : array($ticket_id);
+
+			//当代金券数量没有时不允许备份excel
+			foreach($ticket_id_array as $key => $tid)
+			{
+				if(statistics::getTicketCount($tid) == 0)
+				{
+					unset($ticket_id_array[$key]);
+				}
+			}
+
+			if($ticket_id_array)
+			{
+				$id_num_str = join('","',$ticket_id_array);
+			}
+			else
+			{
+				$this->redirect('ticket_list',false);
+				Util::showMessage('实体代金券数量为0张,无法备份');
+				exit;
+			}
+
+			$where.= ' and `condition` in("'.$id_num_str.'")';
+			$propList = $propObj->query($where,'*','`condition` asc',10000);
+
+			$ticketFile = "ticket_".join("_",$ticket_id_array);
+			$reportObj = new report($ticketFile);
+			$reportObj->setTitle(array("名称","卡号","密码","面值","已被使用","是否关闭","是否发送","开始时间","结束时间"));
+			foreach($propList as $key => $val)
+			{
+				$is_userd = ($val['is_userd']=='1') ? '是':'否';
+				$is_close = ($val['is_close']=='1') ? '是':'否';
+				$is_send  = ($val['is_send']=='1') ? '是':'否';
+
+				$insertData = array(
+					$val['name'],
+					$val['card_name'],
+					$val['card_pwd'],
+					$val['value'].'元',
+					$is_userd,
+					$is_close,
+					$is_send,
+					$val['start_time'],
+					$val['end_time'],
+				);
+				$reportObj->setData($insertData);
+			}
+			$reportObj->toDownload();
+		}
+		else
+		{
+			$this->redirect('ticket_list',false);
+			Util::showMessage('请选择要操作的文件');
+		}
+	}
+
+	//[代金券]获取代金券数据
+	function getTicketList()
+	{
+		$ticketObj  = new IModel('ticket');
+		$ticketList = $ticketObj->query();
+		echo JSON::encode($ticketList);
+	}
+
+	//[促销活动] 添加修改 [单页]
+	function pro_rule_edit()
+	{
+		$id = IFilter::act(IReq::get('id'),'int');
+		if($id)
+		{
+			$promotionObj = new IModel('promotion');
+			$where = 'id = '.$id;
+			$this->promotionRow = $promotionObj->getObj($where);
+		}
+		$this->redirect('pro_rule_edit');
+	}
+
+	//[促销活动] 添加修改 [动作]
+	function pro_rule_edit_act()
+	{
+		$id           = IFilter::act(IReq::get('id'),'int');
+		$user_group   = IFilter::act(IReq::get('user_group','post'));
+		$promotionObj = new IModel('promotion');
+		if(is_string($user_group))
+		{
+			$user_group_str = $user_group;
+		}
+		else
+		{
+			$user_group_str = ",".join(',',$user_group).",";
+		}
+
+		$dataArray = array(
+			'name'       => IFilter::act(IReq::get('name','post')),
+			'condition'  => IFilter::act(IReq::get('condition','post')),
+			'is_close'   => IFilter::act(IReq::get('is_close','post')),
+			'start_time' => IFilter::act(IReq::get('start_time','post')),
+			'end_time'   => IFilter::act(IReq::get('end_time','post')),
+			'intro'      => IFilter::act(IReq::get('intro','post')),
+			'award_type' => IFilter::act(IReq::get('award_type','post')),
+			'type'       => 0,
+			'user_group' => $user_group_str,
+			'award_value'=> IFilter::act(IReq::get('award_value','post')),
+		);
+
+		$promotionObj->setData($dataArray);
+
+		if($id)
+		{
+			$where = 'id = '.$id;
+			$promotionObj->update($where);
+		}
+		else
+		{
+			$promotionObj->add();
+		}
+		$this->redirect('pro_rule_list');
+	}
+
+	//[促销活动] 删除
+	function pro_rule_del()
+	{
+		$id = IFilter::act(IReq::get('id'),'int');
+		if(!empty($id))
+		{
+			$promotionObj = new IModel('promotion');
+			if(is_array($id))
+			{
+				$idStr = join(',',$id);
+				$where = ' id in ('.$idStr.')';
+			}
+			else
+			{
+				$where = 'id = '.$id;
+			}
+			$promotionObj->del($where);
+			$this->redirect('pro_rule_list');
+		}
+		else
+		{
+			$this->redirect('pro_rule_list',false);
+			Util::showMessage('请选择要删除的促销活动');
+		}
+	}
+
+	//[限时抢购]添加,修改[单页]
+	function pro_speed_edit()
+	{
+		$id = IFilter::act(IReq::get('id'),'int');
+		if($id)
+		{
+			$promotionObj = new IModel('promotion');
+			$where = 'id = '.$id;
+			$promotionRow = $promotionObj->getObj($where);
+			if(empty($promotionRow))
+			{
+				$this->redirect('pro_speed_list');
+			}
+
+			//促销商品
+			$goodsObj = new IModel('goods');
+			$goodsRow = $goodsObj->getObj('id = '.$promotionRow['condition'],'id,name,sell_price,img');
+			if($goodsRow)
+			{
+				$result = array(
+					'isError' => false,
+					'data'    => $goodsRow,
+				);
+			}
+			else
+			{
+				$result = array(
+					'isError' => true,
+					'message' => '关联商品被删除,请重新选择要抢购的商品',
+				);
+			}
+
+			$promotionRow['goodsRow'] = JSON::encode($result);
+			$this->promotionRow = $promotionRow;
+		}
+		$this->redirect('pro_speed_edit');
+	}
+
+	//[限时抢购]添加,修改[动作]
+	function pro_speed_edit_act()
+	{
+		$id = IFilter::act(IReq::get('id'),'int');
+
+		$condition   = IFilter::act(IReq::get('condition','post'));
+		$award_value = IFilter::act(IReq::get('award_value','post'));
+		$user_group  = IFilter::act(IReq::get('user_group','post'));
+
+		if(is_string($user_group))
+		{
+			$user_group_str = $user_group;
+		}
+		else
+		{
+			$user_group_str = ",".join(',',$user_group).",";
+		}
+
+		$dataArray = array(
+			'id'         => $id,
+			'name'       => IFilter::act(IReq::get('name','post')),
+			'condition'  => $condition,
+			'award_value'=> $award_value,
+			'is_close'   => IFilter::act(IReq::get('is_close','post')),
+			'start_time' => IFilter::act(IReq::get('start_time','post')),
+			'end_time'   => IFilter::act(IReq::get('end_time','post')),
+			'intro'      => IFilter::act(IReq::get('intro','post')),
+			'type'       => 1,
+			'award_type' => 0,
+			'user_group' => $user_group_str,
+		);
+
+		if(!$condition || !$award_value)
+		{
+			$this->promotionRow = $dataArray;
+			$this->redirect('pro_speed_edit',false);
+			Util::showMessage('请添加促销的商品,并为商品填写价格');
+		}
+
+		$proObj = new IModel('promotion');
+		$proObj->setData($dataArray);
+		if($id)
+		{
+			$where = 'id = '.$id;
+			$proObj->update($where);
+		}
+		else
+		{
+			$proObj->add();
+		}
+		$this->redirect('pro_speed_list');
+	}
+
+	//[限时抢购]删除
+	function pro_speed_del()
+	{
+		$id = IFilter::act(IReq::get('id'),'int');
+		if(!empty($id))
+		{
+			$propObj = new IModel('promotion');
+			if(is_array($id))
+			{
+				$idStr = join(',',$id);
+				$where = ' id in ('.$idStr.')';
+			}
+			else
+			{
+				$where = 'id = '.$id;
+			}
+			$where .= ' and type = 1';
+			$propObj->del($where);
+			$this->redirect('pro_speed_list');
+		}
+		else
+		{
+			$this->redirect('pro_speed_list',false);
+			Util::showMessage('请选择要删除的id值');
+		}
+	}
+
+	//[团购]添加修改[单页]
+	function regiment_edit()
+	{
+		$id = IFilter::act(IReq::get('id'),'int');
+
+		if($id)
+		{
+			$regimentObj = new IModel('regiment');
+			$where       = 'id = '.$id;
+			$regimentRow = $regimentObj->getObj($where);
+			if(!$regimentRow)
+			{
+				$this->redirect('regiment_list');
+			}
+
+			//促销商品
+			$goodsObj = new IModel('goods');
+			$goodsRow = $goodsObj->getObj('id = '.$regimentRow['goods_id']);
+
+			$result = array(
+				'isError' => false,
+				'data'    => $goodsRow,
+			);
+			$regimentRow['goodsRow'] = JSON::encode($result);
+			$this->regimentRow = $regimentRow;
+		}
+		$this->redirect('regiment_edit');
+	}
+
+	//[团购]添加修改[动作]
+	function regiment_edit_act()
+	{
+		$id      = IFilter::act(IReq::get('id'),'int');
+		$goodsId = IFilter::act(IReq::get('goods_id'),'int');
+
+		$dataArray = array(
+			'id'        	=> $id,
+			'title'     	=> IFilter::act(IReq::get('title','post')),
+			'start_time'	=> IFilter::act(IReq::get('start_time','post')),
+			'end_time'  	=> IFilter::act(IReq::get('end_time','post')),
+			'is_close'      => IFilter::act(IReq::get('is_close','post')),
+			'intro'     	=> IFilter::act(IReq::get('intro','post')),
+			'goods_id'      => $goodsId,
+			'store_nums'    => IFilter::act(IReq::get('store_nums','post')),
+			'limit_min_count' => IFilter::act(IReq::get('limit_min_count','post'),'int'),
+			'limit_max_count' => IFilter::act(IReq::get('limit_max_count','post'),'int'),
+			'regiment_price'=> IFilter::act(IReq::get('regiment_price','post')),
+			'sort'          => IFilter::act(IReq::get('sort','post')),
+		);
+
+		$dataArray['limit_min_count'] = $dataArray['limit_min_count'] <= 0 ? 1 : $dataArray['limit_min_count'];
+		$dataArray['limit_max_count'] = $dataArray['limit_max_count'] <= 0 ? $dataArray['store_nums'] : $dataArray['limit_max_count'];
+
+		if($goodsId)
+		{
+			$goodsObj = new IModel('goods');
+			$where    = 'id = '.$goodsId;
+			$goodsRow = $goodsObj->getObj($where);
+
+			//处理上传图片
+			if(isset($_FILES['img']['name']) && $_FILES['img']['name'] != '')
+			{
+				$uploadObj = new PhotoUpload();
+				$photoInfo = $uploadObj->run();
+				$dataArray['img'] = $photoInfo['img']['img'];
+			}
+			else
+			{
+				$dataArray['img'] = $goodsRow['img'];
+			}
+
+			$dataArray['sell_price'] = $goodsRow['sell_price'];
+		}
+		else
+		{
+			$this->regimentRow = $dataArray;
+			$this->redirect('regiment_edit',false);
+			Util::showMessage('请选择要关联的商品');
+		}
+
+		$regimentObj = new IModel('regiment');
+		$regimentObj->setData($dataArray);
+
+		if($id)
+		{
+			$where = 'id = '.$id;
+			$regimentObj->update($where);
+		}
+		else
+		{
+			$regimentObj->add();
+		}
+		$this->redirect('regiment_list');
+	}
+
+	//[团购]删除
+	function regiment_del()
+	{
+		$id = IFilter::act(IReq::get('id'),'int');
+		if($id)
+		{
+			$regObj = new IModel('regiment');
+			if(is_array($id))
+			{
+				$id    = join(',',$id);
+			}
+			$where = ' id in ('.$id.')';
+			$regObj->del($where);
+			$this->redirect('regiment_list');
+		}
+		else
+		{
+			$this->redirect('regiment_list',false);
+			Util::showMessage('请选择要删除的id值');
+		}
+	}
+
+	//账户余额记录
+	function account_list()
+	{
+		$page       = intval(IReq::get('page')) ? IReq::get('page') : 1;
+		$event      = intval(IReq::get('event'));
+		$startDate  = IFilter::act(IReq::get('startDate'));
+		$endDate    = IFilter::act(IReq::get('endDate'));
+
+		$where      = "event != 3";
+		if($startDate)
+		{
+			$where .= " and time >= '{$startDate}' ";
+		}
+
+		if($endDate)
+		{
+			$temp   = $endDate.' 23:59:59';
+			$where .= " and time <= '{$temp}' ";
+		}
+
+		if($event)
+		{
+			$where .= " and event = $event ";
+		}
+
+		$accountObj = new IQuery('account_log');
+		$accountObj->where = $where;
+		$accountObj->order = 'id desc';
+		$accountObj->page  = $page;
+
+		$this->accountObj  = $accountObj;
+		$this->event       = $event;
+		$this->startDate   = $startDate;
+		$this->endDate     = $endDate;
+		$this->accountList = $accountObj->find();
+
+		$this->redirect('account_list');
+	}
+
+	//后台操作记录
+	function operation_list()
+	{
+		$page       = intval(IReq::get('page')) ? IReq::get('page') : 1;
+		$startDate  = IFilter::act(IReq::get('startDate'));
+		$endDate    = IFilter::act(IReq::get('endDate'));
+
+		$where      = "1";
+		if($startDate)
+		{
+			$where .= " and datetime >= '{$startDate}' ";
+		}
+
+		if($endDate)
+		{
+			$temp   = $endDate.' 23:59:59';
+			$where .= " and datetime <= '{$temp}' ";
+		}
+
+		$operationObj = new IQuery('log_operation');
+		$operationObj->where = $where;
+		$operationObj->order = 'id desc';
+		$operationObj->page  = $page;
+
+		$this->operationObj  = $operationObj;
+		$this->startDate     = $startDate;
+		$this->endDate       = $endDate;
+		$this->operationList = $operationObj->find();
+
+		$this->redirect('operation_list');
+	}
+
+	//清理后台管理员操作日志
+	function clear_log()
+	{
+		$type  = IReq::get('type');
+		$month = intval(IReq::get('month'));
+		if(!$month)
+		{
+			die('请填写要清理日志的月份');
+		}
+
+		switch($type)
+		{
+			case "account":
+			{
+				$logObj = new IModel('account_log');
+				$logObj->del("event = 1 and TIMESTAMPDIFF(MONTH,time,NOW()) >= '{$month}'");
+				$this->redirect('account_list');
+				break;
+			}
+			case "operation":
+			{
+				$logObj = new IModel('log_operation');
+				$logObj->del("TIMESTAMPDIFF(MONTH,datetime,NOW()) >= '{$month}'");
+				$this->redirect('operation_list');
+				break;
+			}
+			default:
+				die('缺少类别参数');
+		}
+	}
+
+	//修改结算账单
+	public function bill_edit()
+	{
+		$id = IFilter::act(IReq::get('id'),'int');
+		$billDB = new IModel('bill');
+		$this->billRow = $billDB->getObj('id = '.$id);
+		$this->redirect('bill_edit');
+	}
+
+	//结算单修改
+	public function bill_update()
+	{
+		$id = IFilter::act(IReq::get('id'),'int');
+		$pay_content = IFilter::act(IReq::get('pay_content'));
+		$is_pay = IFilter::act(IReq::get('is_pay'),'int');
+
+		if($id)
+		{
+			$data = array(
+				'admin_id' => $this->admin['admin_id'],
+				'pay_content' => $pay_content,
+				'is_pay' => $is_pay,
+			);
+
+			$billDB = new IModel('bill');
+
+			$data['pay_time'] = ($is_pay == 1) ? ITime::getDateTime() : "";
+
+			$billRow= $billDB->getObj('id = '.$id);
+			if(isset($billRow['order_ids']) && $billRow['order_ids'])
+			{
+				//更新订单商品关系表中的结算字段
+				$orderDB = new IModel('order');
+				$orderIdArray = explode(',',$billRow['order_ids']);
+				foreach($orderIdArray as $key => $val)
+				{
+					$orderDB->setData(array('is_checkout' => $is_pay));
+					$orderDB->update('id = '.$val);
+				}
+			}
+
+			$billDB->setData($data);
+			$billDB->update('id = '.$id);
+		}
+		$this->redirect('bill_list');
+	}
+
+	//结算单删除
+	public function bill_del()
+	{
+		$id = IFilter::act(IReq::get('id'),'int');
+
+		if($id)
+		{
+			$billDB = new IModel('bill');
+			$billDB->del('id = '.$id.' and is_pay = 0');
+		}
+
+		$this->redirect('bill_list');
+	}
+
+	//导出用户统计数据
+	public function user_report()
+	{
+		$start = IFilter::act(IReq::get('start'));
+		$end   = IFilter::act(IReq::get('end'));
+
+		$memberQuery = new IQuery('member as m');
+		$memberQuery->join   = "left join user as u on m.user_id=u.id";
+		$memberQuery->fields = "u.username,m.time,m.email,m.mobile";
+		$memberQuery->where  = "m.time between '".$start."' and '".$end." 23:59:59'";
+		$memberList          = $memberQuery->find();
+
+		$reportObj = new report('user');
+		$reportObj->setTitle(array("日期","用户名","邮箱","手机号"));
+		foreach($memberList as $k => $val)
+		{
+			$insertData = array($val['time'],$val['username'],$val['email'],$val['mobile']);
+			$reportObj->setData($insertData);
+		}
+		$reportObj->toDownload();
+	}
+
+	//导出人均消费数据
+	public function spanding_report()
+	{
+		$start = IFilter::act(IReq::get('start'));
+		$end   = IFilter::act(IReq::get('end'));
+
+		$reportObj = new report('spanding');
+		$reportObj->setTitle(array("日期","人均消费金额"));
+
+		$db = new IQuery('collection_doc');
+		$db->fields   = "sum(amount)/count(*) as count,`time`,DATE_FORMAT(`time`,'%Y-%m-%d') as `timeData`";
+		$db->where    = "pay_status = 1";
+		$db->group    = "DATE_FORMAT(`time`,'%Y-%m-%d') having `time` >= '{$start}' and `time` < '{$end} 23:59:59'";
+		$spandingList = $db->find();
+		foreach($spandingList as $k => $val)
+		{
+			$insertData = array($val['timeData'],$val['count']);
+			$reportObj->setData($insertData);
+		}
+		$reportObj->toDownload();
+	}
+
+	//导出销售数据
+	public function amount_report()
+	{
+		$start = IFilter::act(IReq::get('start'));
+		$end   = IFilter::act(IReq::get('end'));
+
+		$reportObj = new report('amount');
+		$reportObj->setTitle(array("订单生成日期","订单数量","商品销售额","商品成本","商品毛利"));
+
+		$orderDB   = new IModel('order');
+		$orderList = $orderDB->query(" pay_status = 1 and `create_time` between '{$start}' and '{$end} 23:59:59' "," DATE_FORMAT(`create_time`,'%Y-%m-%d') as ctime,id ","id asc");
+		if($orderList)
+		{
+			//按照订单时间组合订单ID
+			$ids = array();
+			foreach($orderList as $key => $val)
+			{
+				if(!isset($ids[$val['ctime']]))
+				{
+					$ids[$val['ctime']] = array();
+				}
+				$ids[$val['ctime']][] = $val['id'];
+			}
+
+			//获取订单数据
+			$db        = new IQuery('order_goods as og');
+			$db->join  = "left join goods as go on go.id = og.goods_id left join products as p on p.id = og.product_id ";
+			$db->fields= "og.*,go.cost_price as go_cost,p.cost_price as p_cost";
+			$db->order = "og.order_id asc";
+			$result    = array();
+			foreach($ids as $ctime => $idArray)
+			{
+				$db->where = "og.order_id in (".join(',',$idArray).") and og.is_send != 2";
+				$orderList = $db->find();
+
+				$result[$ctime] = array("orderNum" => count($idArray),"goods_sum" => 0,"goods_cost" => 0,"goods_diff" => 0);
+				foreach($orderList as $key => $val)
+				{
+					$result[$ctime]['goods_sum']  += $val['real_price'] * $val['goods_nums'];
+					$cost                          = $val['p_cost'] ? $val['p_cost'] : $val['go_cost'];
+					$result[$ctime]['goods_cost'] += $cost * $val['goods_nums'];
+				}
+				$result[$ctime]['goods_diff'] += $result[$ctime]['goods_sum'] - $result[$ctime]['goods_cost'];
+			}
+
+			foreach($result as $ctime => $val)
+			{
+				$insertData = array(
+					$ctime,
+					$val['orderNum'],
+					$val['goods_sum'],
+					$val['goods_cost'],
+					$val['goods_diff'],
+				);
+				$reportObj->setData($insertData);
+			}
+		}
+		$reportObj->toDownload();
+	}
+
+	//[特价商品]添加,修改[单页]
+	function sale_edit()
+	{
+		$id = IFilter::act(IReq::get('id'),'int');
+		if($id)
+		{
+			$promotionObj = new IModel('promotion');
+			$where = 'id = '.$id.' and award_type = 7';
+			$this->promotionRow = $promotionObj->getObj($where);
+			if(!$this->promotionRow)
+			{
+				IError::show("信息不存在");
+			}
+		}
+		$this->redirect('sale_edit');
+	}
+
+	//[特价商品]添加,修改[动作]
+	function sale_edit_act()
+	{
+		$id           = IFilter::act(IReq::get('id'),'int');
+		$award_value  = IFilter::act(IReq::get('award_value'),'int');
+		$type         = IFilter::act(IReq::get('type'));
+		$is_close     = IFilter::act(IReq::get('is_close','post'));
+		$intro        = array();//商品ID => 促销金额(或者折扣率)
+
+		$proObj = new IModel('promotion');
+		if($id)
+		{
+			//获取旧数据和原始价格
+			$proRow = $proObj->getObj("id = ".$id);
+			if(!$proRow)
+			{
+				IError::show('特价活动不存在');
+			}
+
+			if($proRow['is_close'] == 0)
+			{
+				$tempUpdate = JSON::decode($proRow['intro']);
+				if($tempUpdate)
+				{
+					foreach($tempUpdate as $gid => $g_discount)
+					{
+						goods_class::goodsDiscount($gid,$g_discount,"constant","add");
+					}
+				}
+			}
+		}
+
+		switch($type)
+		{
+			case 2:
+			{
+				$category = IFilter::act(IReq::get('category'),'int');
+				if(!$category)
+				{
+					IError::show(403,'商品分类信息没有设置');
+				}
+				$condition = join(",",$category);
+				$goodsData = Api::run("getCategoryExtendList",array("#categroy_id#",$condition),500);
+				foreach($goodsData as $key => $val)
+				{
+					$intro[$val['id']] = $val['sell_price'] - $val['sell_price']*$award_value/100;
+				}
+			}
+			break;
+
+			case 3:
+			{
+				$gid = IFilter::act(IReq::get('goods_id'),'int');
+				if(!$gid)
+				{
+					IError::show(403,'商品信息没有设置');
+				}
+				$condition   = join(",",$gid);
+				$goodsDB     = new IModel('goods');
+				$goodsData   = $goodsDB->query('id in ('.$condition.')');
+				$goods_price = IFilter::act(IReq::get('goods_price'),'float');
+
+				foreach($goodsData as $key => $val)
+				{
+					if(isset( $goods_price[$val['id']] ))
+					{
+						$intro[$val['id']] = $val['sell_price'] - $goods_price[$val['id']];
+					}
+				}
+			}
+			break;
+
+			case 4:
+			{
+				$condition = IFilter::act(IReq::get('brand_id'),'int');
+				if(!$condition)
+				{
+					IError::show(403,'品牌信息没有设置');
+				}
+				$goodsDB   = new IModel('goods');
+				$goodsData = $goodsDB->query("brand_id = ".$condition,"*","sort asc",500);
+				foreach($goodsData as $key => $val)
+				{
+					$intro[$val['id']] = $val['sell_price'] - $val['sell_price']*$award_value/100;
+				}
+			}
+			break;
+		}
+
+		if(!$intro)
+		{
+			IError::show(403,'商品信息不存在,请确定你选择的条件有商品');
+		}
+
+		//去掉重复促销的商品
+		$proData = $proObj->query("award_type = 7 and id != ".$id);
+		foreach($proData as $key => $val)
+		{
+			$temp  = JSON::decode($val['intro']);
+			$intro = array_diff_key($intro,$temp);
+		}
+
+		if(!$intro)
+		{
+			IError::show(403,'商品不能重复设置特价');
+		}
+
+		$dataArray = array(
+			'name'       => IFilter::act(IReq::get('name','post')),
+			'condition'  => $condition,
+			'award_value'=> $award_value,
+			'is_close'   => $is_close,
+			'start_time' => ITime::getDateTime(),
+			'intro'      => JSON::encode($intro),
+			'type'       => $type,
+			'award_type' => 7,
+			'sort'       => IFilter::act(IReq::get('sort'),'int'),
+		);
+
+		$proObj->setData($dataArray);
+		if($id)
+		{
+			$where = 'id = '.$id;
+			$proObj->update($where);
+		}
+		else
+		{
+			$proObj->add();
+		}
+
+		//开启
+		if($is_close == 0)
+		{
+			$tempUpdate = $intro;
+			if($tempUpdate)
+			{
+				foreach($tempUpdate as $gid => $g_discount)
+				{
+					goods_class::goodsDiscount($gid,$g_discount,"constant","reduce");
+				}
+			}
+		}
+		$this->redirect('sale_list');
+	}
+
+	//[特价商品]删除
+	function sale_del()
+	{
+		$id = IFilter::act(IReq::get('id'),'int');
+		if($id)
+		{
+			$proObj = new IModel('promotion');
+			if(is_array($id))
+			{
+				$idStr = join(',',$id);
+				$where = ' id in ('.$idStr.')';
+			}
+			else
+			{
+				$where = ' id = '.$id;
+			}
+			$where .= ' and award_type = 7 ';
+
+			//恢复特价商品价格
+			$proList = $proObj->query($where);
+			foreach($proList as $key => $val)
+			{
+				if($val['is_close'] == 0)
+				{
+					$tempUpdate = JSON::decode($val['intro']);
+					if($tempUpdate)
+					{
+						foreach($tempUpdate as $gid => $g_discount)
+						{
+							goods_class::goodsDiscount($gid,$g_discount,"constant","add");
+						}
+					}
+				}
+			}
+			$proObj->del($where);
+			$this->redirect('sale_list');
+		}
+		else
+		{
+			$this->redirect('sale_list',false);
+			Util::showMessage('请选择要删除的id值');
+		}
+	}
+
+	//商家销售报表明细导出
+	function sellerReport()
+	{
+		$where  = util::search(IReq::get('search'));
+		$billDB = new IQuery('bill as b');
+		$billDB->join   = "left join seller as s on s.id = b.seller_id";
+		$billDB->where  = $where;
+		$billDB->fields = "b.*,s.email,s.true_name";
+		$billDB->group  = "b.seller_id";
+		$billData       = $billDB->find();
+
+		$reportObj = new report('seller_bill');
+		$reportObj->setTitle(array("收款人email","收款人姓名","付款金额(元)","付款理由"));
+		if($billData)
+		{
+			foreach($billData as $key => $val)
+			{
+				$insertData = array(
+					$val['email'],
+					$val['true_name'],
+					$val['amount'],
+					$val['start_time']."至".$val['end_time']."货款",
+				);
+				$reportObj->setData($insertData);
+			}
+		}
+		$reportObj->toDownload();
+	}
+}

+ 914 - 0
src/controllers/member.php

@@ -0,0 +1,914 @@
+<?php
+/**
+ * @brief 会员模块
+ * @class Member
+ * @note  后台
+ */
+class Member extends IController implements adminAuthorization
+{
+	public $checkRight  = 'all';
+    public $layout='admin';
+	private $data = array();
+
+	function init()
+	{
+
+	}
+
+	/**
+	 * @brief 添加会员
+	 */
+	function member_edit()
+	{
+		$uid  = IFilter::act(IReq::get('uid'),'int');
+
+		//编辑会员信息读取会员信息
+		if($uid)
+		{
+			$userDB = new IQuery('user as u');
+			$userDB->join = 'left join member as m on u.id = m.user_id';
+			$userDB->where= 'u.id = '.$uid;
+			$userInfo = $userDB->find();
+
+			if($userInfo)
+			{
+				$this->userInfo = current($userInfo);
+			}
+			else
+			{
+				$this->member_list();
+				Util::showMessage("没有找到相关记录!");
+				exit;
+			}
+		}
+		$this->redirect('member_edit');
+	}
+
+	//保存会员信息
+	function member_save()
+	{
+		$user_id    = IFilter::act(IReq::get('user_id'),'int');
+		$user_name  = IFilter::act(IReq::get('username'));
+		$email      = IFilter::act(IReq::get('email'));
+		$password   = IFilter::act(IReq::get('password'));
+		$repassword = IFilter::act(IReq::get('repassword'));
+		$group_id   = IFilter::act(IReq::get('group_id'),'int');
+		$truename   = IFilter::act(IReq::get('true_name'));
+		$sex        = IFilter::act(IReq::get('sex'),'int');
+		$telephone  = IFilter::act(IReq::get('telephone'));
+		$mobile     = IFilter::act(IReq::get('mobile'));
+		$province   = IFilter::act(IReq::get('province'),'int');
+		$city       = IFilter::act(IReq::get('city'),'int');
+		$area       = IFilter::act(IReq::get('area'),'int');
+		$contact_addr = IFilter::act(IReq::get('contact_addr'));
+		$zip        = IFilter::act(IReq::get('zip'));
+		$qq         = IFilter::act(IReq::get('qq'));
+		$exp        = IFilter::act(IReq::get('exp'),'int');
+		$point      = IFilter::act(IReq::get('point'),'int');
+		$status     = IFilter::act(IReq::get('status'),'int');
+
+		$_POST['area'] = "";
+		if($province && $city && $area)
+		{
+			$_POST['area'] = ",{$province},{$city},{$area},";
+		}
+
+		if(!$user_id && $password == '')
+		{
+			$this->setError('请输入密码!');
+		}
+
+		if($password != $repassword)
+		{
+			$this->setError('两次输入的密码不一致!');
+		}
+
+		//创建会员操作类
+		$userDB   = new IModel("user");
+		$memberDB = new IModel("member");
+
+		if($userDB->getObj("username='".$user_name."' and id != ".$user_id))
+		{
+			$this->setError('用户名重复');
+		}
+
+		if($email && $memberDB->getObj("email='".$email."' and user_id != ".$user_id))
+		{
+			$this->setError('邮箱重复');
+		}
+
+		if($mobile && $memberDB->getObj("mobile='".$mobile."' and user_id != ".$user_id))
+		{
+			$this->setError('手机号码重复');
+		}
+
+		//操作失败表单回填
+		if($errorMsg = $this->getError())
+		{
+			$this->userInfo = $_POST;
+			$this->redirect('member_edit',false);
+			Util::showMessage($errorMsg);
+		}
+
+		$member = array(
+			'email'        => $email,
+			'true_name'    => $truename,
+			'telephone'    => $telephone,
+			'mobile'       => $mobile,
+			'area'         => $_POST['area'],
+			'contact_addr' => $contact_addr,
+			'qq'           => $qq,
+			'sex'          => $sex,
+			'zip'          => $zip,
+			'exp'          => $exp,
+			'point'        => $point,
+			'group_id'     => $group_id,
+			'status'       => $status,
+		);
+
+		//添加新会员
+		if(!$user_id)
+		{
+			$user = array(
+				'username' => $user_name,
+				'password' => md5($password),
+			);
+			$userDB->setData($user);
+			$user_id = $userDB->add();
+
+			$member['user_id'] = $user_id;
+			$member['time']    = ITime::getDateTime();
+
+			$memberDB->setData($member);
+			$memberDB->add();
+		}
+		//编辑会员
+		else
+		{
+			$user = array(
+				'username' => $user_name,
+			);
+			//修改密码
+			if($password)
+			{
+				$user['password'] = md5($password);
+			}
+			$userDB->setData($user);
+			$userDB->update('id = '.$user_id);
+
+			$member_info = $memberDB->getObj('user_id='.$user_id);
+
+			//修改积分记录日志
+			if($point != $member_info['point'])
+			{
+				$ctrlType = $point > $member_info['point'] ? '增加' : '减少';
+				$diffPoint= $point-$member_info['point'];
+
+				$pointObj = new Point();
+				$pointConfig = array(
+					'user_id' => $user_id,
+					'point'   => $diffPoint,
+					'log'     => '管理员'.$this->admin['admin_name'].'将积分'.$ctrlType.$diffPoint.'积分',
+				);
+				$pointObj->update($pointConfig);
+			}
+
+			$memberDB->setData($member);
+			$memberDB->update("user_id = ".$user_id);
+		}
+		$this->redirect('member_list');
+	}
+
+	/**
+	 * @brief 会员列表
+	 */
+	function member_list()
+	{
+		$search = IFilter::act(IReq::get('search'),'strict');
+		$keywords = IFilter::act(IReq::get('keywords'));
+		$where = ' 1 ';
+		if($search && $keywords)
+		{
+			$where .= " and $search like '%{$keywords}%' ";
+		}
+		$this->data['search'] = $search;
+		$this->data['keywords'] = $keywords;
+		$this->data['where'] = $where;
+		$tb_user_group = new IModel('user_group');
+		$data_group = $tb_user_group->query();
+		$group      = array();
+		foreach($data_group as $value)
+		{
+			$group[$value['id']] = $value['group_name'];
+		}
+		$this->data['group'] = $group;
+		$this->setRenderData($this->data);
+		$this->redirect('member_list');
+	}
+
+	/**
+	 * 用户余额管理页面
+	 */
+	function member_balance()
+	{
+		$this->layout = '';
+		$this->redirect('member_balance');
+	}
+	/**
+	 * @brief 删除至回收站
+	 */
+	function member_reclaim()
+	{
+		$user_ids = IReq::get('check');
+		$user_ids = is_array($user_ids) ? $user_ids : array($user_ids);
+		$user_ids = IFilter::act($user_ids,'int');
+		if($user_ids)
+		{
+			$ids = implode(',',$user_ids);
+			if($ids)
+			{
+				$tb_member = new IModel('member');
+				$tb_member->setData(array('status'=>'2'));
+				$where = "user_id in (".$ids.")";
+				$tb_member->update($where);
+			}
+		}
+		$this->member_list();
+	}
+	//批量用户余额操作
+    function member_recharge()
+    {
+    	$id       = IFilter::act(IReq::get('check'),'int');
+    	$balance  = IFilter::act(IReq::get('balance'),'float');
+    	$type     = IFIlter::act(IReq::get('type')); //操作类型 recharge充值,withdraw提现金
+    	$even     = '';
+
+    	if(!$id)
+    	{
+			die(JSON::encode(array('flag' => 'fail','message' => '请选择要操作的用户')));
+			return;
+    	}
+
+    	//执行写入操作
+    	$id = is_array($id) ? join(',',$id) : $id;
+    	$memberDB = new IModel('member');
+    	$memberData = $memberDB->query('user_id in ('.$id.')');
+
+		foreach($memberData as $value)
+		{
+			//用户余额进行的操作记入account_log表
+			$log = new AccountLog();
+			$config=array
+			(
+				'user_id'  => $value['user_id'],
+				'admin_id' => $this->admin['admin_id'],
+				'event'    => $type,
+				'num'      => $balance,
+			);
+			$re = $log->write($config);
+			if($re == false)
+			{
+				die(JSON::encode(array('flag' => 'fail','message' => $log->error)));
+			}
+		}
+		die(JSON::encode(array('flag' => 'success')));
+    }
+	/**
+	 * @brief 用户组添加
+	 */
+	function group_edit()
+	{
+		$gid = (int)IReq::get('gid');
+		//编辑会员等级信息 读取会员等级信息
+		if($gid)
+		{
+			$tb_user_group = new IModel('user_group');
+			$group_info = $tb_user_group->query("id=".$gid);
+
+			if(is_array($group_info) && ($info=$group_info[0]))
+			{
+				$this->data['group'] = array(
+					'group_id'	=>	$info['id'],
+					'group_name'=>	$info['group_name'],
+					'discount'	=>	$info['discount'],
+					'minexp'	=>	$info['minexp'],
+					'maxexp'	=>	$info['maxexp']
+				);
+			}
+			else
+			{
+				$this->redirect('group_list',false);
+				Util::showMessage("没有找到相关记录!");
+				return;
+			}
+		}
+		$this->setRenderData($this->data);
+		$this->redirect('group_edit');
+	}
+
+	/**
+	 * @brief 保存用户组修改
+	 */
+	function group_save()
+	{
+		$group_id = IFilter::act(IReq::get('group_id'),'int');
+		$maxexp   = IFilter::act(IReq::get('maxexp'),'int');
+		$minexp   = IFilter::act(IReq::get('minexp'),'int');
+		$discount = IFilter::act(IReq::get('discount'),'float');
+		$group_name = IFilter::act(IReq::get('group_name'));
+
+		$group = array(
+			'maxexp' => $maxexp,
+			'minexp' => $minexp,
+			'discount' => $discount,
+			'group_name' => $group_name
+		);
+
+		if($discount > 100)
+		{
+			$errorMsg = '折扣率不能大于100';
+		}
+
+		if($maxexp <= $minexp)
+		{
+			$errorMsg = '最大经验值必须大于最小经验值';
+		}
+
+		if(isset($errorMsg) && $errorMsg)
+		{
+			$group['group_id'] = $group_id;
+			$data = array($group);
+
+			$this->setRenderData($data);
+			$this->redirect('group_edit',false);
+			Util::showMessage($errorMsg);
+			exit;
+		}
+		$tb_user_group = new IModel("user_group");
+		$tb_user_group->setData($group);
+
+		if($group_id)
+		{
+			$affected_rows = $tb_user_group->update("id=".$group_id);
+			$this->redirect('group_list');
+		}
+		else
+		{
+			$tb_user_group->add();
+			$this->redirect('group_list');
+		}
+	}
+
+	/**
+	 * @brief 删除会员组
+	 */
+	function group_del()
+	{
+		$group_ids = IReq::get('check');
+		$group_ids = is_array($group_ids) ? $group_ids : array($group_ids);
+		$group_ids = IFilter::act($group_ids,'int');
+		if($group_ids)
+		{
+			$ids = implode(',',$group_ids);
+			if($ids)
+			{
+				$tb_user_group = new IModel('user_group');
+				$where = "id in (".$ids.")";
+				$tb_user_group->del($where);
+			}
+		}
+		$this->redirect('group_list');
+	}
+
+	/**
+	 * @brief 回收站
+	 */
+	function recycling()
+	{
+		$search = IReq::get('search');
+		$keywords = IReq::get('keywords');
+		$search_sql = IFilter::act($search,'strict');
+		$keywords = IFilter::act($keywords,'strict');
+
+		$where = ' 1 ';
+		if($search && $keywords)
+		{
+			$where .= " and $search_sql like '%{$keywords}%' ";
+		}
+		$this->data['search'] = $search;
+		$this->data['keywords'] = $keywords;
+		$this->data['where'] = $where;
+		$tb_user_group = new IModel('user_group');
+		$data_group = $tb_user_group->query();
+		$data_group = is_array($data_group) ? $data_group : array();
+		$group = array();
+		foreach($data_group as $value)
+		{
+			$group[$value['id']] = $value['group_name'];
+		}
+		$this->data['group'] = $group;
+		$this->setRenderData($this->data);
+		$this->redirect('recycling');
+	}
+
+	/**
+	 * @brief 彻底删除会员
+	 */
+	function member_del()
+	{
+		$user_ids = IReq::get('check');
+		$user_ids = is_array($user_ids) ? $user_ids : array($user_ids);
+		$user_ids = IFilter::act($user_ids,'int');
+		if($user_ids)
+		{
+			$ids = implode(',',$user_ids);
+
+			if($ids)
+			{
+				$tb_member = new IModel('member');
+				$where = "user_id in (".$ids.")";
+				$tb_member->del($where);
+
+				$tb_user = new IModel('user');
+				$where = "id in (".$ids.")";
+				$tb_user->del($where);
+
+				$logObj = new log('db');
+				$logObj->write('operation',array("管理员:".$this->admin['admin_name'],"删除了用户","被删除的用户ID为:".$ids));
+			}
+		}
+		$this->redirect('member_list');
+	}
+
+	/**
+	 * @brief 从回收站还原会员
+	 */
+	function member_restore()
+	{
+		$user_ids = IReq::get('check');
+		$user_ids = is_array($user_ids) ? $user_ids : array($user_ids);
+		if($user_ids)
+		{
+			$user_ids = IFilter::act($user_ids,'int');
+			$ids = implode(',',$user_ids);
+			if($ids)
+			{
+				$tb_member = new IModel('member');
+				$tb_member->setData(array('status'=>'1'));
+				$where = "user_id in (".$ids.")";
+				$tb_member->update($where);
+			}
+		}
+		$this->redirect('recycling');
+	}
+
+	//[提现管理] 删除
+	function withdraw_del()
+	{
+		$id = IFilter::act(IReq::get('id'));
+
+		if($id)
+		{
+			$id = IFilter::act($id,'int');
+			$withdrawObj = new IModel('withdraw');
+
+			if(is_array($id))
+			{
+				$idStr = join(',',$id);
+				$where = ' id in ('.$idStr.')';
+			}
+			else
+			{
+				$where = 'id = '.$id;
+			}
+
+			$withdrawObj->del($where);
+			$this->redirect('withdraw_recycle');
+		}
+		else
+		{
+			$this->redirect('withdraw_recycle',false);
+			Util::showMessage('请选择要删除的数据');
+		}
+	}
+
+	//[提现管理] 回收站 删除,恢复
+	function withdraw_update()
+	{
+		$id   = IFilter::act( IReq::get('id') , 'int' );
+		$type = IReq::get('type') ;
+
+		if(!empty($id))
+		{
+			$withdrawObj = new IModel('withdraw');
+
+			$is_del = ($type == 'res') ? '0' : '1';
+			$dataArray = array(
+				'is_del' => $is_del
+			);
+
+			if(is_array($id))
+			{
+				$idStr = join(',',$id);
+				$where = ' id in ('.$idStr.')';
+			}
+			else
+			{
+				$where = 'id = '.$id;
+			}
+
+			$dataArray = array(
+				'is_del' => $is_del,
+			);
+
+			$withdrawObj->setData($dataArray);
+			$withdrawObj->update($where);
+			$this->redirect('withdraw_list');
+		}
+		else
+		{
+			if($type == 'del')
+			{
+				$this->redirect('withdraw_list',false);
+			}
+			else
+			{
+				$this->redirect('withdraw_recycle',false);
+			}
+			Util::showMessage('请选择要删除的数据');
+		}
+	}
+
+	//[提现管理] 详情展示
+	function withdraw_detail()
+	{
+		$id = IFilter::act( IReq::get('id'),'int' );
+
+		if($id)
+		{
+			$withdrawObj = new IModel('withdraw');
+			$where       = 'id = '.$id;
+			$this->withdrawRow = $withdrawObj->getObj($where);
+
+			$userDB = new IModel('user as u,member as m');
+			$this->userRow = $userDB->getObj('u.id = m.user_id and u.id = '.$this->withdrawRow['user_id']);
+			$this->redirect('withdraw_detail',false);
+		}
+		else
+		{
+			$this->redirect('withdraw_list');
+		}
+	}
+
+	//[提现管理] 修改提现申请的状态
+	function withdraw_status()
+	{
+		$id      = IFilter::act( IReq::get('id'),'int');
+		$re_note = IFilter::act( IReq::get('re_note'),'string');
+		$status  = IFilter::act(IReq::get('status'),'int');
+
+		if($id && $status)
+		{
+			$withdrawObj = new IModel('withdraw');
+			//提现成功
+			if($status == 2)
+			{
+				$withdrawRow = $withdrawObj->getObj('id = '.$id);
+
+				//用户余额进行的操作记入account_log表
+				$log    = new AccountLog();
+				$config = array
+				(
+					'user_id'  => $withdrawRow['user_id'],
+					'admin_id' => $this->admin['admin_id'],
+					'event'    => "withdraw",
+					'num'      => $withdrawRow['amount'],
+				);
+				$result = $log->write($config);
+				if($result == false)
+				{
+					$this->withdraw_detail();
+					Util::showMessage($log->error);
+				}
+			}
+
+			$dataArray = array(
+				're_note'=> $re_note,
+				'status' => $status,
+			);
+			$withdrawObj->setData($dataArray);
+			$where = "`id`= {$id} AND `status` = 0";
+			$withdrawObj->update($where);
+
+			//管理员操作日志
+			$logObj = new log('db');
+			$logObj->write('operation',array("管理员:".$this->admin['admin_name'],"修改了提现申请","ID值为:".$id));
+
+			$this->withdraw_detail();
+			Util::showMessage("更新成功");
+		}
+		else
+		{
+			$this->redirect('withdraw_list');
+		}
+	}
+
+	/**
+	 * @brief 商家修改页面
+	 */
+	public function seller_edit()
+	{
+		$seller_id = IFilter::act(IReq::get('id'),'int');
+
+		//修改页面
+		if($seller_id)
+		{
+			$sellerDB        = new IModel('seller');
+			$this->sellerRow = $sellerDB->getObj('id = '.$seller_id);
+		}
+		$this->redirect('seller_edit');
+	}
+
+	/**
+	 * @brief 商户的增加动作
+	 */
+	public function seller_add()
+	{
+		$seller_id   = IFilter::act(IReq::get('id'),'int');
+		$seller_name = IFilter::act(IReq::get('seller_name'));
+		$email       = IFilter::act(IReq::get('email'));
+		$password    = IFilter::act(IReq::get('password'));
+		$repassword  = IFilter::act(IReq::get('repassword'));
+		$truename    = IFilter::act(IReq::get('true_name'));
+		$phone       = IFilter::act(IReq::get('phone'));
+		$mobile      = IFilter::act(IReq::get('mobile'));
+		$province    = IFilter::act(IReq::get('province'),'int');
+		$city        = IFilter::act(IReq::get('city'),'int');
+		$area        = IFilter::act(IReq::get('area'),'int');
+		$cash        = IFilter::act(IReq::get('cash'),'float');
+		$is_vip      = IFilter::act(IReq::get('is_vip'),'int');
+		$is_lock     = IFilter::act(IReq::get('is_lock'),'int');
+		$address     = IFilter::act(IReq::get('address'));
+		$account     = IFilter::act(IReq::get('account'));
+		$server_num  = IFilter::act(IReq::get('server_num'));
+		$home_url    = IFilter::act(IReq::get('home_url'));
+		$sort        = IFilter::act(IReq::get('sort'),'int');
+
+		if(!$seller_id && $password == '')
+		{
+			$errorMsg = '请输入密码!';
+		}
+
+		if($password != $repassword)
+		{
+			$errorMsg = '两次输入的密码不一致!';
+		}
+
+		//创建商家操作类
+		$sellerDB = new IModel("seller");
+
+		if($sellerDB->getObj("seller_name = '{$seller_name}' and id != {$seller_id}"))
+		{
+			$errorMsg = "登录用户名重复";
+		}
+		else if($sellerDB->getObj("true_name = '{$truename}' and id != {$seller_id}"))
+		{
+			$errorMsg = "商户真实全程重复";
+		}
+
+		//操作失败表单回填
+		if(isset($errorMsg))
+		{
+			$this->sellerRow = $_POST;
+			$this->redirect('seller_edit',false);
+			Util::showMessage($errorMsg);
+		}
+
+		//待更新的数据
+		$sellerRow = array(
+			'true_name' => $truename,
+			'account'   => $account,
+			'phone'     => $phone,
+			'mobile'    => $mobile,
+			'email'     => $email,
+			'address'   => $address,
+			'is_vip'    => $is_vip,
+			'is_lock'   => $is_lock,
+			'cash'      => $cash,
+			'province'  => $province,
+			'city'      => $city,
+			'area'      => $area,
+			'server_num'=> $server_num,
+			'home_url'  => $home_url,
+			'sort'      => $sort,
+		);
+
+		//附件上传$_FILE
+		if($_FILES)
+		{
+			$uploadObj = new PhotoUpload();
+			$uploadObj->setIterance(false);
+			$photoInfo = $uploadObj->run();
+
+			//商户资质上传
+			if(isset($photoInfo['paper_img']['img']) && file_exists($photoInfo['paper_img']['img']))
+			{
+				$sellerRow['paper_img'] = $photoInfo['paper_img']['img'];
+			}
+
+			//logo图片处理
+			if(isset($photoInfo['logo']['img']) && file_exists($photoInfo['logo']['img']))
+			{
+				$sellerRow['logo'] = $photoInfo['logo']['img'];
+			}
+		}
+
+		//添加新会员
+		if(!$seller_id)
+		{
+			$sellerRow['seller_name'] = $seller_name;
+			$sellerRow['password']    = md5($password);
+			$sellerRow['create_time'] = ITime::getDateTime();
+
+			$sellerDB->setData($sellerRow);
+			$sellerDB->add();
+		}
+		//编辑会员
+		else
+		{
+			//修改密码
+			if($password)
+			{
+				$sellerRow['password'] = md5($password);
+			}
+
+			$sellerDB->setData($sellerRow);
+			$sellerDB->update("id = ".$seller_id);
+		}
+		$this->redirect('seller_list');
+	}
+	/**
+	 * @brief 商户的删除动作
+	 */
+	public function seller_del()
+	{
+		$id = IFilter::act(IReq::get('id'),'int');
+		$sellerDB = new IModel('seller');
+		$data = array('is_del' => 1);
+		$sellerDB->setData($data);
+
+		if(is_array($id))
+		{
+			$sellerDB->update('id in ('.join(",",$id).')');
+		}
+		else
+		{
+			$sellerDB->update('id = '.$id);
+		}
+		$this->redirect('seller_list');
+	}
+	/**
+	 * @brief 商户的回收站删除动作
+	 */
+	public function seller_recycle_del()
+	{
+		$id = IFilter::act(IReq::get('id'),'int');
+		$sellerDB = new IModel('seller');
+		$goodsDB  = new IModel('goods');
+		$merch_ship_infoDB = new IModel('merch_ship_info');
+		$specDB = new IModel('spec');
+
+		if(is_array($id))
+		{
+			$id = join(",",$id);
+		}
+
+		$sellerDB->del('id in ('.$id.')');
+		$goodsDB->del('seller_id in ('.$id.')');
+		$merch_ship_infoDB->del('seller_id in ('.$id.')');
+		$specDB->del('seller_id in ('.$id.')');
+
+		$this->redirect('seller_recycle_list');
+	}
+	/**
+	 * @brief 商户的回收站恢复动作
+	 */
+	public function seller_recycle_restore()
+	{
+		$id = IFilter::act(IReq::get('id'),'int');
+		$sellerDB = new IModel('seller');
+		$data = array('is_del' => 0);
+		$sellerDB->setData($data);
+		if(is_array($id))
+		{
+			$sellerDB->update('id in ('.join(",",$id).')');
+		}
+		else
+		{
+			$sellerDB->update('id = '.$id);
+		}
+
+		$this->redirect('seller_recycle_list');
+	}
+	//商户状态ajax
+	public function ajax_seller_lock()
+	{
+		$id   = IFilter::act(IReq::get('id'));
+		$lock = IFilter::act(IReq::get('lock'));
+		$sellerObj = new IModel('seller');
+		$sellerObj->setData(array('is_lock' => $lock));
+		$sellerObj->update("id = ".$id);
+
+		//短信通知状态修改
+		$sellerRow = $sellerObj->getObj('id = '.$id);
+		if(isset($sellerRow['mobile']) && $sellerRow['mobile'])
+		{
+			$result = $lock == 0 ? "正常" : "锁定";
+			$content = smsTemplate::sellerCheck(array('{result}' => $result));
+			$result = Hsms::send($sellerRow['mobile'],$content,0);
+		}
+	}
+
+    /**
+     * 筛选用户
+     */
+    public function filter_user()
+    {
+		$where   = array();
+		$userIds = '';
+    	$search  = IFilter::act(IReq::get('search'),'strict');
+    	$search  = $search ? $search : array();
+
+    	foreach($search as $key => $val)
+    	{
+    		if($val)
+    		{
+    			$where[] = $key.'"'.$val.'"';
+    		}
+    	}
+
+    	//有筛选条件
+    	if($where)
+    	{
+	    	$userDB = new IQuery('user as u');
+	    	$userDB->join  = 'left join member as m on u.id = m.user_id';
+	    	$userDB->fields= 'u.id';
+	    	$userDB->where = join(" and ",$where);
+	    	$userData      = $userDB->find();
+	    	$tempArray     = array();
+	    	foreach($userData as $key => $item)
+	    	{
+	    		$tempArray[] = $item['id'];
+	    	}
+	    	$userIds = join(',',$tempArray);
+
+	    	if(!$userIds)
+	    	{
+	    		die('<script type="text/javascript">alert("没有找到用户信息,请重新输入条件");window.history.go(-1);</script>');
+	    	}
+    	}
+
+    	die('<script type="text/javascript">parent.searchUserCallback("'.$userIds.'");</script>');
+    }
+
+	/**
+     * 筛选商户
+     */
+    public function filter_seller()
+    {
+		$where     = array();
+		$sellerIds = '';
+    	$search    = IFilter::act(IReq::get('search'),'strict');
+    	$search    = $search ? $search : array();
+
+    	foreach($search as $key => $val)
+    	{
+    		if($val)
+    		{
+    			$where[] = $key.'"'.$val.'"';
+    		}
+    	}
+
+    	//有筛选条件
+    	if($where)
+    	{
+	    	$sellerDB = new IQuery('seller');
+	    	$sellerDB->fields= 'id';
+	    	$sellerDB->where   = join(" and ",$where);
+	    	$sellerData      = $sellerDB->find();
+	    	$tempArray       = array();
+	    	foreach($sellerData as $key => $item)
+	    	{
+	    		$tempArray[] = $item['id'];
+	    	}
+	    	$sellerIds = join(',',$tempArray);
+
+	    	if(!$sellerIds)
+	    	{
+	    		die('<script type="text/javascript">alert("没有找到商户信息,请重新输入条件");window.history.go(-1);</script>');
+	    	}
+    	}
+
+    	die('<script type="text/javascript">parent.searchSellerCallback("'.$sellerIds.'");</script>');
+    }
+}

+ 400 - 0
src/controllers/message.php

@@ -0,0 +1,400 @@
+<?php
+/**
+ * @brief 消息模块
+ * @class Message
+ * @note  后台
+ */
+class Message extends IController implements adminAuthorization
+{
+	public $checkRight = 'all';
+	public $layout     = 'admin';
+	private $data      = array();
+
+	function init()
+	{
+
+	}
+
+	//删除电子邮箱订阅
+	function registry_del()
+	{
+		$ids = IFilter::act(IReq::get('id'),'int');
+		if(!$ids)
+		{
+			$this->redirect('registry_list',false);
+			Util::showMessage('请选择要删除的邮箱');
+			exit;
+		}
+
+		if(is_array($ids))
+		{
+			$ids = join(',',$ids);
+		}
+
+		$registryObj = new IModel('email_registry');
+		$registryObj->del('id in ('.$ids.')');
+		$this->redirect('registry_list');
+	}
+
+	/**
+	 * @brief 删除登记的到货通知邮件
+	 */
+	function notify_del()
+	{
+		$notify_ids = IFilter::act(IReq::get('check'),'int');
+		if($notify_ids)
+		{
+			$ids = join(',',$notify_ids);
+			$tb_notify = new IModel('notify_registry');
+			$where = "id in (".$ids.")";
+			$tb_notify->del($where);
+		}
+		$this->redirect('notify_list');
+	}
+
+	/**
+	 * @brief 发送到货通知邮件
+	 */
+	function notify_email_send()
+	{
+		$smtp  = new SendMail();
+		$error = $smtp->getError();
+
+		if($error)
+		{
+			$return = array(
+				'isError' => true,
+				'message' => $error,
+			);
+			echo JSON::encode($return);
+			exit;
+		}
+
+		$notify_ids = IFilter::act(IReq::get('notifyid'));
+		if($notify_ids && is_array($notify_ids))
+		{
+			$ids = join(',',$notify_ids);
+			$query = new IQuery("notify_registry as notify");
+			$query->join   = "right join goods as goods on notify.goods_id=goods.id ";
+			$query->fields = "notify.*,goods.name as goods_name,goods.store_nums";
+			$query->where  = "notify.id in(".$ids.")";
+			$items = $query->find();
+
+			//库存大于0,且处于未发送邮件状态的 发送通知
+			$succeed = 0;
+			$failed  = 0;
+			$tb_notify_registry = new IModel('notify_registry');
+
+			foreach($items as $value)
+			{
+				// 十进制转换为二进制
+				$notify_status = decbin($value['notify_status']);
+				// 是否已发送邮件
+				if (1 == ($notify_status & 1)) {
+					$failed++;
+					continue;
+				}
+
+				$body   = mailTemplate::notify(array('{goodsName}' => $value['goods_name'],'{url}' => IUrl::getHost().IUrl::creatUrl('/site/products/id/'.$value['goods_id'])));
+				$status = $smtp->send($value['email'],"到货通知",$body);
+
+				if($status)
+				{
+					//发送成功
+					$succeed++;
+					$notify_status = $notify_status | 1;
+					// 二进制转换为十进制
+					$notify_status = bindec($notify_status);
+					$data = array('notify_time' => ITime::getDateTime(),'notify_status' => $notify_status);
+					$tb_notify_registry->setData($data);
+					$tb_notify_registry->update('id='.$value['id']);
+				}
+				else
+				{
+					//发送失败
+					$failed++;
+				}
+			}
+		}
+
+		$return = array(
+			'isError' => false,
+			'count'   => count($items),
+			'succeed' => $succeed,
+			'failed'  => $failed,
+		);
+		echo JSON::encode($return);
+	}
+
+	/**
+	 * @brief 发送到货通知短信
+	 */
+	function notify_sms_send()
+	{
+		$notify_ids = IFilter::act(IReq::get('notifyid'));
+		if($notify_ids && is_array($notify_ids))
+		{
+			$ids = join(',',$notify_ids);
+			$query = new IQuery("notify_registry as notify");
+			$query->join   = "right join goods as goods on notify.goods_id=goods.id ";
+			$query->fields = "notify.*,goods.name as goods_name,goods.store_nums";
+			$query->where  = "notify.id in(".$ids.")";
+			$items = $query->find();
+
+			//库存大于0,且处于未发送短信状态的 发送通知
+			$succeed = 0;
+			$failed  = 0;
+			$tb_notify_registry = new IModel('notify_registry');
+
+			foreach($items as $value)
+			{
+				// 十进制转换为二进制
+				$notify_status = decbin($value['notify_status']);
+				// 是否已发送短信
+				if (10 == ($notify_status & 10)) {
+					$failed++;
+					continue;
+				}
+
+				$content = smsTemplate::notify(array('{goodsName}' => $value['goods_name'],'{url}' => IUrl::getHost().IUrl::creatUrl('/site/products/id/'.$value['goods_id'])));
+				$send_result = Hsms::send($value['mobile'], $content, 0);
+				if($send_result == 'success')
+				{
+					//发送成功
+					$succeed++;
+					$notify_status = $notify_status | 10;
+					// 二进制转换为十进制
+					$notify_status = bindec($notify_status);
+					$data = array('notify_time' => ITime::getDateTime(),'notify_status' => $notify_status);
+					$tb_notify_registry->setData($data);
+					$tb_notify_registry->update('id='.$value['id']);
+				}
+				else
+				{
+					//发送失败
+					$failed++;
+				}
+			}
+		}
+
+		$return = array(
+			'isError' => false,
+			'count'   => count($items),
+			'succeed' => $succeed,
+			'failed'  => $failed,
+		);
+		echo JSON::encode($return);
+	}
+
+	/**
+	 * @brief 发送信件
+	 */
+	function registry_message_send()
+	{
+		set_time_limit(0);
+		$ids     = IFilter::act(IReq::get('ids'),'int');
+		$title   = IFilter::act(IReq::get('title'));
+		$content = IReq::get("content");
+
+		$smtp  = new SendMail();
+		$error = $smtp->getError();
+
+		$list = array();
+		$tb   = new IModel("email_registry");
+
+		$ids_sql = "1";
+		if($ids)
+		{
+			$ids_sql = "id IN ({$ids})";
+		}
+
+		$start = 0;
+		$query = new IQuery("email_registry");
+		$query->fields = "email";
+		$query->order  = "id DESC";
+		$query->where  = $ids_sql;
+
+		do
+		{
+			$query->limit = "{$start},50";
+			$list = $query->find();
+			if(!$list)
+			{
+				die('没有要发送的邮箱数据');
+				break;
+			}
+			$start += 51;
+
+			$to = array_pop($list);
+			$to = $to['email'];
+			$bcc = array();
+			foreach($list as $value)
+			{
+				$bcc[] = $value['email'];
+			}
+			$bcc = join(";",$bcc);
+			$result = $smtp->send($to,$title,$content,$bcc);
+			if(!$result)
+			{
+				die('发送失败');
+			}
+		}
+		while(count($list)>=50);
+		echo "success";
+	}
+
+	/**
+	 * @brief 营销短信列表
+	 */
+	function marketing_sms_list()
+	{
+		$tb_user_group = new IModel('user_group');
+		$data_group = $tb_user_group->query();
+		$data_group = is_array($data_group) ? $data_group : array();
+		$group      = array();
+		foreach($data_group as $value)
+		{
+			$group[$value['id']] = $value['group_name'];
+		}
+		$this->data['group'] = $group;
+
+		$this->setRenderData($this->data);
+		$this->redirect('marketing_sms_list');
+	}
+
+	/**
+	 * @brief 发送营销短信
+	 */
+	function marketing_sms_send()
+	{
+		$this->layout = '';
+		$this->redirect('marketing_sms_send');
+	}
+
+	/**
+	 * @brief 发送短信
+	 */
+	function start_marketing_sms()
+	{
+		set_time_limit(0);
+		$toUser  = IFilter::act(IReq::get('toUser'));
+		$content = IFilter::act(IReq::get('content'));
+
+		if(!$content)
+		{
+			die('<script type="text/javascript">parent.startMarketingSmsCallback(0);</script>');
+		}
+
+		$list = array();
+		$offset = 0;
+		// 单次发送数量
+		$length = 50;
+		$succeed = 0;
+
+		$query = new IQuery("member");
+		$query->fields = "mobile";
+		$query->order  = "user_id DESC";
+
+		if(!empty($toUser))
+		{
+			$user_array = array();
+			$user_array = explode(",", $toUser);
+			$user_count = count($user_array);
+			$query_num = ceil($user_count / $length);
+			for ($i=0; $i<$query_num; $i++)
+			{
+				$user_ids = array_slice($user_array, $offset, $length);
+				$user_id_string = implode(",", $user_ids);
+				$offset += $length;
+				$query->where  = "user_id IN ({$user_id_string}) AND `mobile` IS NOT NULL AND `mobile`!='' ";
+				$list = $query->find();
+				if (!empty($list))
+				{
+					$mobile_array = array();
+					foreach ($list as $value)
+					{
+						if(false != IValidate::mobi($value['mobile']))
+						{
+							$mobile_array[] = $value['mobile'];
+						}
+					}
+					unset($list);
+					$mobile_count = count($mobile_array);
+					if (0 < $mobile_count)
+					{
+						$mobiles = implode(",", $mobile_array);
+						$send_result = Hsms::send($mobiles, $content, 0);
+						if($send_result == 'success')
+						{
+							$succeed += $mobile_count;
+						}
+					}
+				}
+			}
+		}
+		else
+		{
+			// 默认为所有用户
+			$query->where  = " `mobile` IS NOT NULL AND `mobile`!='' ";
+			$list = $query->find();
+			if (!empty($list))
+			{
+				$mobile_array = array();
+				foreach ($list as $value)
+				{
+					if(false != IValidate::mobi($value['mobile']))
+					{
+						$mobile_array[] = $value['mobile'];
+					}
+				}
+				unset($list);
+				$mobile_count = count($mobile_array);
+				if (0 < $mobile_count)
+				{
+					$send_num = ceil($mobile_count / $length);
+					for ($i=0; $i<$send_num; $i++)
+					{
+						$mobiles = array_slice($mobile_array, $offset, $length);
+						$mobile_string = implode(",", $mobiles);
+						$send_result = Hsms::send($mobile_string, $content, 0);
+						if($send_result == 'success')
+						{
+							$succeed += count($mobiles);
+						}
+						$offset += $length;
+					}
+				}
+			}
+		}
+
+		//获得marketing_sms的表对象
+		$tb_marketing_sms =  new IModel('marketing_sms');
+		$tb_marketing_sms->setData(array(
+			'content'=>$content,
+			'send_nums' =>$succeed,
+			'time'=> ITime::getDateTime(),
+		));
+		$tb_marketing_sms->add();
+		die('<script type="text/javascript">parent.startMarketingSmsCallback(1);</script>');
+	}
+
+	/**
+	 * @brief 删除营销短信
+	 */
+	function marketing_sms_del()
+	{
+		$refer_ids = IReq::get('check');
+		$refer_ids = is_array($refer_ids) ? $refer_ids : array($refer_ids);
+		if($refer_ids)
+		{
+			$ids = implode(',',$refer_ids);
+			if($ids)
+			{
+				$tb_refer = new IModel('marketing_sms');
+				$where = "id in (".$ids.")";
+				$tb_refer->del($where);
+			}
+		}
+		$this->marketing_sms_list();
+	}
+}

+ 1535 - 0
src/controllers/order.php

@@ -0,0 +1,1535 @@
+<?php
+/**
+ * @brief 订单模块
+ * @class Order
+ * @note  后台
+ */
+class Order extends IController implements adminAuthorization
+{
+	public $checkRight  = 'all';
+	public $layout='admin';
+	function init()
+	{
+
+	}
+	/**
+	 * @brief查看订单
+	 */
+	public function order_show()
+	{
+		//获得post传来的值
+		$order_id = IFilter::act(IReq::get('id'),'int');
+		$data = array();
+		if($order_id)
+		{
+			$order_show = new Order_Class();
+			$data = $order_show->getOrderShow($order_id);
+			if($data)
+			{
+		 		//获取地区
+		 		$data['area_addr'] = join('&nbsp;',area::name($data['province'],$data['city'],$data['area']));
+
+			 	$this->setRenderData($data);
+				$this->redirect('order_show',false);
+			}
+		}
+		if(!$data)
+		{
+			$this->redirect('order_list');
+		}
+	}
+	/**
+	 * @brief查看收款单
+	 */
+	public function collection_show()
+	{
+		//获得post传来的收款单id值
+		$collection_id = IFilter::act(IReq::get('id'),'int');
+		$data = array();
+		if($collection_id)
+		{
+			$tb_collection = new IQuery('collection_doc as c ');
+			$tb_collection->join=' left join order as o on c.order_id=o.id left join payment as p on c.payment_id = p.id left join user as u on u.id = c.user_id';
+			$tb_collection->fields = 'o.order_no,p.name as pname,o.create_time,p.type,u.username,c.amount,o.pay_time,c.admin_id,c.note';
+			$tb_collection->where = 'c.id='.$collection_id;
+			$collection_info = $tb_collection->find();
+			if($collection_info)
+			{
+				$data = $collection_info[0];
+
+				$this->setRenderData($data);
+				$this->redirect('collection_show',false);
+			}
+		}
+		if(count($data)==0)
+		{
+			$this->redirect('order_collection_list');
+		}
+	}
+	/**
+	 * @brief查看退款单
+	 */
+	public function refundment_show()
+	{
+	 	//获得post传来的退款单id值
+	 	$refundment_id = IFilter::act(IReq::get('id'),'int');
+	 	$data = array();
+	 	if($refundment_id)
+	 	{
+	 		$tb_refundment = new IQuery('refundment_doc as c');
+	 		$tb_refundment->join=' left join order as o on c.order_id=o.id left join user as u on u.id = c.user_id';
+	 		$tb_refundment->fields = 'o.order_no,o.create_time,u.username,c.*';
+	 		$tb_refundment->where = 'c.id='.$refundment_id;
+	 		$refundment_info = $tb_refundment->find();
+	 		if($refundment_info)
+	 		{
+	 			$data = current($refundment_info);
+	 			$this->setRenderData($data);
+	 			$this->redirect('refundment_show',false);
+	 		}
+	 	}
+
+	 	if(!$data)
+		{
+			$this->redirect('order_refundment_list');
+		}
+	}
+	/**
+	 * @brief查看申请退款单
+	 */
+	public function refundment_doc_show()
+	{
+	 	//获得post传来的申请退款单id值
+	 	$refundment_id = IFilter::act(IReq::get('id'),'int');
+	 	if($refundment_id)
+	 	{
+	 		$refundsDB = new IModel('refundment_doc');
+	 		$data = $refundsDB->getObj('id = '.$refundment_id);
+	 		if($data)
+	 		{
+	 			$this->setRenderData($data);
+	 			$this->redirect('refundment_doc_show',false);
+	 			return;
+	 		}
+	 	}
+
+	 	$this->redirect('refundment_list');
+	}
+	//删除申请退款单
+	public function refundment_doc_del()
+	{
+		//获得post传来的申请退款单id值
+		$refundment_id = IFilter::act(IReq::get('id'),'int');
+		if(is_array($refundment_id))
+		{
+			$refundment_id = implode(",",$refundment_id);
+		}
+		if($refundment_id)
+		{
+			$tb_refundment_doc = new IModel('refundment_doc');
+			$tb_refundment_doc->del("id IN ($refundment_id)");
+		}
+
+		$logObj = new log('db');
+		$logObj->write('operation',array("管理员:".ISafe::get('admin_name'),"退款申请单移除到回收站",'移除的ID:'.$refundment_id));
+
+		$this->redirect('refundment_list');
+	}
+
+	/**
+	 * @brief更新申请退款单
+	 */
+	public function refundment_doc_show_save()
+	{
+		//获得post传来的退款单id值
+		$refundment_id = IFilter::act(IReq::get('id'),'int');
+		$dispose_idea  = IFilter::act(IReq::get('dispose_idea'),'text');
+		$pay_status    = IFilter::act(IReq::get('pay_status'),'int');
+		if($refundment_id)
+		{
+			//获得refundment_doc对象
+			$tb_refundment_doc = new IModel('refundment_doc');
+			$tb_refundment_doc->setData(array(
+				'pay_status'   => $pay_status,
+				'dispose_idea' => $dispose_idea,
+				'dispose_time' => ITime::getDateTime(),
+				'admin_id'     => $this->admin['admin_id'],
+			));
+			$tb_refundment_doc->update('id='.$refundment_id);
+
+			$logObj = new log('db');
+			$logObj->write('operation',array("管理员:".ISafe::get('admin_name'),"修改了退款单",'修改的ID:'.$refundment_id));
+		}
+		$this->redirect('refundment_list');
+	}
+	/**
+	 * @brief查看发货单
+	 */
+	public function delivery_show()
+	{
+	 	//获得post传来的发货单id值
+	 	$delivery_id = IFilter::act(IReq::get('id'),'int');
+	 	$data = array();
+	 	if($delivery_id)
+	 	{
+	 		$tb_delivery = new IQuery('delivery_doc as c ');
+	 		$tb_delivery->join=' left join order as o on c.order_id=o.id left join delivery as p on c.delivery_type = p.id left join user as u on u.id = c.user_id';
+	 		$tb_delivery->fields = 'c.id as id,o.order_no,c.order_id,p.name as pname,o.create_time,u.username,c.name,c.province,c.city,c.area,c.address,c.mobile,c.telphone,c.postcode,c.freight,c.delivery_code,c.time,c.note ';
+	 		$tb_delivery->where = 'c.id='.$delivery_id;
+	 		$delivery_info = $tb_delivery->find();
+	 		if($delivery_info)
+	 		{
+	 			$data = current($delivery_info);
+	 			$data['country'] = join("-",area::name($data['province'],$data['city'],$data['area']));
+
+	 			$this->setRenderData($data);
+	 			$this->redirect('delivery_show',false);
+	 		}
+	 	}
+
+	 	if(!$data)
+		{
+			$this->redirect('order_delivery_list');
+		}
+	}
+	/**
+	 * @brief 支付订单页面collection_doc
+	 */
+	public function order_collection()
+	{
+	 	//去掉左侧菜单和上部导航
+	 	$this->layout='';
+	 	$order_id = IFilter::act(IReq::get('id'),'int');
+	 	$data = array();
+	 	if($order_id)
+	 	{
+	 		$order_show = new Order_Class();
+	 		$data = $order_show->getOrderShow($order_id);
+	 	}
+	 	$this->setRenderData($data);
+	 	$this->redirect('order_collection');
+	}
+	/**
+	 * @brief 保存支付订单页面collection_doc
+	 */
+	public function order_collection_doc()
+	{
+	 	//获得订单号
+	 	$order_no = IFilter::act(IReq::get('order_no'));
+	 	$note     = IFilter::act(IReq::get('note'));
+
+	 	if(Order_Class::updateOrderStatus($order_no,$this->admin['admin_id'],$note))
+	 	{
+		 	//生成订单日志
+	    	$tb_order_log = new IModel('order_log');
+	    	$tb_order_log->setData(array(
+	    		'order_id' =>IFilter::act(IReq::get('id'),'int'),
+	    		'user' =>$this->admin['admin_name'],
+	    		'action' =>'付款',
+	    		'result' =>'成功',
+	    		'note' =>'订单【'.$order_no.'】付款'.IFilter::act(IReq::get('amount'),'float').'元',
+	    		'addtime' => ITime::getDateTime(),
+	    	));
+	    	$tb_order_log->add();
+
+			$logObj = new log('db');
+			$logObj->write('operation',array("管理员:".ISafe::get('admin_name'),"订单更新为已付款","订单号:".$order_no.',已经确定付款'));
+	 		echo '<script type="text/javascript">parent.actionCallback();</script>';
+	 	}
+	 	else
+	 	{
+	 		echo '<script type="text/javascript">parent.actionFailCallback();</script>';
+	 	}
+	}
+	/**
+	 * @brief 退款单页面
+	 */
+	public function order_refundment()
+	{
+		//去掉左侧菜单和上部导航
+		$this->layout='';
+		$orderId   = IFilter::act(IReq::get('id'),'int');
+		$refundsId = IFilter::act(IReq::get('refunds_id'),'int');
+
+		if($orderId)
+		{
+			$orderDB = new Order_Class();
+			$data    = $orderDB->getOrderShow($orderId);
+
+			//已经存退款申请
+			if($refundsId)
+			{
+				$refundsDB  = new IModel('refundment_doc');
+				$refundsRow = $refundsDB->getObj('id = '.$refundsId);
+				$data['refunds'] = $refundsRow;
+			}
+			$this->setRenderData($data);
+			$this->data = $data;
+			$this->redirect('order_refundment');
+			return;
+		}
+		die('订单数据不存在');
+	}
+	/**
+	 * @brief 保存退款单页面
+	 */
+	public function order_refundment_doc()
+	{
+		$refunds_id = IFilter::act(IReq::get('refunds_id'),'int');
+		$amount   = IFilter::act(IReq::get('amount'),'float');
+		$order_id = IFilter::act(IReq::get('id'),'int');
+		$order_no = IFilter::act(IReq::get('order_no'));
+		$user_id  = IFilter::act(IReq::get('user_id'),'int');
+		$order_goods_id = IFilter::act(IReq::get('order_goods_id'),'int'); //要退款的商品,如果是用户已经提交的退款申请此数据为NULL,需要获取出来
+		$way = IFilter::act(IReq::get('way'));
+
+		//访客订单不能退款到余额中
+		if(!$user_id && $way == "balance")
+		{
+			die('<script text="text/javascript">parent.actionCallback("游客无法退款");</script>');
+		}
+
+		//1,退款单存在更新退款价格
+		$tb_refundment_doc = new IModel('refundment_doc');
+		if($refunds_id)
+		{
+			$updateData = array('amount' => $amount);
+			$tb_refundment_doc->setData($updateData);
+			$tb_refundment_doc->update("id = ".$refunds_id);
+		}
+		//2,无退款申请单,必须生成退款单
+		else
+		{
+			if(!$order_goods_id)
+			{
+				die('<script text="text/javascript">parent.actionCallback("请选择要退款的商品");</script>');
+			}
+
+			$orderDB = new IModel('order');
+			$orderRow= $orderDB->getObj("id = ".$order_id);
+
+			//插入refundment_doc表
+			$updateData = array(
+				'amount'        => $amount,
+				'order_no'      => $order_no,
+				'order_id'      => $order_id,
+				'admin_id'      => $this->admin['admin_id'],
+				'pay_status'    => 1,
+				'dispose_time'  => ITime::getDateTime(),
+				'dispose_idea'  => '',
+				'user_id'       => $user_id,
+				'time'          => ITime::getDateTime(),
+				'seller_id'     => $orderRow['seller_id'],
+				'order_goods_id'=> join(",",$order_goods_id),
+			);
+			$tb_refundment_doc->setData($updateData);
+			$refunds_id = $tb_refundment_doc->add();
+		}
+
+		$result = Order_Class::refund($refunds_id,$this->admin['admin_id'],'admin',$way);
+		if(is_string($result))
+		{
+			$tb_refundment_doc->rollback();
+			die('<script text="text/javascript">parent.actionCallback("'.$result.'");</script>');
+		}
+		else
+		{
+			//记录操作日志
+			$logObj = new log('db');
+			$logObj->write('operation',array("管理员:".ISafe::get('admin_name'),"订单更新为退款",'订单号:'.$order_no));
+			die('<script text="text/javascript">parent.actionCallback();</script>');
+		}
+	}
+	/**
+	 * @brief 保存订单备注
+	 */
+	public function order_note()
+	{
+	 	//获得post数据
+	 	$order_id = IFilter::act(IReq::get('order_id'),'int');
+	 	$note = IFilter::act(IReq::get('note'),'text');
+
+	 	//获得order的表对象
+	 	$tb_order =  new IModel('order');
+	 	$tb_order->setData(array(
+	 		'note'=>$note
+	 	));
+	 	$tb_order->update('id='.$order_id);
+	 	IReq::set('id',$order_id);
+	 	$this->order_show();
+	}
+	/**
+	 * @brief 保存顾客留言
+	 */
+	public function order_message()
+	{
+		//获得post数据
+		$order_id = IFilter::act(IReq::get('order_id'),'int');
+		$user_id = IFilter::act(IReq::get('user_id'),'int');
+		$title = IFilter::act(IReq::get('title'));
+		$content = IFilter::act(IReq::get('content'),'text');
+
+		//获得message的表对象
+		$tb_message =  new IModel('message');
+		$tb_message->setData(array(
+			'title'=>$title,
+			'content' =>$content,
+			'time'=> ITime::getDateTime(),
+		));
+		$message_id = $tb_message->add();
+		//获的mess类
+		$message = new Mess($user_id);
+		$message->writeMessage($message_id);
+		IReq::set('id',$order_id);
+		$this->order_show();
+	}
+	/**
+	 * @brief 完成或作废订单页面
+	 **/
+	public function order_complete()
+	{
+		//去掉左侧菜单和上部导航
+		$this->layout='';
+		$order_id = IFilter::act(IReq::get('id'),'int');
+		$type     = IFilter::act(IReq::get('type'),'int');
+		$order_no = IFilter::act(IReq::get('order_no'));
+
+		//oerder表的对象
+		$tb_order = new IModel('order');
+		$tb_order->setData(array(
+			'status'          => $type,
+			'completion_time' => ITime::getDateTime(),
+		));
+		$tb_order->update('id='.$order_id);
+
+		//生成订单日志
+		$tb_order_log = new IModel('order_log');
+		$action = '作废';
+		$note   = '订单【'.$order_no.'】作废成功';
+
+		if($type=='5')
+		{
+			$action = '完成';
+			$note   = '订单【'.$order_no.'】完成成功';
+
+			//完成订单并且进行支付
+			Order_Class::updateOrderStatus($order_no);
+
+			//增加用户评论商品机会
+			Order_Class::addGoodsCommentChange($order_id);
+
+			$logObj = new log('db');
+			$logObj->write('operation',array("管理员:".ISafe::get('admin_name'),"订单更新为完成",'订单号:'.$order_no));
+		}
+		else
+		{
+			Order_class::resetOrderProp($order_id);
+
+			$logObj = new log('db');
+			$logObj->write('operation',array("管理员:".ISafe::get('admin_name'),"订单更新为作废",'订单号:'.$order_no));
+		}
+
+		$tb_order_log->setData(array(
+			'order_id' => $order_id,
+			'user'     => $this->admin['admin_name'],
+			'action'   => $action,
+			'result'   => '成功',
+			'note'     => $note,
+			'addtime'  => ITime::getDateTime(),
+		));
+		$tb_order_log->add();
+		die('success');
+	}
+	/**
+	 * @brief 发货订单页面
+	 */
+	public function order_deliver()
+	{
+		//去掉左侧菜单和上部导航
+		$this->layout='';
+		$order_id = IFilter::act(IReq::get('id'),'int');
+		$data = array();
+		if($order_id)
+		{
+			$order_show = new Order_Class();
+			$data = $order_show->getOrderShow($order_id);
+		}
+		$this->setRenderData($data);
+		$this->redirect('order_deliver');
+	}
+	/**
+	 * @brief 发货操作
+	 */
+	public function order_delivery_doc()
+	{
+	 	//获得post变量参数
+	 	$order_id = IFilter::act(IReq::get('id'),'int');
+
+	 	//发送的商品关联
+	 	$sendgoods = IFilter::act(IReq::get('sendgoods'));
+
+	 	if(!$sendgoods)
+	 	{
+	 		die('<script type="text/javascript">parent.actionCallback("请选择要发货的商品");</script>');
+	 	}
+
+	 	$result = Order_Class::sendDeliveryGoods($order_id,$sendgoods,$this->admin['admin_id']);
+
+		if($result === true)
+		{
+			die('<script type="text/javascript">parent.actionCallback();</script>');
+		}
+		die('<script type="text/javascript">parent.actionCallback("'.$result.'");</script>');
+	}
+	/**
+	 * @brief 保存修改订单
+	 */
+    public function order_update()
+    {
+    	//获取必要数据
+    	$order_id = IFilter::act(IReq::get('id'),'int');
+
+    	//生成order数据
+    	$dataArray                  = array();
+    	$dataArray['invoice_title'] = IFilter::act(IReq::get('invoice_title'));
+    	$dataArray['invoice']       = IFilter::act(IReq::get('invoice'),'int');
+    	$dataArray['pay_type']      = IFilter::act(IReq::get('pay_type'),'int');
+    	$dataArray['accept_name']   = IFilter::act(IReq::get('accept_name'));
+    	$dataArray['postcode']      = IFilter::act(IReq::get('postcode'));
+    	$dataArray['telphone']      = IFilter::act(IReq::get('telphone'));
+    	$dataArray['province']      = IFilter::act(IReq::get('province'),'int');
+    	$dataArray['city']          = IFilter::act(IReq::get('city'),'int');
+    	$dataArray['area']          = IFilter::act(IReq::get('area'),'int');
+    	$dataArray['address']       = IFilter::act(IReq::get('address'));
+    	$dataArray['mobile']        = IFilter::act(IReq::get('mobile'));
+    	$dataArray['discount']      = $order_id ? IFilter::act(IReq::get('discount'),'float') : 0;
+    	$dataArray['postscript']    = IFilter::act(IReq::get('postscript'));
+    	$dataArray['distribution']  = IFilter::act(IReq::get('distribution'),'int');
+    	$dataArray['accept_time']   = IFilter::act(IReq::get('accept_time'));
+    	$dataArray['takeself']      = IFilter::act(IReq::get('takeself'));
+    	$dataArray['real_freight']  = IFilter::act(IReq::get('real_freight'));
+    	$dataArray['note']          = IFilter::act(IReq::get('note'));
+
+		//设置订单持有者
+		$username = IFilter::act(IReq::get('username'));
+		$userDB   = new IModel('user');
+		$userRow  = $userDB->getObj('username = "'.$username.'"');
+		$dataArray['user_id'] = isset($userRow['id']) ? $userRow['id'] : 0;
+
+		//拼接要购买的商品或货品数据,组装成固有的数据结构便于计算价格
+		$goodsId   = IFilter::act(IReq::get('goods_id'));
+		$productId = IFilter::act(IReq::get('product_id'));
+		$num       = IFilter::act(IReq::get('goods_nums'));
+
+		$goodsArray  = array();
+		$productArray= array();
+		if($goodsId)
+		{
+	    	foreach($goodsId as $key => $goods_id)
+	    	{
+	    		if(!$goods_id)
+	    		{
+	    			continue;
+	    		}
+
+	    		$pid = $productId[$key];
+	    		$nVal= $num[$key];
+
+	    		if($pid > 0)
+	    		{
+	    			$productArray[$pid] = $nVal;
+	    		}
+	    		else
+	    		{
+	    			$goodsArray[$goods_id] = $nVal;
+	    		}
+	    	}
+		}
+
+		if(!$goodsArray && !$productArray)
+		{
+			IError::show("商品信息不存在");
+			exit;
+		}
+
+		//开始算账
+		$countSumObj  = new CountSum($dataArray['user_id']);
+		$cartObj      = new Cart();
+		$goodsResult  = $countSumObj->goodsCount($cartObj->cartFormat(array("goods" => $goodsArray,"product" => $productArray)));
+		$orderData   = $countSumObj->countOrderFee($goodsResult,$dataArray['province'],$dataArray['distribution'],$dataArray['pay_type'],$dataArray['invoice'],$dataArray['discount']);
+		if(is_string($orderData))
+		{
+			IError::show(403,$orderData);
+			exit;
+		}
+
+		//根据商品所属商家不同批量生成订单
+		foreach($orderData as $seller_id => $goodsResult)
+		{
+			//运费自定义
+			if(is_numeric($dataArray['real_freight']) && $goodsResult['deliveryPrice'] != $dataArray['real_freight'])
+			{
+				$goodsResult['orderAmountPrice'] += $dataArray['real_freight'] - $goodsResult['deliveryPrice'];
+				$goodsResult['deliveryPrice']     = $dataArray['real_freight'];
+			}
+			$dataArray['payable_freight']= $goodsResult['deliveryOrigPrice'];
+			$dataArray['payable_amount'] = $goodsResult['sum'];
+			$dataArray['real_amount']    = $goodsResult['final_sum'];
+			$dataArray['real_freight']   = $goodsResult['deliveryPrice'];
+			$dataArray['insured']        = $goodsResult['insuredPrice'];
+			$dataArray['pay_fee']        = $goodsResult['paymentPrice'];
+			$dataArray['taxes']          = $goodsResult['taxPrice'];
+			$dataArray['promotions']     = $goodsResult['proReduce'] + $goodsResult['reduce'];
+			$dataArray['order_amount']   = $goodsResult['orderAmountPrice'] <= 0 ? 0 : $goodsResult['orderAmountPrice'];
+			$dataArray['exp']            = $goodsResult['exp'];
+			$dataArray['point']          = $goodsResult['point'];
+
+			//商家ID
+			$dataArray['seller_id'] = $seller_id;
+
+	    	//生成订单
+	    	$orderDB = new IModel('order');
+
+	    	//修改操作
+	    	if($order_id)
+	    	{
+	    		//获取订单信息
+	    		$orderRow = $orderDB->getObj('id = '.$order_id);
+
+	    		//修改订单不能加入其他商家产品
+	    		if(count($orderData) != 1 || $orderRow['seller_id'] != $seller_id)
+	    		{
+					IError::show(403,"此订单中不能混入其他商家的商品");
+					exit;
+	    		}
+
+	    		//订单中已经使用了代金券
+	    		if(isset($orderRow['prop']) && $orderRow['prop'])
+	    		{
+					$propObj   = new IModel('prop');
+					$ticketRow = $propObj->getObj('id = '.$orderRow['prop']);
+					if($ticketRow)
+					{
+						$ticketRow['value']         = $ticketRow['value'] >= $goodsResult['final_sum'] ? $goodsResult['final_sum'] : $ticketRow['value'];
+						$dataArray['promotions']   += $ticketRow['value'];
+						$dataArray['order_amount'] -= $ticketRow['value'];
+					}
+	    		}
+
+	    		$orderDB->setData($dataArray);
+	    		$orderDB->update('id = '.$order_id);
+
+				//记录日志信息
+				$logObj = new log('db');
+				$logObj->write('operation',array("管理员:".$this->admin['admin_name'],"修改了订单信息",'订单号:'.$orderRow['order_no']));
+	    	}
+	    	//添加操作
+	    	else
+	    	{
+	    		$dataArray['create_time'] = ITime::getDateTime();
+	    		$dataArray['order_no']    = Order_Class::createOrderNum();
+
+	    		$orderDB->setData($dataArray);
+	    		$order_id = $orderDB->add();
+
+				//记录日志信息
+				$logObj = new log('db');
+				$logObj->write('operation',array("管理员:".$this->admin['admin_name'],"添加了订单信息",'订单号:'.$dataArray['order_no']));
+	    	}
+
+	    	//同步order_goods表
+	    	$orderInstance = new Order_Class();
+	    	$result = $orderInstance->insertOrderGoods($order_id,$goodsResult['goodsResult']);
+	    	if($result !== true)
+	    	{
+	    		IError::show($result);
+	    	}
+		}
+
+    	$this->redirect('order_list');
+    }
+	/**
+	 * @brief 修改订单
+	 */
+	public function order_edit()
+    {
+    	$data = array();
+
+    	//获得order_id的值
+		$order_id = IFilter::act(IReq::get('id'),'int');
+		if($order_id)
+		{
+			$orderDB = new IModel('order');
+			$data    = $orderDB->getObj('id = '.$order_id);
+			if(Order_class::getOrderStatus($data) >= 3)
+			{
+				IError::show(403,"当前订单状态不允许修改");
+			}
+
+			$this->orderRow = $data;
+
+			//存在自提点
+			if($data['takeself'])
+			{
+				$takeselfObj = new IModel('takeself');
+				$takeselfRow = $takeselfObj->getObj('id = '.$data['takeself']);
+				$dataArea    = area::name($takeselfRow['province'],$takeselfRow['city'],$takeselfRow['area']);
+				$takeselfRow['province_str'] = $dataArea[$takeselfRow['province']];
+				$takeselfRow['city_str']     = $dataArea[$takeselfRow['city']];
+				$takeselfRow['area_str']     = $dataArea[$takeselfRow['area']];
+				$this->takeself = $takeselfRow;
+			}
+
+			//获取订单中的商品信息
+			$orderGoodsDB         = new IQuery('order_goods as og');
+			$orderGoodsDB->join   = "left join goods as go on og.goods_id = go.id left join products as p on p.id = og.product_id";
+			$orderGoodsDB->fields = "go.id,go.name,p.spec_array,p.id as product_id,og.real_price,og.goods_nums,go.goods_no,p.products_no";
+			$orderGoodsDB->where  = "og.order_id = ".$order_id;
+			$this->orderGoods     = $orderGoodsDB->find();
+
+			//获取用户名
+			if($data['user_id'])
+			{
+				$userDB  = new IModel('user');
+				$userRow = $userDB->getObj("id = ".$data['user_id']);
+				$this->username = isset($userRow['username']) ? $userRow['username'] : '';
+			}
+		}
+		$this->redirect('order_edit');
+    }
+    /**
+     * @brief 订单列表
+     */
+    public function order_list()
+    {
+		//搜索条件
+		$search = IReq::get('search');
+		$page   = IReq::get('page') ? IFilter::act(IReq::get('page'),'int') : 1;
+		//条件筛选处理
+		list($join,$where) = order_class::getSearchCondition($search);
+		//拼接sql
+		$orderHandle = new IQuery('order as o');
+		$orderHandle->order  = "o.id desc";
+		$orderHandle->fields = "o.*,d.name as distribute_name,p.name as payment_name";
+		$orderHandle->page   = $page;
+		$orderHandle->where  = $where;
+		$orderHandle->join   = $join;
+
+		$this->search      = $search;
+		$this->orderHandle = $orderHandle;
+
+		$this->redirect("order_list");
+    }
+    /**
+     * @brief 订单删除功能_删除到回收站
+     */
+    public function order_del()
+    {
+    	//post数据
+    	$id = IFilter::act(IReq::get('id'),'int');
+
+    	//生成order对象
+    	$tb_order = new IModel('order');
+    	$tb_order->setData(array('if_del'=>1));
+    	if($id)
+		{
+			$tb_order->update(Util::joinStr($id));
+
+			//获取订单编号
+			$orderRs   = $tb_order->query(Util::joinStr($id),'order_no');
+			$orderData = array();
+			foreach($orderRs as $val)
+			{
+				$orderData[] = $val['order_no'];
+			}
+
+			$logObj = new log('db');
+			$logObj->write('operation',array("管理员:".ISafe::get('admin_name'),"订单移除到回收站内",'订单号:'.join(',',$orderData)));
+		}
+		$this->redirect('order_list');
+    }
+	/**
+     * @brief 收款单删除功能_删除到回收站
+     */
+    public function collection_del()
+    {
+    	//post数据
+    	$id = IFilter::act(IReq::get('id'),'int');
+    	//生成order对象
+    	$tb_order = new IModel('collection_doc');
+    	$tb_order->setData(array('if_del'=>1));
+    	if($id)
+		{
+			$tb_order->update(Util::joinStr($id));
+
+			$logObj = new log('db');
+			$logObj->write('operation',array("管理员:".ISafe::get('admin_name'),"收款单移除到回收站内",'收款单ID:'.join(',',$id)));
+
+			$this->redirect('order_collection_list');
+		}
+		else
+		{
+			$this->redirect('order_collection_list',false);
+			Util::showMessage('请选择要删除的数据');
+		}
+    }
+	/**
+     * @brief 收款单删除功能_删除回收站中的数据,彻底删除
+     */
+    public function collection_recycle_del()
+    {
+    	//post数据
+    	$id = IFilter::act(IReq::get('id'),'int');
+    	//生成order对象
+    	$tb_order = new IModel('collection_doc');
+    	if($id)
+		{
+			$tb_order->del(Util::joinStr($id));
+
+			$logObj = new log('db');
+			$logObj->write('operation',array("管理员:".ISafe::get('admin_name'),"删除回收站内的收款单",'收款单ID:'.join(',',$id)));
+
+			$this->redirect('collection_recycle_list');
+		}
+		else
+		{
+			$this->redirect('collection_recycle_list',false);
+			Util::showMessage('请选择要删除的数据');
+		}
+    }
+	/**
+	 * @brief 还原还款单列表
+	 */
+    public function collection_recycle_restore()
+    {
+    	//post数据
+    	$id = IFilter::act(IReq::get('id'),'int');
+    	//生成order对象
+    	$tb_order = new IModel('collection_doc');
+    	$tb_order->setData(array('if_del'=>0));
+    	if($id)
+		{
+			$tb_order->update(Util::joinStr($id));
+
+			$logObj = new log('db');
+			$logObj->write('operation',array("管理员:".ISafe::get('admin_name'),"恢复了回收站内的收款单",'收款单ID:'.join(',',$id)));
+
+			$this->redirect('collection_recycle_list');
+		}
+		else
+		{
+			$this->redirect('collection_recycle_list',false);
+			Util::showMessage('请选择要还原的数据');
+		}
+    }
+	/**
+	 * @brief 退款单删除功能_删除到回收站
+	 */
+    public function refundment_del()
+    {
+    	//post数据
+    	$id = IFilter::act(IReq::get('id'),'int');
+    	//生成order对象
+    	$tb_order = new IModel('refundment_doc');
+    	$tb_order->setData(array('if_del'=>1));
+    	if(!empty($id))
+		{
+			$tb_order->update(Util::joinStr($id));
+
+			$logObj = new log('db');
+			$logObj->write('operation',array("管理员:".ISafe::get('admin_name'),"退款单移除到回收站内",'退款单ID:'.join(',',$id)));
+
+			$this->redirect('order_refundment_list');
+		}
+		else
+		{
+			$this->redirect('order_refundment_list',false);
+			Util::showMessage('请选择要删除的数据');
+		}
+    }
+	/**
+	 * @brief 退款单删除功能_删除回收站中的数据,彻底删除
+	 */
+    public function refundment_recycle_del()
+    {
+    	//post数据
+    	$id = IFilter::act(IReq::get('id'),'int');
+    	//生成order对象
+    	$tb_order = new IModel('refundment_doc');
+    	if(!empty($id))
+		{
+			$tb_order->del(Util::joinStr($id));
+
+			$logObj = new log('db');
+			$logObj->write('operation',array("管理员:".ISafe::get('admin_name'),"删除了回收站内的退款单",'退款单ID:'.join(',',$id)));
+
+			$this->redirect('refundment_recycle_list');
+		}
+		else
+		{
+			$this->redirect('refundment_recycle_list',false);
+			Util::showMessage('请选择要删除的数据');
+		}
+    }
+	/**
+	 * @brief 还原还款单列表
+	 */
+    public function refundment_recycle_restore()
+    {
+    	//post数据
+    	$id = IFilter::act(IReq::get('id'),'int');
+    	//生成order对象
+    	$tb_order = new IModel('refundment_doc');
+    	$tb_order->setData(array('if_del'=>0));
+    	if(!empty($id))
+		{
+			$tb_order->update(Util::joinStr($id));
+
+			$logObj = new log('db');
+			$logObj->write('operation',array("管理员:".ISafe::get('admin_name'),"还原了回收站内的还款单",'还款单ID:'.join(',',$id)));
+
+			$this->redirect('refundment_recycle_list');
+		}
+		else
+		{
+			$this->redirect('refundment_recycle_list',false);
+			Util::showMessage('请选择要还原的数据');
+		}
+    }
+    /**
+     * @brief 发货单删除功能_删除到回收站
+     */
+    public function delivery_del()
+    {
+    	//post数据
+    	$id = IFilter::act(IReq::get('id'),'int');
+    	//生成order对象
+    	$tb_order = new IModel('delivery_doc');
+    	$tb_order->setData(array('if_del'=>1));
+    	if(!empty($id))
+		{
+			$tb_order->update(Util::joinStr($id));
+
+			$logObj = new log('db');
+			$logObj->write('operation',array("管理员:".ISafe::get('admin_name'),"发货单移除到回收站内",'发货单ID:'.join(',',$id)));
+
+			$this->redirect('order_delivery_list');
+		}
+		else
+		{
+			$this->redirect('order_delivery_list',false);
+			Util::showMessage('请选择要删除的数据');
+		}
+    }
+	/**
+     * @brief 发货单删除功能_删除回收站中的数据,彻底删除
+     */
+    public function delivery_recycle_del()
+    {
+    	//post数据
+    	$id = IFilter::act(IReq::get('id'),'int');
+    	//生成order对象
+    	$tb_order = new IModel('delivery_doc');
+    	if(!empty($id))
+		{
+			$tb_order->del(Util::joinStr($id));
+
+			$logObj = new log('db');
+			$logObj->write('operation',array("管理员:".ISafe::get('admin_name'),"删除了回收站中的发货单",'发货单ID:'.join(',',$id)));
+
+			$this->redirect('delivery_recycle_list');
+		}
+		else
+		{
+			$this->redirect('delivery_recycle_list',false);
+			Util::showMessage('请选择要删除的数据');
+		}
+    }
+	/**
+	 * @brief 还原发货单列表
+	 */
+    public function delivery_recycle_restore()
+    {
+    	//post数据
+    	$id = IFilter::act(IReq::get('id'),'int');
+    	//生成order对象
+    	$tb_order = new IModel('delivery_doc');
+    	$tb_order->setData(array('if_del'=>0));
+    	if(!empty($id))
+		{
+			$tb_order->update(Util::joinStr($id));
+
+			$logObj = new log('db');
+			$logObj->write('operation',array("管理员:".ISafe::get('admin_name'),"还原了回收站中的发货单",'发货单ID:'.join(',',$id)));
+
+			$this->redirect('delivery_recycle_list');
+		}
+		else
+		{
+			$this->redirect('delivery_recycle_list',false);
+			Util::showMessage('请选择要还原的数据');
+		}
+    }
+    /**
+     * @brief 订单删除功能_删除回收站中的数据,彻底删除
+     */
+    public function order_recycle_del()
+    {
+    	//post数据
+    	$id = IFilter::act(IReq::get('id'),'int');
+
+    	//生成order对象
+    	$tb_order = new IModel('order');
+
+    	if($id)
+		{
+			$id = is_array($id) ? join(',',$id) : $id;
+
+			Order_class::resetOrderProp($id);
+
+			//删除订单
+			$tb_order->del('id in ('.$id.')');
+
+			//记录日志
+			$logObj = new log('db');
+			$logObj->write('operation',array("管理员:".ISafe::get('admin_name'),"删除回收站中退货单",'退货单ID:'.$id));
+
+			$this->redirect('order_recycle_list');
+		}
+		else
+		{
+			$this->redirect('order_recycle_list',false);
+			Util::showMessage('请选择要删除的数据');
+		}
+    }
+    /**
+	 * @brief 还原订单列表
+	 */
+    public function order_recycle_restore()
+    {
+    	//post数据
+    	$id = IFilter::act(IReq::get('id'),'int');
+    	//生成order对象
+    	$tb_order = new IModel('order');
+    	$tb_order->setData(array('if_del'=>0));
+    	if(!empty($id))
+		{
+			$tb_order->update(Util::joinStr($id));
+			$this->redirect('order_recycle_list');
+		}
+		else
+		{
+			$this->redirect('order_recycle_list',false);
+			Util::showMessage('请选择要还原的数据');
+		}
+    }
+	/**
+	 * @brief 订单打印模板修改
+	 */
+    public function print_template()
+    {
+		//获取根目录路径
+		$path = $this->getViewPath().$this->getId();
+
+    	//获取 购物清单模板
+		$ifile_shop = new IFile($path.'/shop_template.html');
+		$arr['ifile_shop']=$ifile_shop->read();
+		//获取 配货单模板
+		$ifile_pick = new IFile($path."/pick_template.html");
+		$arr['ifile_pick']=$ifile_pick->read();
+
+		$this->setRenderData($arr);
+		$this->redirect('print_template');
+    }
+	/**
+	 * @brief 订单打印模板修改保存
+	 */
+    public function print_template_update()
+    {
+		// 获取POST数据
+    	$con_shop = IReq::get("con_shop");
+		$con_pick = IReq::get("con_pick");
+
+    	//获取根目录路径
+		$path = $this->getViewPath().$this->getId();
+    	//保存 购物清单模板
+		$ifile_shop = new IFile($path.'/shop_template.html','w');
+		if(!($ifile_shop->write($con_shop)))
+		{
+			$this->redirect('print_template',false);
+			Util::showMessage('保存购物清单模板失败!');
+		}
+		//保存 配货单模板
+		$ifile_pick = new IFile($path."/pick_template.html",'w');
+		if(!($ifile_pick->write($con_pick)))
+		{
+			$this->redirect('print_template',false);
+			Util::showMessage('保存配货单模板失败!');
+		}
+		//保存 合并单模板
+    	$ifile_merge = new IFile($path."/merge_template.html",'w');
+		if(!($ifile_merge->write($con_shop.$con_pick)))
+		{
+			$this->redirect('print_template',false);
+			Util::showMessage('购物清单和配货单模板合并失败!');
+		}
+
+		$this->setRenderData(array('where'=>''));
+		$this->redirect('order_list');
+	}
+
+	//购物单
+	public function shop_template()
+	{
+		$this->layout='print';
+		$order_id = IFilter::act( IReq::get('id'),'int' );
+		$seller_id= IFilter::act( IReq::get('seller_id'),'int' );
+
+		$tb_order = new IModel('order');
+		$where    = $seller_id ? 'id='.$order_id.' and seller_id = '.$seller_id : 'id='.$order_id;
+		$data     = $tb_order->getObj($where);
+		if(!$data)
+		{
+			IError::show(403,"您没有权限查阅该订单");
+		}
+
+		if($data['seller_id'])
+		{
+			$sellerObj   = new IModel('seller');
+			$config_info = $sellerObj->getObj('id = '.$data['seller_id']);
+
+	     	$data['set']['name']   = isset($config_info['true_name'])? $config_info['true_name'] : '';
+	     	$data['set']['phone']  = isset($config_info['phone'])    ? $config_info['phone']     : '';
+	     	$data['set']['email']  = isset($config_info['email'])    ? $config_info['email']     : '';
+	     	$data['set']['url']    = isset($config_info['home_url']) ? $config_info['home_url']  : '';
+		}
+		else
+		{
+			$config = new Config("site_config");
+			$config_info = $config->getInfo();
+
+	     	$data['set']['name']   = isset($config_info['name'])  ? $config_info['name']  : '';
+	     	$data['set']['phone']  = isset($config_info['phone']) ? $config_info['phone'] : '';
+	     	$data['set']['email']  = isset($config_info['email']) ? $config_info['email'] : '';
+	     	$data['set']['url']    = isset($config_info['url'])   ? $config_info['url']   : '';
+		}
+
+		$data['address']   = join('&nbsp;',area::name($data['province'],$data['city'],$data['area']))."&nbsp;".$data['address'];
+		$this->setRenderData($data);
+		$this->redirect("shop_template");
+	}
+	//发货单
+	public function pick_template()
+	{
+		$this->layout='print';
+		$order_id = IFilter::act( IReq::get('id'),'int' );
+		$seller_id= IFilter::act( IReq::get('seller_id'),'int' );
+
+		$tb_order = new IModel('order');
+		$where    = $seller_id ? 'id='.$order_id.' and seller_id = '.$seller_id : 'id='.$order_id;
+		$data     = $tb_order->getObj($where);
+		if(!$data)
+		{
+			IError::show(403,"您没有权限查阅该订单");
+		}
+ 		//获取地区
+ 		$data['address'] = join('&nbsp;',area::name($data['province'],$data['city'],$data['area']))."&nbsp;".$data['address'];
+
+		$this->setRenderData($data);
+		$this->redirect('pick_template');
+	}
+	//合并购物单和发货单
+	public function merge_template()
+	{
+		$this->layout='print';
+		$order_id = IFilter::act(IReq::get('id'),'int');
+		$seller_id= IFilter::act( IReq::get('seller_id'),'int' );
+
+		$tb_order = new IModel('order');
+		$where    = $seller_id ? 'id='.$order_id.' and seller_id = '.$seller_id : 'id='.$order_id;
+		$data     = $tb_order->getObj($where);
+		if(!$data)
+		{
+			IError::show(403,"您没有权限查阅该订单");
+		}
+		if($data['seller_id'])
+		{
+			$sellerObj   = new IModel('seller');
+			$config_info = $sellerObj->getObj('id = '.$data['seller_id']);
+
+	     	$data['set']['name']   = isset($config_info['true_name'])? $config_info['true_name'] : '';
+	     	$data['set']['phone']  = isset($config_info['phone'])    ? $config_info['phone']     : '';
+	     	$data['set']['email']  = isset($config_info['email'])    ? $config_info['email']     : '';
+	     	$data['set']['url']    = isset($config_info['home_url']) ? $config_info['home_url']  : '';
+		}
+		else
+		{
+			$config = new Config("site_config");
+			$config_info = $config->getInfo();
+
+	     	$data['set']['name']   = isset($config_info['name'])  ? $config_info['name']  : '';
+	     	$data['set']['phone']  = isset($config_info['phone']) ? $config_info['phone'] : '';
+	     	$data['set']['email']  = isset($config_info['email']) ? $config_info['email'] : '';
+	     	$data['set']['url']    = isset($config_info['url'])   ? $config_info['url']   : '';
+		}
+
+ 		//获取地区
+ 		$data['address'] = join('&nbsp;',area::name($data['province'],$data['city'],$data['area']))."&nbsp;".$data['address'];
+
+		$this->setRenderData($data);
+		$this->redirect("merge_template");
+	}
+	/**
+	 * @brief 添加/修改发货信息
+	 */
+	public function ship_info_edit()
+	{
+		// 获取POST数据
+    	$id = IFilter::act(IReq::get("sid"),'int');
+    	if($id)
+    	{
+    		$tb_ship   = new IModel("merch_ship_info");
+    		$ship_info = $tb_ship->getObj("id=".$id." and seller_id = 0");
+    		if($ship_info)
+    		{
+    			$this->data = $ship_info;
+    		}
+    		else
+    		{
+    			die('数据不存在');
+    		}
+    	}
+    	$this->setRenderData($this->data);
+		$this->redirect('ship_info_edit');
+	}
+	/**
+	 * @brief 设置发货信息的默认值
+	 */
+	public function ship_info_default()
+	{
+		$id = IFilter::act( IReq::get('id'),'int' );
+        $default = IFilter::string(IReq::get('default'));
+        $tb_merch_ship_info = new IModel('merch_ship_info');
+        if($default == 1)
+        {
+            $tb_merch_ship_info->setData(array('is_default'=>0));
+            $tb_merch_ship_info->update("seller_id = 0");
+        }
+        $tb_merch_ship_info->setData(array('is_default'=>$default));
+        $tb_merch_ship_info->update("id = ".$id." and seller_id = 0");
+        $this->redirect('ship_info_list');
+	}
+	/**
+	 * @brief 保存添加/修改发货信息
+	 */
+	public function ship_info_update()
+	{
+		// 获取POST数据
+    	$id = IFilter::act(IReq::get('sid'),'int');
+    	$ship_name = IFilter::act(IReq::get('ship_name'));
+    	$ship_user_name = IFilter::act(IReq::get('ship_user_name'));
+    	$sex = IFilter::act(IReq::get('sex'),'int');
+    	$province =IFilter::act(IReq::get('province'),'int');
+    	$city = IFilter::act(IReq::get('city'),'int');
+    	$area = IFilter::act(IReq::get('area'),'int');
+    	$address = IFilter::act(IReq::get('address'));
+    	$postcode = IFilter::act(IReq::get('postcode'),'int');
+    	$mobile = IFilter::act(IReq::get('mobile'));
+    	$telphone = IFilter::act(IReq::get('telphone'));
+    	$is_default = IFilter::act(IReq::get('is_default'),'int');
+
+    	$tb_merch_ship_info = new IModel('merch_ship_info');
+
+    	//判断是否已经有了一个默认地址
+    	if(isset($is_default) && $is_default==1)
+    	{
+    		$tb_merch_ship_info->setData(array('is_default' => 0));
+    		$tb_merch_ship_info->update('seller_id = 0');
+    	}
+    	//设置存储数据
+    	$arr['ship_name'] = $ship_name;
+	    $arr['ship_user_name'] = $ship_user_name;
+	    $arr['sex'] = $sex;
+    	$arr['province'] = $province;
+    	$arr['city'] =$city;
+    	$arr['area'] =$area;
+    	$arr['address'] = $address;
+    	$arr['postcode'] = $postcode;
+    	$arr['mobile'] = $mobile;
+    	$arr['telphone'] =$telphone;
+    	$arr['is_default'] = $is_default;
+    	$arr['is_del'] = 1;
+    	$arr['seller_id'] = 0;
+
+    	$tb_merch_ship_info->setData($arr);
+    	//判断是添加还是修改
+    	if($id)
+    	{
+    		$tb_merch_ship_info->update('id='.$id." and seller_id = 0");
+    	}
+    	else
+    	{
+    		$tb_merch_ship_info->add();
+    	}
+		$this->redirect('ship_info_list');
+	}
+	/**
+	 * @brief 删除发货信息到回收站中
+	 */
+	public function ship_info_del()
+	{
+		// 获取POST数据
+    	$id = IFilter::act(IReq::get('id'),'int');
+
+		//加载 商家发货点信息
+    	$tb_merch_ship_info = new IModel('merch_ship_info');
+    	$tb_merch_ship_info->setData(array('is_del' => 0));
+		if($id)
+		{
+			$tb_merch_ship_info->update(Util::joinStr($id)." and seller_id = 0");
+			$this->redirect('ship_info_list');
+		}
+		else
+		{
+			$this->redirect('ship_info_list',false);
+			Util::showMessage('请选择要删除的数据');
+		}
+	}
+	/**
+	 * @brief 还原回收站的信息到列表
+	 */
+	public function recycle_restore()
+	{
+		// 获取POST数据
+    	$id = IFilter::act(IReq::get('id'),'int');
+		//加载 商家发货点信息
+    	$tb_merch_ship_info = new IModel('merch_ship_info');
+    	$tb_merch_ship_info->setData(array('is_del' => 1));
+		if($id)
+		{
+			$tb_merch_ship_info->update(Util::joinStr($id)." and seller_id = 0");
+			$this->redirect('ship_recycle_list');
+		}
+		else
+		{
+			$this->redirect('ship_recycle_list',false);
+		}
+	}
+	/**
+	 * @brief 删除收货地址的信息
+	 */
+	public function recycle_del()
+	{
+		// 获取POST数据
+    	$id = IFilter::act(IReq::get('id'),'int');
+		//加载 商家发货点信息
+    	$tb_merch_ship_info = new IModel('merch_ship_info');
+		if($id)
+		{
+			$tb_merch_ship_info->del(Util::joinStr($id).' and seller_id = 0');
+			$this->redirect('ship_recycle_list');
+		}
+		else
+		{
+			$this->redirect('ship_recycle_list',false);
+			Util::showMessage('请选择要删除的数据');
+		}
+	}
+
+	//快递单背景图片上传
+	public function expresswaybill_upload()
+	{
+		$result = array(
+			'isError' => true,
+		);
+
+		if(isset($_FILES['attach']['name']) && $_FILES['attach']['name'] != '')
+		{
+			$photoObj = new PhotoUpload();
+			$photo    = $photoObj->run();
+
+			$result['isError'] = false;
+			$result['data']    = $photo['attach']['img'];
+		}
+		else
+		{
+			$result['message'] = '请选择图片';
+		}
+
+		echo '<script type="text/javascript">parent.photoUpload_callback('.JSON::encode($result).');</script>';
+	}
+
+	//快递单添加修改
+	public function expresswaybill_edit()
+	{
+		$id = intval(IReq::get('id'));
+
+		$this->expressRow = array();
+
+		//修改模式
+		if($id)
+		{
+			$expressObj       = new IModel('expresswaybill');
+			$this->expressRow = $expressObj->getObj('id = '.$id);
+		}
+
+		$this->redirect('expresswaybill_edit');
+	}
+
+	//快递单添加修改动作
+	public function expresswaybill_edit_act()
+	{
+		$id           = intval(IReq::get('id'));
+		$printExpress = IReq::get('printExpress');
+		$name         = IFilter::act(IReq::get('express_name'));
+		$width        = intval(IReq::get('width'));
+		$height       = intval(IReq::get('height'));
+		$background   = IFilter::act(IReq::get('printBackground'));
+		$background   = ltrim($background,IUrl::creatUrl(''));
+
+		if(!$printExpress)
+		{
+			$printExpress = array();
+		}
+
+		if(!$name)
+		{
+			die('快递单的名称不能为空');
+		}
+
+		$expressObj     = new IModel('expresswaybill');
+
+		$data = array(
+			'config'     => serialize($printExpress),
+			'name'       => $name,
+			'width'      => $width,
+			'height'     => $height,
+			'background' => $background,
+		);
+
+		$expressObj->setData($data);
+
+		//修改模式
+		if($id)
+		{
+			$is_result = $expressObj->update('id = '.$id);
+		}
+		else
+		{
+			$is_result = $expressObj->add();
+		}
+		echo $is_result === false ? '操作失败' : 'success';
+	}
+
+	//快递单删除
+	public function expresswaybill_del()
+	{
+		$id = intval(IReq::get('id'));
+		$expressObj = new IModel('expresswaybill');
+		$expressObj->del('id = '.$id);
+		$this->redirect('print_template/tab_index/3');
+	}
+
+	//选择快递单打印类型
+	public function expresswaybill_template()
+	{
+		$this->layout = 'print';
+		$seller_id    = IFilter::act(IReq::get('seller_id'),'int');
+
+    	//获得order_id的值
+		$order_id = IFilter::act(IReq::get('id'),'int');
+		$order_id = is_array($order_id) ? join(',',$order_id) : $order_id;
+
+		if(!$order_id)
+		{
+			$this->redirect('order_list');
+			return;
+		}
+
+		$ord_class       = new Order_Class();
+ 		$this->orderInfo = $ord_class->getOrderInfo($order_id,$seller_id);
+		$this->redirect('expresswaybill_template');
+	}
+
+	//打印快递单
+	public function expresswaybill_print()
+	{
+		$config_conver = array();
+		$this->layout  = 'print';
+
+		$order_id     = IFilter::act(IReq::get('order_id'));
+		$seller_id    = IFilter::act(IReq::get('seller_id'),'int');
+		$express_id   = intval(IReq::get('express_id'));
+		$expressObj   = new IModel('expresswaybill');
+		$expressRow   = $expressObj->getObj('id = '.$express_id);
+
+		if(empty($expressRow))
+		{
+			die('不存在此快递单信息');
+		}
+
+		$expressConfig     = unserialize($expressRow['config']);
+		$expresswaybillObj = new Expresswaybill();
+
+		$config_conver       = $expresswaybillObj->conver($expressConfig,$order_id,$seller_id);
+		$this->config_conver = str_replace('trackingLeft','letterSpacing',$config_conver);
+		if(!$this->config_conver)
+		{
+			die('快递单模板配置不正确');
+		}
+		$this->order_id      = $order_id;
+		$this->expressRow    = $expressRow;
+		$this->redirect('expresswaybill_print');
+	}
+
+	//订单导出excel 参考订单列表
+	public function order_report()
+	{
+		//搜索条件
+		$search = IReq::get('search');
+
+		//条件筛选处理
+		list($join,$where) = order_class::getSearchCondition($search);
+
+		//拼接sql
+		$orderHandle = new IQuery('order as o');
+		$orderHandle->order  = "o.id desc";
+		$orderHandle->fields = "o.*,d.name as distribute_name,p.name as payment_name";
+		$orderHandle->join   = $join;
+		$orderHandle->where  = $where;
+		$orderList = $orderHandle->find();
+
+		$reportObj = new report('order');
+		$reportObj->setTitle(array("订单编号","日期","收货人","收货地址","电话","订单金额","支付方式","支付状态","发货状态","商品信息"));
+
+		foreach($orderList as $k => $val)
+		{
+			$orderGoods = Order_class::getOrderGoods($val['id']);
+			$strGoods   = "";
+			foreach($orderGoods as $good)
+			{
+				$strGoods .= "商品编号:".$good['goodsno']." 商品名称:".$good['name']." 商品数量:".$good['goods_nums'];
+				if ( isset($good['value']) && $good['value'] )
+				{
+					$strGoods .= " 规格:".$good['value'];
+				}
+				$strGoods .= "<br />";
+			}
+
+			$insertData = array(
+				$val['order_no'],
+				$val['create_time'],
+				$val['accept_name'],
+				join('&nbsp;',area::name($val['province'],$val['city'],$val['area'])).$val['address'],
+				$val['telphone'].'&nbsp;'.$val['mobile'],
+				$val['order_amount'],
+				$val['payment_name'],
+				Order_Class::getOrderPayStatusText($val),
+				Order_Class::getOrderDistributionStatusText($val),
+				$strGoods,
+			);
+			$reportObj->setData($insertData);
+		}
+		$reportObj->toDownload();
+	}
+}

+ 154 - 0
src/controllers/pic.php

@@ -0,0 +1,154 @@
+<?php
+/**
+ * @copyright (c) 2011 aircheng.com
+ * @file pic.php
+ * @brief 图库处理
+ * @author chendeshan
+ * @date 2010-12-16
+ */
+class Pic extends IController
+{
+	public $layout = '';
+
+	function init()
+	{
+
+	}
+	//规格图片上传
+	function uploadFile()
+	{
+		//上传状态
+		$state = false;
+
+		//规格索引值
+		$specIndex = IFilter::act(IReq::get('specIndex'));
+		if($specIndex === null)
+		{
+			$message = '没有找到规格索引值';
+		}
+		else
+		{
+			//本地上传方式
+			if(isset($_FILES['attach']) && $_FILES['attach']['name'])
+			{
+			 	//调用文件上传类
+				$photoObj = new PhotoUpload();
+				$photoInfo= $photoObj->run();
+				$photoInfo= current($photoInfo);
+
+				if($photoInfo['flag']==1)
+				{
+					$fileName = $photoInfo['img'];
+					$state = true;
+				}
+
+				//实例化
+				$obj = new IModel('spec_photo');
+				$insertData = array(
+					'address'     => $photoInfo['img'],
+					'create_time' => ITime::getDateTime(),
+				);
+				$obj->setData($insertData);
+				$obj->add();
+			}
+
+			//远程网络方式
+			else if($fileName=IReq::get('outerSrc','post'))
+			{
+				$state = true;
+			}
+
+			//图库选择方式
+			else if($fileName=IReq::get('selectPhoto','post'))
+			{
+				$state = true;
+			}
+		}
+
+		//根据状态值进行
+		if($state == true)
+		{
+			die("<script type='text/javascript'>parent.art.dialog({id:'addSpecWin'}).iframe.contentWindow.updatePic(".$specIndex.",'".$fileName."');</script>");
+		}
+		else
+		{
+			die("<script type='text/javascript'>alert('添加图片失败');window.history.go(-1);</script>");
+		}
+	}
+
+	//获取图片列表
+	function getPhotoList()
+	{
+		$obj = new IModel('spec_photo');
+		$photoRs = $obj->query();
+		echo JSON::encode($photoRs);
+	}
+
+	//kindeditor图片上传
+	public function upload_json()
+	{
+		$save_path = $this->app->getBasePath().$this->app->config['upload'].'/';
+		$save_url  = IUrl::creatUrl('').$this->app->config['upload'].'/';
+		$realpath  = $this->app->getRuntimePath().'_systemjs/editor/php/upload_json.php';
+		include($realpath);
+	}
+
+	//kindeditor flash多图片上传
+	public function file_manager_json()
+	{
+		$root_path = $this->app->getBasePath().$this->app->config['upload'].'/';
+		$root_url  = IUrl::creatUrl('').$this->app->config['upload'].'/';
+		$realpath  = $this->app->getRuntimePath().'_systemjs/editor/php/file_manager_json.php';
+		include($realpath);
+	}
+
+	//生成缩略图
+	public function thumb()
+	{
+		//配置参数
+		$mixData = IFile::dirExplodeDecode(IReq::get('img'));
+
+		//http 304缓存
+		if(isset($_SERVER['HTTP_IF_NONE_MATCH']) && $_SERVER['HTTP_IF_NONE_MATCH'] == md5($mixData))
+		{
+			header("HTTP/1.1 304 Not Modified");
+			exit;
+		}
+
+		if($mixData)
+		{
+			preg_match("#/w/(\d+)#",$mixData,$widthData);
+			preg_match("#/h/(\d+)#",$mixData,$heightData);
+
+			//1,默认原图形式
+			$thumbSrc = $mixData;
+
+			//2,有缩略图的形式,替换原图形式
+			if(isset($widthData[1]) && isset($heightData[1]))
+			{
+				$imageSrc = str_replace(array($widthData[0],$heightData[0]),"",$mixData);
+				if(!$imageSrc)
+				{
+					return;
+				}
+				$width    = $widthData[1];
+				$height   = $heightData[1];
+				$thumbSrc = Thumb::get($imageSrc,$width,$height);
+			}
+
+			//设置扩展名
+			$fileExt = pathinfo($thumbSrc, PATHINFO_EXTENSION);
+			if(!in_array(strtolower($fileExt),array("jpg","png","gif","tbi")))
+			{
+				return;
+			}
+
+			$cacheTime  = 31104000;
+			header('Pragma: cache');
+			header('Cache-Control: max-age='.$cacheTime);
+ 			header('Content-type: image/'.$fileExt);
+ 			header("Etag: ".md5($mixData));
+ 			readfile($thumbSrc);
+		}
+	}
+}

+ 140 - 0
src/controllers/plugins.php

@@ -0,0 +1,140 @@
+<?php
+/**
+ * @brief 插件模块
+ * @class plugins
+ * @note  后台
+ */
+class plugins extends IController implements adminAuthorization
+{
+	public $layout='admin';
+	public $checkRight = array('check' => 'all');
+
+	function init()
+	{
+
+	}
+
+	//修改插件
+	public function plugin_edit()
+	{
+		$className = IFilter::act(IReq::get('class_name'));
+		if(!$className || !$pluginRow = plugin::getItems($className))
+		{
+			IError::show("插件不存在");
+		}
+		$this->pluginRow = $pluginRow;
+		if($this->pluginRow['is_install'] == 0)
+		{
+			IError::show("插件必须还没有安装无法进行配置");
+		}
+		$this->redirect('plugin_edit');
+	}
+
+	//更新插件信息
+	public function plugin_update()
+	{
+		$className    = IFilter::act(IReq::get('class_name'));
+		$isOpen       = IFilter::act(IReq::get('is_open'));
+		$sort         = IFilter::act(IReq::get('sort'));
+		$config_param = array();
+
+		$pluginRow = plugin::getItems($className);
+		if(!$pluginRow)
+		{
+			IError::show("插件不存在");
+		}
+
+		if($pluginRow['is_install'] == 0)
+		{
+			IError::show("插件还没有安装无法进行配置");
+		}
+
+		if($_POST)
+		{
+			foreach($_POST as $key => $val)
+			{
+				if(array_key_exists($key,$pluginRow['config_name']))
+				{
+					$config_param[$key] = is_array($val) ? join(";",$val) : $val;
+					$config_param[$key] = trim($config_param[$key]);
+				}
+			}
+		}
+		$pluginDB = new IModel('plugin');
+		$pluginDB->setData(array(
+			'is_open'      => $isOpen,
+			'sort'         => $sort,
+			'config_param' => IFilter::act(JSON::encode($config_param)),
+		));
+		$pluginDB->update('class_name = "'.$className.'"');
+		$this->redirect('plugin_list');
+	}
+
+	//删除插件
+	public function plugin_del()
+	{
+		$className = IFilter::act(IReq::get('class_name'));
+		$pluginRow = plugin::getItems($className);
+		if(!$pluginRow)
+		{
+			IError::show("插件不存在");
+		}
+
+		if($pluginRow['is_install'] == 0)
+		{
+			IError::show("插件未安装到系统");
+		}
+
+		//运行插件uninstall卸载接口
+		$uninstallResult = call_user_func(array($pluginRow['class_name'],"uninstall"));
+		if($uninstallResult === true)
+		{
+			//删除插件从plugin表数据库中
+			$pluginDB = new IModel('plugin');
+			$pluginDB->del('class_name = "'.$className.'"');
+		}
+		else
+		{
+			$message = is_string($uninstallResult) ? $uninstallResult : "卸载插件失败";
+			IError::show($message);
+		}
+		$this->redirect('plugin_list');
+	}
+
+	//添加插件
+	public function plugin_add()
+	{
+		$className = IFilter::act(IReq::get('class_name'));
+		$pluginRow = plugin::getItems($className);
+		if(!$pluginRow)
+		{
+			IError::show("插件不存在");
+		}
+
+		if($pluginRow['is_install'] == 1)
+		{
+			IError::show("插件已经安装到系统");
+		}
+
+		//运行插件install安装接口
+		$installResult = call_user_func(array($pluginRow['class_name'],"install"));
+		if($installResult === true)
+		{
+			//插入到plugin表数据库中
+			$pluginDB = new IModel('plugin');
+			$pluginDB->setData(array(
+				"name"       => $pluginRow['name'],
+				"class_name" => $pluginRow['class_name'],
+				"description"=> $pluginRow['description'],
+				"is_open"    => 0,
+			));
+			$pluginDB->add();
+		}
+		else
+		{
+			$message = is_string($installResult) ? $message : "安装插件失败";
+			IError::show($message);
+		}
+		$this->redirect('plugin_list');
+	}
+}

+ 1345 - 0
src/controllers/seller.php

@@ -0,0 +1,1345 @@
+<?php
+/**
+ * @brief 商家模块
+ * @class Seller
+ * @author chendeshan
+ * @datetime 2014/7/19 15:18:56
+ */
+class Seller extends IController implements sellerAuthorization
+{
+	public $layout = 'seller';
+
+	/**
+	 * @brief 初始化检查
+	 */
+	public function init()
+	{
+
+	}
+	/**
+	 * @brief 商品添加和修改视图
+	 */
+	public function goods_edit()
+	{
+		$goods_id = IFilter::act(IReq::get('id'),'int');
+
+		//初始化数据
+		$goods_class = new goods_class($this->seller['seller_id']);
+
+		//获取所有商品扩展相关数据
+		$data = $goods_class->edit($goods_id);
+
+		if($goods_id && !$data)
+		{
+			die("没有找到相关商品!");
+		}
+
+		$this->setRenderData($data);
+		$this->redirect('goods_edit');
+	}
+	//商品更新动作
+	public function goods_update()
+	{
+		$id       = IFilter::act(IReq::get('id'),'int');
+		$callback = IReq::get('callback');
+		$callback = strpos($callback,'seller/goods_list') === false ? '' : $callback;
+
+		//检查表单提交状态
+		if(!$_POST)
+		{
+			die('请确认表单提交正确');
+		}
+
+		//初始化商品数据
+		unset($_POST['id']);
+		unset($_POST['callback']);
+
+		$goodsObject = new goods_class($this->seller['seller_id']);
+		$goodsObject->update($id,$_POST);
+
+		$callback ? $this->redirect($callback) : $this->redirect("goods_list");
+	}
+	//商品列表
+	public function goods_list()
+	{
+		$seller_id = $this->seller['seller_id'];
+		$searchArray = Util::getUrlParam('search');
+		$searchParam = http_build_query($searchArray);
+		$condition = Util::goodsSearch(IReq::get('search'));
+		$where = "go.seller_id='$seller_id' ";
+		$where .= $condition ? " and ".$condition : "";
+		$join = isset($searchArray['search']['category_id']) ? " left join category_extend as ce on ce.goods_id = go.id " : "";
+		$page   = IReq::get('page') ? IFilter::act(IReq::get('page'),'int') : 1;
+
+		$goodHandle = new IQuery('goods as go');
+		$goodHandle->order  = "go.id desc";
+		$goodHandle->fields = "distinct go.id,go.name,go.sell_price,go.market_price,go.store_nums,go.img,go.is_del,go.seller_id,go.is_share,go.sort";
+		$goodHandle->where  = $where;
+		$goodHandle->page	= $page;
+		$goodHandle->join	= $join;
+
+		$this->goodHandle = $goodHandle;
+
+		$goods_info = array();
+		$goods_info['seller_id'] = $seller_id;
+		$goods_info['searchParam'] = $searchParam;
+		$this->setRenderData($goods_info);
+		$this->redirect('goods_list');
+	}
+
+	//商品列表
+	public function goods_report()
+	{
+		$seller_id = $this->seller['seller_id'];
+		$condition = Util::goodsSearch(IReq::get('search'));
+
+		$where  = 'go.seller_id='.$seller_id;
+		$where .= $condition ? " and ".$condition : "";
+		$join = isset($_GET['search']['category_id']) ? " left join category_extend as ce on ce.goods_id = go.id " : "";
+
+		$goodHandle = new IQuery('goods as go');
+		$goodHandle->order  = "go.id desc";
+		$goodHandle->fields = "go.*";
+		$goodHandle->where  = $where;
+		$goodHandle->join	= $join;
+		$goodList = $goodHandle->find();
+
+		$reportObj = new report('goods');
+		$reportObj->setTitle(array("商品名称","分类","售价","库存"));
+		foreach($goodList as $k => $val)
+		{
+			$insertData = array(
+				$val['name'],
+				goods_class::getGoodsCategory($val['id']),
+				$val['sell_price'],
+				$val['store_nums'],
+			);
+			$reportObj->setData($insertData);
+		}
+		$reportObj->toDownload();
+	}
+
+	//商品删除
+	public function goods_del()
+	{
+		//post数据
+	    $id = IFilter::act(IReq::get('id'),'int');
+
+	    //生成goods对象
+	    $goods = new goods_class();
+	    $goods->seller_id = $this->seller['seller_id'];
+
+	    if($id)
+		{
+			if(is_array($id))
+			{
+				foreach($id as $key => $val)
+				{
+					$goods->del($val);
+				}
+			}
+			else
+			{
+				$goods->del($id);
+			}
+		}
+		$this->redirect("goods_list");
+	}
+
+
+	//商品状态修改
+	public function goods_status()
+	{
+	    $id        = IFilter::act(IReq::get('id'),'int');
+		$is_del    = IFilter::act(IReq::get('is_del'),'int');
+		$is_del    = $is_del === 0 ? 3 : $is_del; //不能等于0直接上架
+		$seller_id = $this->seller['seller_id'];
+
+		$goodsDB = new IModel('goods');
+		$goodsDB->setData(array('is_del' => $is_del));
+
+	    if($id)
+		{
+			$id = is_array($id) ? join(",",$id) : $id;
+			$goodsDB->update("id in (".$id.") and seller_id = ".$seller_id);
+		}
+		$this->redirect("goods_list");
+	}
+
+	//规格删除
+	public function spec_del()
+	{
+		$id = IFilter::act(IReq::get('id'),'int');
+
+		if($id)
+		{
+			$idString = is_array($id) ? join(',',$id) : $id;
+			$specObj  = new IModel('spec');
+			$specObj->del("id in ( {$idString} ) and seller_id = ".$this->seller['seller_id']);
+			$this->redirect('spec_list');
+		}
+		else
+		{
+			$this->redirect('spec_list',false);
+			Util::showMessage('请选择要删除的规格');
+		}
+	}
+	//修改排序
+	public function ajax_sort()
+	{
+		$id   = IFilter::act(IReq::get('id'),'int');
+		$sort = IFilter::act(IReq::get('sort'),'int');
+
+		$goodsDB = new IModel('goods');
+		$goodsDB->setData(array('sort' => $sort));
+		$goodsDB->update("id = {$id} and seller_id = ".$this->seller['seller_id']);
+	}
+
+	//咨询回复
+	public function refer_reply()
+	{
+		$rid     = IFilter::act(IReq::get('refer_id'),'int');
+		$content = IFilter::act(IReq::get('content'),'text');
+
+		if($rid && $content)
+		{
+			$tb_refer = new IModel('refer');
+			$seller_id = $this->seller['seller_id'];//商户id
+			$data = array(
+				'answer' => $content,
+				'reply_time' => ITime::getDateTime(),
+				'seller_id' => $seller_id,
+				'status' => 1
+			);
+			$tb_refer->setData($data);
+			$tb_refer->update("id=".$rid);
+		}
+		$this->redirect('refer_list');
+	}
+	/**
+	 * @brief查看订单
+	 */
+	public function order_show()
+	{
+		//获得post传来的值
+		$order_id = IFilter::act(IReq::get('id'),'int');
+		$data = array();
+		if($order_id)
+		{
+			$order_show = new Order_Class();
+			$data = $order_show->getOrderShow($order_id,0,$this->seller['seller_id']);
+			if($data)
+			{
+		 		//获取地区
+		 		$data['area_addr'] = join('&nbsp;',area::name($data['province'],$data['city'],$data['area']));
+
+			 	$this->setRenderData($data);
+				$this->redirect('order_show',false);
+			}
+		}
+		if(!$data)
+		{
+			$this->redirect('order_list');
+		}
+	}
+	/**
+	 * @brief 发货订单页面
+	 */
+	public function order_deliver()
+	{
+		$order_id = IFilter::act(IReq::get('id'),'int');
+		$data     = array();
+
+		if($order_id)
+		{
+			$order_show = new Order_Class();
+			$data = $order_show->getOrderShow($order_id,0,$this->seller['seller_id']);
+			if($data)
+			{
+				$this->setRenderData($data);
+				$this->redirect('order_deliver');
+			}
+		}
+		if(!$data)
+		{
+			IError::show("订单信息不存在",403);
+		}
+	}
+	/**
+	 * @brief 发货操作
+	 */
+	public function order_delivery_doc()
+	{
+	 	//获得post变量参数
+	 	$order_id = IFilter::act(IReq::get('id'),'int');
+
+	 	//发送的商品关联
+	 	$sendgoods = IFilter::act(IReq::get('sendgoods'),'int');
+
+	 	if(!$sendgoods)
+	 	{
+	 		die('请选择要发货的商品');
+	 	}
+
+	 	$result = Order_Class::sendDeliveryGoods($order_id,$sendgoods,$this->seller['seller_id'],'seller');
+	 	if($result === true)
+	 	{
+	 		$this->redirect('order_list');
+	 	}
+	 	else
+	 	{
+	 		IError::show($result);
+	 	}
+	}
+	/**
+	 * @brief 订单列表
+	 */
+	public function order_list()
+	{
+		$seller_id = $this->seller['seller_id'];
+		$searchArray = Util::getUrlParam('search');
+		$searchParam = http_build_query($searchArray);
+		$condition = Util::orderSearch(IReq::get('search'));
+		$where  = "o.seller_id='$seller_id' and o.if_del=0 and o.status not in(3,4)";
+		$where .= $condition ? " and ".$condition : "";
+		$page   = IReq::get('page') ? IFilter::act(IReq::get('page'),'int') : 1;
+
+		$orderHandle = new IQuery('order as o');
+		$orderHandle->order  = "o.id desc";
+		$orderHandle->where  = $where;
+		$orderHandle->page	 = $page;
+		$this->orderHandle   = $orderHandle;
+		$order_info = array();
+		$order_info['seller_id'] = $seller_id;
+		$order_info['searchParam'] = $searchParam;
+		$this->setRenderData($order_info);
+		$this->redirect('order_list');
+	}
+
+	//订单导出 Excel
+	public function order_report()
+	{
+		$seller_id = $this->seller['seller_id'];
+		$condition = Util::orderSearch(IReq::get('search'));
+
+		$where  = "o.seller_id = ".$seller_id." and o.if_del=0 and o.status not in(3,4)";
+		$where .= $condition ? " and ".$condition : "";
+
+		//拼接sql
+		$orderHandle = new IQuery('order as o');
+		$orderHandle->order  = "o.id desc";
+		$orderHandle->fields = "o.*,p.name as payment_name";
+		$orderHandle->join   = "left join payment as p on p.id = o.pay_type";
+		$orderHandle->where  = $where;
+		$orderList = $orderHandle->find();
+
+		$reportObj = new report('order');
+		$reportObj->setTitle(array("订单编号","日期","收货人","收货地址","电话","订单金额","实际支付","支付方式","支付状态","发货状态","商品信息"));
+
+		foreach($orderList as $k => $val)
+		{
+			$orderGoods = Order_class::getOrderGoods($val['id']);
+			$strGoods   = "";
+			foreach($orderGoods as $good)
+			{
+				$strGoods .= "商品编号:".$good['goodsno']." 商品名称:".$good['name'];
+				if ($good['value']!='') $strGoods .= " 规格:".$good['value'];
+				$strGoods .= "<br />";
+			}
+
+			$insertData = array(
+				$val['order_no'],
+				$val['create_time'],
+				$val['accept_name'],
+				join('&nbsp;',area::name($val['province'],$val['city'],$val['area'])).$val['address'],
+				$val['telphone'].'&nbsp;'.$val['mobile'],
+				$val['payable_amount'],
+				$val['real_amount'],
+				$val['payment_name'],
+				Order_Class::getOrderPayStatusText($val),
+				Order_Class::getOrderDistributionStatusText($val),
+				$strGoods,
+			);
+			$reportObj->setData($insertData);
+		}
+		$reportObj->toDownload();
+	}
+
+	//修改商户信息
+	public function seller_edit()
+	{
+		$seller_id = $this->seller['seller_id'];
+		$sellerDB        = new IModel('seller');
+		$this->sellerRow = $sellerDB->getObj('id = '.$seller_id);
+		$this->redirect('seller_edit');
+	}
+
+	/**
+	 * @brief 商户的增加动作
+	 */
+	public function seller_add()
+	{
+		$seller_id   = $this->seller['seller_id'];
+		$email       = IFilter::act(IReq::get('email'));
+		$password    = IFilter::act(IReq::get('password'));
+		$repassword  = IFilter::act(IReq::get('repassword'));
+		$phone       = IFilter::act(IReq::get('phone'));
+		$mobile      = IFilter::act(IReq::get('mobile'));
+		$province    = IFilter::act(IReq::get('province'),'int');
+		$city        = IFilter::act(IReq::get('city'),'int');
+		$area        = IFilter::act(IReq::get('area'),'int');
+		$address     = IFilter::act(IReq::get('address'));
+		$account     = IFilter::act(IReq::get('account'));
+		$server_num  = IFilter::act(IReq::get('server_num'));
+		$home_url    = IFilter::act(IReq::get('home_url'));
+		$tax         = IFilter::act(IReq::get('tax'),'float');
+
+		if(!$seller_id && $password == '')
+		{
+			$errorMsg = '请输入密码!';
+		}
+
+		if($password != $repassword)
+		{
+			$errorMsg = '两次输入的密码不一致!';
+		}
+
+		//操作失败表单回填
+		if(isset($errorMsg))
+		{
+			$this->sellerRow = $_POST;
+			$this->redirect('seller_edit',false);
+			Util::showMessage($errorMsg);
+		}
+
+		//待更新的数据
+		$sellerRow = array(
+			'account'   => $account,
+			'phone'     => $phone,
+			'mobile'    => $mobile,
+			'email'     => $email,
+			'address'   => $address,
+			'province'  => $province,
+			'city'      => $city,
+			'area'      => $area,
+			'server_num'=> $server_num,
+			'home_url'  => $home_url,
+			'tax'      => $tax,
+		);
+
+		//logo图片处理
+		if(isset($_FILES['logo']['name']) && $_FILES['logo']['name']!='')
+		{
+			$uploadObj = new PhotoUpload();
+			$uploadObj->setIterance(false);
+			$photoInfo = $uploadObj->run();
+			if(isset($photoInfo['logo']['img']) && file_exists($photoInfo['logo']['img']))
+			{
+				$sellerRow['logo'] = $photoInfo['logo']['img'];
+			}
+		}
+
+		//创建商家操作类
+		$sellerDB   = new IModel("seller");
+
+		//修改密码
+		if($password)
+		{
+			$sellerRow['password'] = md5($password);
+		}
+
+		$sellerDB->setData($sellerRow);
+		$sellerDB->update("id = ".$seller_id);
+
+		$this->redirect('seller_edit');
+	}
+
+	//[团购]添加修改[单页]
+	function regiment_edit()
+	{
+		$id = IFilter::act(IReq::get('id'),'int');
+
+		if($id)
+		{
+			$regimentObj = new IModel('regiment');
+			$where       = 'id = '.$id.' and seller_id = '.$this->seller['seller_id'];
+			$regimentRow = $regimentObj->getObj($where);
+			if(!$regimentRow)
+			{
+				$this->redirect('regiment_list');
+			}
+
+			//促销商品
+			$goodsObj = new IModel('goods');
+			$goodsRow = $goodsObj->getObj('id = '.$regimentRow['goods_id']);
+
+			$result = array(
+				'isError' => false,
+				'data'    => $goodsRow,
+			);
+			$regimentRow['goodsRow'] = JSON::encode($result);
+			$this->regimentRow = $regimentRow;
+		}
+		$this->redirect('regiment_edit');
+	}
+
+	//[团购]删除
+	function regiment_del()
+	{
+		$id = IFilter::act(IReq::get('id'),'int');
+		if($id)
+		{
+			$regObj = new IModel('regiment');
+			if(is_array($id))
+			{
+				$id    = join(',',$id);
+			}
+			$where = ' id in ('.$id.') and seller_id = '.$this->seller['seller_id'];
+			$regObj->del($where);
+			$this->redirect('regiment_list');
+		}
+		else
+		{
+			$this->redirect('regiment_list',false);
+			Util::showMessage('请选择要删除的id值');
+		}
+	}
+
+	//[团购]添加修改[动作]
+	function regiment_edit_act()
+	{
+		$id      = IFilter::act(IReq::get('id'),'int');
+		$goodsId = IFilter::act(IReq::get('goods_id'),'int');
+
+		$dataArray = array(
+			'id'        	=> $id,
+			'title'     	=> IFilter::act(IReq::get('title','post')),
+			'start_time'	=> IFilter::act(IReq::get('start_time','post')),
+			'end_time'  	=> IFilter::act(IReq::get('end_time','post')),
+			'is_close'      => 2,
+			'intro'     	=> IFilter::act(IReq::get('intro','post')),
+			'goods_id'      => $goodsId,
+			'store_nums'    => IFilter::act(IReq::get('store_nums','post')),
+			'limit_min_count' => IFilter::act(IReq::get('limit_min_count','post'),'int'),
+			'limit_max_count' => IFilter::act(IReq::get('limit_max_count','post'),'int'),
+			'regiment_price'=> IFilter::act(IReq::get('regiment_price','post')),
+			'seller_id'     => $this->seller['seller_id'],
+		);
+
+		$dataArray['limit_min_count'] = $dataArray['limit_min_count'] <= 0 ? 1 : $dataArray['limit_min_count'];
+		$dataArray['limit_max_count'] = $dataArray['limit_max_count'] <= 0 ? $dataArray['store_nums'] : $dataArray['limit_max_count'];
+
+		if($goodsId)
+		{
+			$goodsObj = new IModel('goods');
+			$where    = 'id = '.$goodsId.' and seller_id = '.$this->seller['seller_id'];
+			$goodsRow = $goodsObj->getObj($where);
+
+			//商品信息不存在
+			if(!$goodsRow)
+			{
+				$this->regimentRow = $dataArray;
+				$this->redirect('regiment_edit',false);
+				Util::showMessage('请选择商户自己的商品');
+			}
+
+			//处理上传图片
+			if(isset($_FILES['img']['name']) && $_FILES['img']['name'] != '')
+			{
+				$uploadObj = new PhotoUpload();
+				$photoInfo = $uploadObj->run();
+				$dataArray['img'] = $photoInfo['img']['img'];
+			}
+			else
+			{
+				$dataArray['img'] = $goodsRow['img'];
+			}
+
+			$dataArray['sell_price'] = $goodsRow['sell_price'];
+		}
+		else
+		{
+			$this->regimentRow = $dataArray;
+			$this->redirect('regiment_edit',false);
+			Util::showMessage('请选择要关联的商品');
+		}
+
+		$regimentObj = new IModel('regiment');
+		$regimentObj->setData($dataArray);
+
+		if($id)
+		{
+			$where = 'id = '.$id.' and seller_id = '.$this->seller['seller_id'];
+			$regimentObj->update($where);
+		}
+		else
+		{
+			$regimentObj->add();
+		}
+		$this->redirect('regiment_list');
+	}
+
+	//结算单修改
+	public function bill_edit()
+	{
+		$id = IFilter::act(IReq::get('id'),'int');
+		$billRow = array();
+
+		if($id)
+		{
+			$billDB  = new IModel('bill');
+			$billRow = $billDB->getObj('id = '.$id.' and seller_id = '.$this->seller['seller_id']);
+		}
+
+		$this->billRow = $billRow;
+		$this->redirect('bill_edit');
+	}
+
+	//结算单删除
+	public function bill_del()
+	{
+		$id = IFilter::act(IReq::get('id'),'int');
+
+		if($id)
+		{
+			$billDB = new IModel('bill');
+			$billDB->del('id = '.$id.' and seller_id = '.$this->seller['seller_id'].' and is_pay = 0');
+		}
+
+		$this->redirect('bill_list');
+	}
+
+	//结算单更新
+	public function bill_update()
+	{
+		$id            = IFilter::act(IReq::get('id'),'int');
+		$start_time    = IFilter::act(IReq::get('start_time'));
+		$end_time      = IFilter::act(IReq::get('end_time'));
+		$apply_content = IFilter::act(IReq::get('apply_content'));
+
+		$billDB = new IModel('bill');
+
+		if($id)
+		{
+			$billRow = $billDB->getObj('id = '.$id);
+			if($billRow['is_pay'] == 0)
+			{
+				$billDB->setData(array('apply_content' => $apply_content));
+				$billDB->update('id = '.$id.' and seller_id = '.$this->seller['seller_id']);
+			}
+		}
+		else
+		{
+			//判断是否存在未处理的申请
+			$isSubmitBill = $billDB->getObj(" seller_id = ".$this->seller['seller_id']." and is_pay = 0");
+			if($isSubmitBill)
+			{
+				$this->redirect('bill_list',false);
+				Util::showMessage('请耐心等待管理员结算后才能再次提交申请');
+			}
+
+			//获取未结算的订单
+			$queryObject = CountSum::getSellerGoodsFeeQuery($this->seller['seller_id'],$start_time,$end_time,0);
+			$countData   = CountSum::countSellerOrderFee($queryObject->find());
+
+			if($countData['countFee'] > 0)
+			{
+				$countData['start_time'] = $start_time;
+				$countData['end_time']   = $end_time;
+
+				$billString = AccountLog::sellerBillTemplate($countData);
+				$data = array(
+					'seller_id'     => $this->seller['seller_id'],
+					'apply_time'    => ITime::getDateTime(),
+					'apply_content' => IFilter::act(IReq::get('apply_content')),
+					'start_time'    => $start_time,
+					'end_time'      => $end_time,
+					'log'           => $billString,
+					'order_ids'     => join(",",$countData['order_ids']),
+					'amount'        => $countData['countFee'],
+				);
+				$billDB->setData($data);
+				$billDB->add();
+			}
+			else
+			{
+				$this->redirect('bill_list',false);
+				Util::showMessage('当前时间段内没有任何结算货款');
+			}
+		}
+		$this->redirect('bill_list');
+	}
+
+	//计算应该结算的货款明细
+	public function countGoodsFee()
+	{
+		$seller_id   = $this->seller['seller_id'];
+		$start_time  = IFilter::act(IReq::get('start_time'));
+		$end_time    = IFilter::act(IReq::get('end_time'));
+
+		$queryObject = CountSum::getSellerGoodsFeeQuery($seller_id,$start_time,$end_time,0);
+		$countData   = CountSum::countSellerOrderFee($queryObject->find());
+
+		if($countData['countFee'] > 0)
+		{
+			$countData['start_time'] = $start_time;
+			$countData['end_time']   = $end_time;
+
+			$billString = AccountLog::sellerBillTemplate($countData);
+			$result     = array('result' => 'success','data' => $billString);
+		}
+		else
+		{
+			$result = array('result' => 'fail','data' => '当前没有任何款项可以结算');
+		}
+
+		die(JSON::encode($result));
+	}
+
+	/**
+	 * @brief 显示评论信息
+	 */
+	function comment_edit()
+	{
+		$cid = IFilter::act(IReq::get('cid'),'int');
+
+		if(!$cid)
+		{
+			$this->comment_list();
+			return false;
+		}
+		$query = new IQuery("comment as c");
+		$query->join = "left join goods as goods on c.goods_id = goods.id left join user as u on c.user_id = u.id";
+		$query->fields = "c.*,u.username,goods.name,goods.seller_id";
+		$query->where = "c.id=".$cid." and goods.seller_id = ".$this->seller['seller_id'];
+		$items = $query->find();
+
+		if($items)
+		{
+			$this->comment = current($items);
+			$this->redirect('comment_edit');
+		}
+		else
+		{
+			$this->comment_list();
+			$msg = '没有找到相关记录!';
+			Util::showMessage($msg);
+		}
+	}
+
+	/**
+	 * @brief 回复评论
+	 */
+	function comment_update()
+	{
+		$id = IFilter::act(IReq::get('id'),'int');
+		$recontent = IFilter::act(IReq::get('recontents'));
+		if($id)
+		{
+			$commentDB = new IQuery('comment as c');
+			$commentDB->join = 'left join goods as go on go.id = c.goods_id';
+			$commentDB->where= 'c.id = '.$id.' and go.seller_id = '.$this->seller['seller_id'];
+			$checkList = $commentDB->find();
+			if(!$checkList)
+			{
+				IError::show(403,'该商品不属于您,无法对其评论进行回复');
+			}
+
+			$updateData = array(
+				'recontents' => $recontent,
+				'recomment_time' => ITime::getDateTime(),
+			);
+			$commentDB = new IModel('comment');
+			$commentDB->setData($updateData);
+			$commentDB->update('id = '.$id);
+		}
+		$this->redirect('comment_list');
+	}
+
+	//商品退款详情
+	function refundment_show()
+	{
+	 	//获得post传来的退款单id值
+	 	$refundment_id = IFilter::act(IReq::get('id'),'int');
+	 	$data = array();
+	 	if($refundment_id)
+	 	{
+	 		$tb_refundment = new IQuery('refundment_doc as c');
+	 		$tb_refundment->join=' left join order as o on c.order_id=o.id left join user as u on u.id = c.user_id';
+	 		$tb_refundment->fields = 'u.username,c.*,o.*,c.id as id,c.pay_status as pay_status';
+	 		$tb_refundment->where = 'c.id='.$refundment_id.' and c.seller_id = '.$this->seller['seller_id'];
+	 		$refundment_info = $tb_refundment->find();
+	 		if($refundment_info)
+	 		{
+	 			$data = current($refundment_info);
+	 			$this->data = $data;
+	 			$this->setRenderData($data);
+	 			$this->redirect('refundment_show',false);
+	 		}
+	 	}
+
+	 	if(!$data)
+		{
+			$this->redirect('refundment_list');
+		}
+	}
+
+	//商品退款操作
+	function refundment_update()
+	{
+		$id           = IFilter::act(IReq::get('id'),'int');
+		$pay_status   = IFilter::act(IReq::get('pay_status'),'int');
+		$dispose_idea = IFilter::act(IReq::get('dispose_idea'));
+		$amount       = IFilter::act(IReq::get('amount'),'float');
+
+		if(!$pay_status)
+		{
+			die('选择处理状态');
+		}
+
+		//商户处理退款
+		if($id && Order_Class::isSellerRefund($id,$this->seller['seller_id']) == 2)
+		{
+			$updateData = array(
+				'dispose_time' => ITime::getDateTime(),
+				'dispose_idea' => $dispose_idea,
+				'pay_status'   => $pay_status == 1 ? 1 : 0,
+				'amount'       => $amount,
+			);
+			$tb_refundment_doc = new IModel('refundment_doc');
+			$tb_refundment_doc->setData($updateData);
+			$tb_refundment_doc->update('id = '.$id);
+
+			if($pay_status == 2)
+			{
+				$result = Order_Class::refund($id,$this->seller['seller_id'],'seller');
+				if(is_string($result))
+				{
+					$tb_refundment_doc->rollback();
+					die($result);
+				}
+			}
+		}
+		$this->redirect('refundment_list');
+	}
+
+	//商品复制
+	function goods_copy()
+	{
+		$idArray = explode(',',IReq::get('id'));
+		$idArray = IFilter::act($idArray,'int');
+
+		$goodsDB     = new IModel('goods');
+		$goodsAttrDB = new IModel('goods_attribute');
+		$goodsPhotoRelationDB = new IModel('goods_photo_relation');
+		$productsDB = new IModel('products');
+
+		$goodsData = $goodsDB->query('id in ('.join(',',$idArray).') and is_share = 1 and is_del = 0 and seller_id = 0','*');
+		if($goodsData)
+		{
+			foreach($goodsData as $key => $val)
+			{
+				//判断是否重复
+				if( $goodsDB->getObj('seller_id = '.$this->seller['seller_id'].' and name = "'.$val['name'].'"') )
+				{
+					die('商品不能重复复制');
+				}
+
+				$oldId = $val['id'];
+
+				//商品数据
+				unset($val['id'],$val['visit'],$val['favorite'],$val['sort'],$val['comments'],$val['sale'],$val['grade'],$val['is_share']);
+				$val['seller_id'] = $this->seller['seller_id'];
+				$val['goods_no'] .= '-'.$this->seller['seller_id'];
+				$val['name']      = IFilter::act($val['name'],'text');
+				$val['content']   = IFilter::act($val['content'],'text');
+
+				$goodsDB->setData($val);
+				$goods_id = $goodsDB->add();
+
+				//商品属性
+				$attrData = $goodsAttrDB->query('goods_id = '.$oldId);
+				if($attrData)
+				{
+					foreach($attrData as $k => $v)
+					{
+						unset($v['id']);
+						$v['goods_id'] = $goods_id;
+						$goodsAttrDB->setData($v);
+						$goodsAttrDB->add();
+					}
+				}
+
+				//商品图片
+				$photoData = $goodsPhotoRelationDB->query('goods_id = '.$oldId);
+				if($photoData)
+				{
+					foreach($photoData as $k => $v)
+					{
+						unset($v['id']);
+						$v['goods_id'] = $goods_id;
+						$goodsPhotoRelationDB->setData($v);
+						$goodsPhotoRelationDB->add();
+					}
+				}
+
+				//货品
+				$productsData = $productsDB->query('goods_id = '.$oldId);
+				if($productsData)
+				{
+					foreach($productsData as $k => $v)
+					{
+						unset($v['id']);
+						$v['products_no'].= '-'.$this->seller['seller_id'];
+						$v['goods_id']    = $goods_id;
+						$productsDB->setData($v);
+						$productsDB->add();
+					}
+				}
+			}
+			die('success');
+		}
+		else
+		{
+			die('复制的商品不存在');
+		}
+	}
+
+	/**
+	 * @brief 添加/修改发货信息
+	 */
+	public function ship_info_edit()
+	{
+		// 获取POST数据
+    	$id = IFilter::act(IReq::get("sid"),'int');
+    	if($id)
+    	{
+    		$tb_ship   = new IModel("merch_ship_info");
+    		$ship_info = $tb_ship->getObj("id=".$id." and seller_id = ".$this->seller['seller_id']);
+    		if($ship_info)
+    		{
+    			$this->data = $ship_info;
+    		}
+    		else
+    		{
+    			die('数据不存在');
+    		}
+    	}
+    	$this->setRenderData($this->data);
+		$this->redirect('ship_info_edit');
+	}
+	/**
+	 * @brief 设置发货信息的默认值
+	 */
+	public function ship_info_default()
+	{
+		$id = IFilter::act( IReq::get('id'),'int' );
+        $default = IFilter::string(IReq::get('default'));
+        $tb_merch_ship_info = new IModel('merch_ship_info');
+        if($default == 1)
+        {
+            $tb_merch_ship_info->setData(array('is_default'=>0));
+            $tb_merch_ship_info->update("seller_id = ".$this->seller['seller_id']);
+        }
+        $tb_merch_ship_info->setData(array('is_default' => $default));
+        $tb_merch_ship_info->update("id = ".$id." and seller_id = ".$this->seller['seller_id']);
+        $this->redirect('ship_info_list');
+	}
+	/**
+	 * @brief 保存添加/修改发货信息
+	 */
+	public function ship_info_update()
+	{
+		// 获取POST数据
+    	$id = IFilter::act(IReq::get('sid'),'int');
+    	$ship_name = IFilter::act(IReq::get('ship_name'));
+    	$ship_user_name = IFilter::act(IReq::get('ship_user_name'));
+    	$sex = IFilter::act(IReq::get('sex'),'int');
+    	$province =IFilter::act(IReq::get('province'),'int');
+    	$city = IFilter::act(IReq::get('city'),'int');
+    	$area = IFilter::act(IReq::get('area'),'int');
+    	$address = IFilter::act(IReq::get('address'));
+    	$postcode = IFilter::act(IReq::get('postcode'),'int');
+    	$mobile = IFilter::act(IReq::get('mobile'));
+    	$telphone = IFilter::act(IReq::get('telphone'));
+    	$is_default = IFilter::act(IReq::get('is_default'),'int');
+
+    	$tb_merch_ship_info = new IModel('merch_ship_info');
+
+    	//判断是否已经有了一个默认地址
+    	if(isset($is_default) && $is_default==1)
+    	{
+    		$tb_merch_ship_info->setData(array('is_default' => 0));
+    		$tb_merch_ship_info->update('seller_id = 0');
+    	}
+    	//设置存储数据
+    	$arr['ship_name'] = $ship_name;
+	    $arr['ship_user_name'] = $ship_user_name;
+	    $arr['sex'] = $sex;
+    	$arr['province'] = $province;
+    	$arr['city'] =$city;
+    	$arr['area'] =$area;
+    	$arr['address'] = $address;
+    	$arr['postcode'] = $postcode;
+    	$arr['mobile'] = $mobile;
+    	$arr['telphone'] =$telphone;
+    	$arr['is_default'] = $is_default;
+    	$arr['is_del'] = 1;
+    	$arr['seller_id'] = $this->seller['seller_id'];
+
+    	$tb_merch_ship_info->setData($arr);
+    	//判断是添加还是修改
+    	if($id)
+    	{
+    		$tb_merch_ship_info->update('id='.$id." and seller_id = ".$this->seller['seller_id']);
+    	}
+    	else
+    	{
+    		$tb_merch_ship_info->add();
+    	}
+		$this->redirect('ship_info_list');
+	}
+	/**
+	 * @brief 删除发货信息到回收站中
+	 */
+	public function ship_info_del()
+	{
+		// 获取POST数据
+    	$id = IFilter::act(IReq::get('id'),'int');
+		//加载 商家发货点信息
+    	$tb_merch_ship_info = new IModel('merch_ship_info');
+		if($id)
+		{
+			$tb_merch_ship_info->del(Util::joinStr($id)." and seller_id = ".$this->seller['seller_id']);
+			$this->redirect('ship_info_list');
+		}
+		else
+		{
+			$this->redirect('ship_info_list',false);
+			Util::showMessage('请选择要删除的数据');
+		}
+	}
+
+	/**
+	 * @brief 配送方式修改
+	 */
+    public function delivery_edit()
+	{
+		$data = array();
+        $delivery_id = IFilter::act(IReq::get('id'),'int');
+
+        if($delivery_id)
+        {
+            $delivery = new IModel('delivery_extend');
+            $data = $delivery->getObj('delivery_id = '.$delivery_id.' and seller_id = '.$this->seller['seller_id']);
+		}
+		else
+		{
+			die('配送方式');
+		}
+
+		//获取省份
+		$areaData = array();
+		$areaDB = new IModel('areas');
+		$areaList = $areaDB->query('parent_id = 0');
+		foreach($areaList as $val)
+		{
+			$areaData[$val['area_id']] = $val['area_name'];
+		}
+		$this->areaList  = $areaList;
+		$this->data_info = $data;
+		$this->area      = $areaData;
+        $this->redirect('delivery_edit');
+	}
+
+	/**
+	 * 配送方式修改
+	 */
+    public function delivery_update()
+    {
+        //首重重量
+        $first_weight = IFilter::act(IReq::get('first_weight'),'float');
+        //续重重量
+        $second_weight = IFilter::act(IReq::get('second_weight'),'float');
+        //首重价格
+        $first_price = IFilter::act(IReq::get('first_price'),'float');
+        //续重价格
+        $second_price = IFilter::act(IReq::get('second_price'),'float');
+        //是否支持物流保价
+        $is_save_price = IFilter::act(IReq::get('is_save_price'),'int');
+        //地区费用类型
+        $price_type = IFilter::act(IReq::get('price_type'),'int');
+        //启用默认费用
+        $open_default = IFilter::act(IReq::get('open_default'),'int');
+        //支持的配送地区ID
+        $area_groupid = serialize(IReq::get('area_groupid'));
+        //配送地址对应的首重价格
+        $firstprice = serialize(IReq::get('firstprice'));
+        //配送地区对应的续重价格
+        $secondprice = serialize(IReq::get('secondprice'));
+        //保价费率
+        $save_rate = IFilter::act(IReq::get('save_rate'),'float');
+        //最低保价
+        $low_price = IFilter::act(IReq::get('low_price'),'float');
+		//配送ID
+        $delivery_id = IFilter::act(IReq::get('deliveryId'),'int');
+
+        $deliveryDB  = new IModel('delivery');
+        $deliveryRow = $deliveryDB->getObj('id = '.$delivery_id);
+        if(!$deliveryRow)
+        {
+        	die('配送方式不存在');
+        }
+
+        //如果选择指定地区配送就必须要选择地区
+        if($price_type == 1 && !$area_groupid)
+        {
+			die('请设置配送地区');
+        }
+
+        $data = array(
+        	'first_weight' => $first_weight,
+        	'second_weight'=> $second_weight,
+        	'first_price'  => $first_price,
+        	'second_price' => $second_price,
+        	'is_save_price'=> $is_save_price,
+        	'price_type'   => $price_type,
+        	'open_default' => $open_default,
+        	'area_groupid' => $area_groupid,
+        	'firstprice'   => $firstprice,
+        	'secondprice'  => $secondprice,
+        	'save_rate'    => $save_rate,
+        	'low_price'    => $low_price,
+        	'seller_id'    => $this->seller['seller_id'],
+        	'delivery_id'  => $delivery_id,
+        );
+        $deliveryExtendDB = new IModel('delivery_extend');
+        $deliveryExtendDB->setData($data);
+        $deliveryObj = $deliveryExtendDB->getObj("delivery_id = ".$delivery_id." and seller_id = ".$this->seller['seller_id']);
+        //已经存在了
+        if($deliveryObj)
+        {
+        	$deliveryExtendDB->update('delivery_id = '.$delivery_id.' and seller_id = '.$this->seller['seller_id']);
+        }
+        else
+        {
+        	$deliveryExtendDB->add();
+        }
+		$this->redirect('delivery');
+    }
+
+	//[促销活动] 添加修改 [单页]
+	function pro_rule_edit()
+	{
+		$id = IFilter::act(IReq::get('id'),'int');
+		if($id)
+		{
+			$promotionObj = new IModel('promotion');
+			$where = 'id = '.$id.' and seller_id='.$this->seller['seller_id'];
+			$this->promotionRow = $promotionObj->getObj($where);
+		}
+		$this->redirect('pro_rule_edit');
+	}
+
+	//[促销活动] 添加修改 [动作]
+	function pro_rule_edit_act()
+	{
+		$id           = IFilter::act(IReq::get('id'),'int');
+		$user_group   = IFilter::act(IReq::get('user_group','post'));
+		$promotionObj = new IModel('promotion');
+		if(is_string($user_group))
+		{
+			$user_group_str = $user_group;
+		}
+		else
+		{
+			$user_group_str = ",".join(',',$user_group).",";
+		}
+
+		$dataArray = array(
+			'name'       => IFilter::act(IReq::get('name','post')),
+			'condition'  => IFilter::act(IReq::get('condition','post')),
+			'is_close'   => IFilter::act(IReq::get('is_close','post')),
+			'start_time' => IFilter::act(IReq::get('start_time','post')),
+			'end_time'   => IFilter::act(IReq::get('end_time','post')),
+			'intro'      => IFilter::act(IReq::get('intro','post')),
+			'award_type' => IFilter::act(IReq::get('award_type','post')),
+			'type'       => 0,
+			'user_group' => $user_group_str,
+			'award_value'=> IFilter::act(IReq::get('award_value','post')),
+			'seller_id'  => $this->seller['seller_id'],
+		);
+
+		if(!in_array($dataArray['award_type'],array(1,2,6)))
+		{
+			IError::show('促销类型不符合规范',403);
+		}
+
+		$promotionObj->setData($dataArray);
+
+		if($id)
+		{
+			$where = 'id = '.$id;
+			$promotionObj->update($where);
+		}
+		else
+		{
+			$promotionObj->add();
+		}
+		$this->redirect('pro_rule_list');
+	}
+
+	//[促销活动] 删除
+	function pro_rule_del()
+	{
+		$id = IFilter::act(IReq::get('id'),'int');
+		if(!empty($id))
+		{
+			$promotionObj = new IModel('promotion');
+			if(is_array($id))
+			{
+				$idStr = join(',',$id);
+				$where = ' id in ('.$idStr.')';
+			}
+			else
+			{
+				$where = 'id = '.$id;
+			}
+			$promotionObj->del($where.' and seller_id = '.$this->seller['seller_id']);
+			$this->redirect('pro_rule_list');
+		}
+		else
+		{
+			$this->redirect('pro_rule_list',false);
+			Util::showMessage('请选择要删除的促销活动');
+		}
+	}
+
+	//修改订单价格
+	public function order_discount()
+	{
+		$order_id = IFilter::act(IReq::get('order_id'),'int');
+		$discount = IFilter::act(IReq::get('discount'),'float');
+		$orderDB  = new IModel('order');
+		$orderRow = $orderDB->getObj('id = '.$order_id.' and status = 1 and distribution_status = 0 and seller_id = '.$this->seller['seller_id']);
+		if($orderRow)
+		{
+			//还原价格
+			$newOrderAmount = ($orderRow['order_amount'] - $orderRow['discount']) + $discount;
+			$newOrderAmount = $newOrderAmount <= 0 ? 0 : $newOrderAmount;
+			if($newOrderAmount == 0)
+			{
+				die(JSON::encode(array('result' => false,'message' => '订单减价折扣不能低于订单总额')));
+			}
+			$orderDB->setData(array('discount' => $discount,'order_amount' => $newOrderAmount));
+			if($orderDB->update('id = '.$order_id))
+			{
+				die(JSON::encode(array('result' => true,'orderAmount' => $newOrderAmount)));
+			}
+		}
+		die(JSON::encode(array('result' => false)));
+	}
+
+	// 消息通知
+	public function message_list()
+	{
+		$page   = IReq::get('page') ? IFilter::act(IReq::get('page'),'int') : 1;
+		$seller_messObject = new seller_mess($this->seller['seller_id']);
+		$msgIds = $seller_messObject->getAllMsgIds();
+		$msgIds = empty($msgIds) ? 0 : $msgIds;
+		$needReadNum = $seller_messObject->needReadNum();
+
+		$seller_messageHandle = new IQuery('seller_message');
+		$seller_messageHandle->where = "id in(".$msgIds.")";
+		$seller_messageHandle->order= "id desc";
+		$seller_messageHandle->page = $page;
+
+		$this->needReadNum = $needReadNum;
+		$this->seller_messObject = $seller_messObject;
+		$this->seller_messageHandle = $seller_messageHandle;
+
+		$this->redirect("message_list");
+	}
+
+	// 消息详情
+	public function message_show()
+	{
+		$id = IFilter::act(IReq::get('id'),'int');
+		$messageRow = null;
+		if($id)
+		{
+			$seller_messObject = new seller_mess($this->seller['seller_id']);
+			$seller_messObject->writeMessage($id, 1);
+			$messageRow = $seller_messObject->read($id);
+		}
+
+		if(!$messageRow)
+		{
+			die('信息不存在');
+		}
+		$this->setRenderData(array('messageRow' => $messageRow));
+		$this->redirect('message_show');
+	}
+
+	// 消息删除
+	public function message_del()
+	{
+		$id = IFilter::act(IReq::get('id'),'int');
+		if (!empty($id))
+		{
+			$seller_messObject = new seller_mess($this->seller['seller_id']);
+			if (is_array($id)) {
+				foreach ($id as $val)
+				{
+					$seller_messObject->delMessage($val);
+				}
+			}else {
+				$seller_messObject->delMessage($id);
+			}
+		}
+		$this->redirect('message_list');
+	}
+
+	//订单备注
+	public function order_note()
+	{
+	 	//获得post数据
+	 	$order_id = IFilter::act(IReq::get('order_id'),'int');
+	 	$note = IFilter::act(IReq::get('note'),'text');
+
+	 	//获得order的表对象
+	 	$tb_order =  new IModel('order');
+	 	$tb_order->setData(array(
+	 		'note'=>$note
+	 	));
+	 	$tb_order->update('id = '.$order_id.' and seller_id = '.$this->seller['seller_id']);
+	 	$this->redirect("/seller/order_show/id/".$order_id,true);
+	}
+
+	/**
+	 * @brief 删除咨询信息
+	 */
+	function refer_del()
+	{
+		$refer_ids = IFilter::act(IReq::get('id'),'int');
+		$refer_ids = is_array($refer_ids) ? $refer_ids : array($refer_ids);
+		if($refer_ids)
+		{
+			$ids = join(',',$refer_ids);
+			if($ids)
+			{
+				//查询咨询的商品是否属于当前商户
+				$referDB        = new IQuery('refer as re,goods as go');
+				$referDB->where = "re.id in (".$ids.") and re.goods_id = go.id and go.seller_id = ".$this->seller['seller_id'];
+				$referDB->fields= "re.id";
+				$referGoods     = $referDB->find();
+				$referModel     = new IModel('refer');
+				foreach($referGoods as $reId)
+				{
+					$referModel->del("id = ".$reId['id']);
+				}
+			}
+		}
+		$this->redirect('refer_list');
+	}
+}

+ 1390 - 0
src/controllers/simple.php

@@ -0,0 +1,1390 @@
+<?php
+/**
+ * @copyright Copyright(c) 2011 aircheng.com
+ * @file Simple.php
+ * @brief
+ * @author webning
+ * @date 2011-03-22
+ * @version 0.6
+ * @note
+ */
+/**
+ * @brief Simple
+ * @class Simple
+ * @note
+ */
+class Simple extends IController
+{
+    public $layout='site_mini';
+
+	function init()
+	{
+
+	}
+
+	function login()
+	{
+		//如果已经登录,就跳到ucenter页面
+		if($this->user)
+		{
+			$this->redirect("/ucenter/index");
+		}
+		else
+		{
+			$this->redirect('login');
+		}
+	}
+
+	//退出登录
+    function logout()
+    {
+    	plugin::trigger('clearUser');
+    	$this->redirect('login');
+    }
+
+    //用户注册
+    function reg_act()
+    {
+    	//调用_userInfo注册插件
+    	$result = plugin::trigger("userRegAct");
+    	if(is_array($result))
+    	{
+			//自定义跳转页面
+			$this->redirect('/site/success?message='.urlencode("注册成功!"));
+    	}
+    	else
+    	{
+    		$this->setError($result);
+    		$this->redirect('reg',false);
+    		Util::showMessage($result);
+    	}
+    }
+
+    //用户登录
+    function login_act()
+    {
+    	//调用_userInfo登录插件
+		$result = plugin::trigger('userLoginAct',$_POST);
+		if(is_array($result))
+		{
+			//自定义跳转页面
+			$callback = plugin::trigger('getCallback');
+			if($callback)
+			{
+				$this->redirect($callback);
+			}
+			else
+			{
+				$this->redirect('/ucenter/index');
+			}
+		}
+		else
+		{
+			$this->setError($result);
+			$this->redirect('login',false);
+			Util::showMessage($result);
+		}
+    }
+
+    //商品加入购物车[ajax]
+    function joinCart()
+    {
+    	$link      = IReq::get('link');
+    	$goods_id  = IFilter::act(IReq::get('goods_id'),'int');
+    	$goods_num = IFilter::act(IReq::get('goods_num'),'int');
+    	$goods_num = $goods_num == 0 ? 1 : $goods_num;
+		$type      = IFilter::act(IReq::get('type'));
+
+		//加入购物车
+    	$cartObj   = new Cart();
+    	$addResult = $cartObj->add($goods_id,$goods_num,$type);
+
+    	if($link != '')
+    	{
+    		if($addResult === false)
+    		{
+    			$this->cart(false);
+    			Util::showMessage($cartObj->getError());
+    		}
+    		else
+    		{
+    			$this->redirect($link);
+    		}
+    	}
+    	else
+    	{
+	    	if($addResult === false)
+	    	{
+		    	$result = array(
+		    		'isError' => true,
+		    		'message' => $cartObj->getError(),
+		    	);
+	    	}
+	    	else
+	    	{
+		    	$result = array(
+		    		'isError' => false,
+		    		'message' => '添加成功',
+		    	);
+	    	}
+	    	echo JSON::encode($result);
+    	}
+    }
+
+    //根据goods_id获取货品
+    function getProducts()
+    {
+    	$id           = IFilter::act(IReq::get('id'),'int');
+    	$productObj   = new IModel('products');
+    	$productsList = $productObj->query('goods_id = '.$id,'sell_price,id,spec_array,goods_id','store_nums desc',7);
+		if($productsList)
+		{
+			foreach($productsList as $key => $val)
+			{
+				$productsList[$key]['specData'] = Block::show_spec($val['spec_array']);
+			}
+		}
+		echo JSON::encode($productsList);
+    }
+
+    //删除购物车
+    function removeCart()
+    {
+    	$link      = IReq::get('link');
+    	$goods_id  = IFilter::act(IReq::get('goods_id'),'int');
+    	$type      = IFilter::act(IReq::get('type'));
+
+    	$cartObj   = new Cart();
+    	$cartInfo  = $cartObj->getMyCart();
+    	$delResult = $cartObj->del($goods_id,$type);
+
+    	if($link != '')
+    	{
+    		if($delResult === false)
+    		{
+    			$this->cart(false);
+    			Util::showMessage($cartObj->getError());
+    		}
+    		else
+    		{
+    			$this->redirect($link);
+    		}
+    	}
+    	else
+    	{
+	    	if($delResult === false)
+	    	{
+	    		$result = array(
+		    		'isError' => true,
+		    		'message' => $cartObj->getError(),
+	    		);
+	    	}
+	    	else
+	    	{
+		    	$goodsRow = $cartInfo[$type]['data'][$goods_id];
+		    	$cartInfo['sum']   -= $goodsRow['sell_price'] * $goodsRow['count'];
+		    	$cartInfo['count'] -= $goodsRow['count'];
+
+		    	$result = array(
+		    		'isError' => false,
+		    		'data'    => $cartInfo,
+		    	);
+	    	}
+
+	    	echo JSON::encode($result);
+    	}
+    }
+
+    //清空购物车
+    function clearCart()
+    {
+    	$cartObj = new Cart();
+    	$cartObj->clear();
+    	$this->redirect('cart');
+    }
+
+    //购物车div展示
+    function showCart()
+    {
+    	$cartObj  = new Cart();
+    	$cartList = $cartObj->getMyCart();
+    	$data['data'] = array_merge($cartList['goods']['data'],$cartList['product']['data']);
+    	$data['count']= $cartList['count'];
+    	$data['sum']  = $cartList['sum'];
+    	echo JSON::encode($data);
+    }
+
+    //购物车页面及商品价格计算[复杂]
+    function cart($redirect = false)
+    {
+    	//防止页面刷新
+    	header("Cache-Control: no-store, no-cache, must-revalidate");
+		header("Cache-Control: post-check=0, pre-check=0", false);
+
+		//开始计算购物车中的商品价格
+    	$countObj = new CountSum();
+    	$result   = $countObj->cart_count();
+
+    	if(is_string($result))
+    	{
+    		IError::show($result,403);
+    	}
+
+    	//返回值
+    	$this->final_sum = $result['final_sum'];
+    	$this->promotion = $result['promotion'];
+    	$this->proReduce = $result['proReduce'];
+    	$this->sum       = $result['sum'];
+    	$this->goodsList = $result['goodsList'];
+    	$this->count     = $result['count'];
+    	$this->reduce    = $result['reduce'];
+    	$this->weight    = $result['weight'];
+
+		//渲染视图
+    	$this->redirect('cart',$redirect);
+    }
+
+    //计算促销规则[ajax]
+    function promotionRuleAjax()
+    {
+    	$goodsId   = IFilter::act(IReq::get("goodsId"),'int');
+    	$productId = IFilter::act(IReq::get("productId"),'int');
+    	$num       = IFilter::act(IReq::get("num"),'int');
+
+    	if(!$goodsId || !$num)
+    	{
+			return;
+    	}
+
+		$goodsArray  = array();
+		$productArray= array();
+
+    	foreach($goodsId as $key => $goods_id)
+    	{
+    		$pid = $productId[$key];
+    		$nVal= $num[$key];
+
+    		if($pid > 0)
+    		{
+    			$productArray[$pid] = $nVal;
+    		}
+    		else
+    		{
+    			$goodsArray[$goods_id] = $nVal;
+    		}
+    	}
+
+		$countSumObj    = new CountSum();
+		$cartObj        = new Cart();
+		$countSumResult = $countSumObj->goodsCount($cartObj->cartFormat(array("goods" => $goodsArray,"product" => $productArray)));
+    	echo JSON::encode($countSumResult);
+    }
+
+    //填写订单信息cart2
+    function cart2()
+    {
+		header("Cache-Control: no-store, no-cache, must-revalidate");
+		header("Cache-Control: post-check=0, pre-check=0",false);
+		$id        = IFilter::act(IReq::get('id'),'int');
+		$type      = IFilter::act(IReq::get('type'));//goods,product
+		$promo     = IFilter::act(IReq::get('promo'));
+		$active_id = IFilter::act(IReq::get('active_id'),'int');
+		$buy_num   = IReq::get('num') ? IFilter::act(IReq::get('num'),'int') : 1;
+		$tourist   = IReq::get('tourist');//游客方式购物
+
+    	//必须为登录用户
+    	if($tourist === null && $this->user['user_id'] == null)
+    	{
+    		if($id == 0 || $type == '')
+    		{
+    			$this->redirect('/simple/login?tourist&callback=/simple/cart2');
+    		}
+    		else
+    		{
+    			$url  = '/simple/login?tourist&callback=/simple/cart2/id/'.$id.'/type/'.$type.'/num/'.$buy_num;
+    			$url .= $promo     ? '/promo/'.$promo         : '';
+    			$url .= $active_id ? '/active_id/'.$active_id : '';
+    			$this->redirect($url);
+    		}
+    	}
+
+		//游客的user_id默认为0
+    	$user_id = ($this->user['user_id'] == null) ? 0 : $this->user['user_id'];
+
+		//计算商品
+		$countSumObj = new CountSum($user_id);
+		$result = $countSumObj->cart_count($id,$type,$buy_num,$promo,$active_id);
+
+		if($countSumObj->error)
+		{
+			IError::show(403,$countSumObj->error);
+		}
+
+    	//获取收货地址
+    	$addressObj  = new IModel('address');
+    	$addressList = $addressObj->query('user_id = '.$user_id,"*","is_default desc");
+
+		//更新$addressList数据
+    	foreach($addressList as $key => $val)
+    	{
+    		$temp = area::name($val['province'],$val['city'],$val['area']);
+    		if(isset($temp[$val['province']]) && isset($temp[$val['city']]) && isset($temp[$val['area']]))
+    		{
+	    		$addressList[$key]['province_val'] = $temp[$val['province']];
+	    		$addressList[$key]['city_val']     = $temp[$val['city']];
+	    		$addressList[$key]['area_val']     = $temp[$val['area']];
+    		}
+    	}
+
+		//获取习惯方式
+		$memberObj = new IModel('member');
+		$memberRow = $memberObj->getObj('user_id = '.$user_id,'custom');
+		if(isset($memberRow['custom']) && $memberRow['custom'])
+		{
+			$this->custom = unserialize($memberRow['custom']);
+		}
+		else
+		{
+			$this->custom = array(
+				'payment'  => '',
+				'delivery' => '',
+			);
+		}
+
+    	//返回值
+		$this->gid       = $id;
+		$this->type      = $type;
+		$this->num       = $buy_num;
+		$this->promo     = $promo;
+		$this->active_id = $active_id;
+    	$this->final_sum = $result['final_sum'];
+    	$this->promotion = $result['promotion'];
+    	$this->proReduce = $result['proReduce'];
+    	$this->sum       = $result['sum'];
+    	$this->goodsList = $result['goodsList'];
+    	$this->count       = $result['count'];
+    	$this->reduce      = $result['reduce'];
+    	$this->weight      = $result['weight'];
+    	$this->freeFreight = $result['freeFreight'];
+    	$this->seller      = $result['seller'];
+
+		//收货地址列表
+		$this->addressList = $addressList;
+
+		//获取商品税金
+		$this->goodsTax    = $result['tax'];
+
+    	//渲染页面
+    	$this->redirect('cart2');
+    }
+
+	/**
+	 * 生成订单
+	 */
+    function cart3()
+    {
+		//防止表单重复提交
+    	if(IReq::get('timeKey'))
+    	{
+    		if(ISafe::get('timeKey') == IReq::get('timeKey'))
+    		{
+	    		IError::show(403,'订单数据不能被重复提交');
+    		}
+    		ISafe::set('timeKey',IReq::get('timeKey'));
+    	}
+
+    	$address_id    = IFilter::act(IReq::get('radio_address'),'int');
+    	$delivery_id   = IFilter::act(IReq::get('delivery_id'),'int');
+    	$accept_time   = IFilter::act(IReq::get('accept_time'));
+    	$payment       = IFilter::act(IReq::get('payment'),'int');
+    	$order_message = IFilter::act(IReq::get('message'));
+    	$ticket_id     = IFilter::act(IReq::get('ticket_id'),'int');
+    	$taxes         = IFilter::act(IReq::get('taxes'),'float');
+    	$tax_title     = IFilter::act(IReq::get('tax_title'));
+    	$gid           = IFilter::act(IReq::get('direct_gid'),'int');
+    	$num           = IFilter::act(IReq::get('direct_num'),'int');
+    	$type          = IFilter::act(IReq::get('direct_type'));//商品或者货品
+    	$promo         = IFilter::act(IReq::get('direct_promo'));
+    	$active_id     = IFilter::act(IReq::get('direct_active_id'),'int');
+    	$takeself      = IFilter::act(IReq::get('takeself'),'int');
+    	$order_type    = 0;
+    	$dataArray     = array();
+    	$user_id       = ($this->user['user_id'] == null) ? 0 : $this->user['user_id'];
+
+		//获取商品数据信息
+    	$countSumObj = new CountSum($user_id);
+		$goodsResult = $countSumObj->cart_count($gid,$type,$num,$promo,$active_id);
+
+		if($countSumObj->error)
+		{
+			IError::show(403,$countSumObj->error);
+		}
+
+		//处理收件地址
+		//1,访客; 2,注册用户
+		if($user_id == 0)
+		{
+			$addressRow = ISafe::get('address');
+		}
+		else
+		{
+			$addressDB = new IModel('address');
+			$addressRow= $addressDB->getObj('id = '.$address_id.' and user_id = '.$user_id);
+		}
+
+		if(!$addressRow)
+		{
+			IError::show(403,"收货地址信息不存在");
+		}
+    	$accept_name   = IFilter::act($addressRow['accept_name'],'name');
+    	$province      = $addressRow['province'];
+    	$city          = $addressRow['city'];
+    	$area          = $addressRow['area'];
+    	$address       = IFilter::act($addressRow['address']);
+    	$mobile        = IFilter::act($addressRow['mobile'],'mobile');
+    	$telphone      = IFilter::act($addressRow['telphone'],'phone');
+    	$zip           = IFilter::act($addressRow['zip'],'zip');
+
+		//检查订单重复
+    	$checkData = array(
+    		"accept_name" => $accept_name,
+    		"address"     => $address,
+    		"mobile"      => $mobile,
+    		"distribution"=> $delivery_id,
+    	);
+    	$result = order_class::checkRepeat($checkData,$goodsResult['goodsList']);
+    	if( is_string($result) )
+    	{
+			IError::show(403,$result);
+    	}
+
+		//配送方式,判断是否为货到付款
+		$deliveryObj = new IModel('delivery');
+		$deliveryRow = $deliveryObj->getObj('id = '.$delivery_id);
+		if(!$deliveryRow)
+		{
+			IError::show(403,'配送方式不存在');
+		}
+
+		if($deliveryRow['type'] == 0)
+		{
+			if($payment == 0)
+			{
+				IError::show(403,'请选择正确的支付方式');
+			}
+		}
+		else if($deliveryRow['type'] == 1)
+		{
+			$payment = 0;
+		}
+		else if($deliveryRow['type'] == 2)
+		{
+			if($takeself == 0)
+			{
+				IError::show(403,'请选择正确的自提点');
+			}
+		}
+		//如果不是自提方式自动清空自提点
+		if($deliveryRow['type'] != 2)
+		{
+			$takeself = 0;
+		}
+
+		if(!$gid)
+		{
+			//清空购物车
+			IInterceptor::reg("cart@onFinishAction");
+		}
+
+    	//判断商品是否存在
+    	if(is_string($goodsResult) || empty($goodsResult['goodsList']))
+    	{
+    		IError::show(403,'商品数据错误');
+    	}
+
+    	//加入促销活动
+    	if($promo && $active_id)
+    	{
+    		$activeObject = new Active($promo,$active_id,$user_id,$gid,$type,$num);
+    		$order_type = $activeObject->getOrderType();
+    	}
+
+		$paymentObj = new IModel('payment');
+		$paymentRow = $paymentObj->getObj('id = '.$payment,'type,name');
+		if(!$paymentRow)
+		{
+			IError::show(403,'支付方式不存在');
+		}
+		$paymentName= $paymentRow['name'];
+		$paymentType= $paymentRow['type'];
+
+		//最终订单金额计算
+		$orderData = $countSumObj->countOrderFee($goodsResult,$province,$delivery_id,$payment,$taxes,0,$promo,$active_id);
+		if(is_string($orderData))
+		{
+			IError::show(403,$orderData);
+		}
+
+		//根据商品所属商家不同批量生成订单
+		$orderIdArray  = array();
+		$orderNumArray = array();
+		$final_sum     = 0;
+		foreach($orderData as $seller_id => $goodsResult)
+		{
+			//生成的订单数据
+			$dataArray = array(
+				'order_no'            => Order_Class::createOrderNum(),
+				'user_id'             => $user_id,
+				'accept_name'         => $accept_name,
+				'pay_type'            => $payment,
+				'distribution'        => $delivery_id,
+				'postcode'            => $zip,
+				'telphone'            => $telphone,
+				'province'            => $province,
+				'city'                => $city,
+				'area'                => $area,
+				'address'             => $address,
+				'mobile'              => $mobile,
+				'create_time'         => ITime::getDateTime(),
+				'postscript'          => $order_message,
+				'accept_time'         => $accept_time,
+				'exp'                 => $goodsResult['exp'],
+				'point'               => $goodsResult['point'],
+				'type'                => $order_type,
+
+				//商品价格
+				'payable_amount'      => $goodsResult['sum'],
+				'real_amount'         => $goodsResult['final_sum'],
+
+				//运费价格
+				'payable_freight'     => $goodsResult['deliveryOrigPrice'],
+				'real_freight'        => $goodsResult['deliveryPrice'],
+
+				//手续费
+				'pay_fee'             => $goodsResult['paymentPrice'],
+
+				//税金
+				'invoice'             => $tax_title ? 1 : 0,
+				'invoice_title'       => $tax_title,
+				'taxes'               => $goodsResult['taxPrice'],
+
+				//优惠价格
+				'promotions'          => $goodsResult['proReduce'] + $goodsResult['reduce'],
+
+				//订单应付总额
+				'order_amount'        => $goodsResult['orderAmountPrice'],
+
+				//订单保价
+				'insured'             => $goodsResult['insuredPrice'],
+
+				//自提点ID
+				'takeself'            => $takeself,
+
+				//促销活动ID
+				'active_id'           => $active_id,
+
+				//商家ID
+				'seller_id'           => $seller_id,
+
+				//备注信息
+				'note'                => '',
+
+				//奖励性促销规则IDS
+				'prorule_ids'         => $goodsResult['giftIds'],
+			);
+
+			//获取红包减免金额
+			if($ticket_id)
+			{
+				$memberObj = new IModel('member');
+				$memberRow = $memberObj->getObj('user_id = '.$user_id,'prop,custom');
+				foreach($ticket_id as $tk => $tid)
+				{
+					//游客手动添加或注册用户道具中已有的代金券
+					if(ISafe::get('ticket_'.$tid) == $tid || stripos(','.trim($memberRow['prop'],',').',',','.$tid.',') !== false)
+					{
+						$propObj   = new IModel('prop');
+						$ticketRow = $propObj->getObj('id = '.$tid.' and NOW() between start_time and end_time and type = 0 and is_close = 0 and is_userd = 0 and is_send = 1');
+						if(!$ticketRow)
+						{
+							IError::show(403,'代金券不可用');
+						}
+
+						if($ticketRow['seller_id'] == 0 || $ticketRow['seller_id'] == $seller_id)
+						{
+							$ticketRow['value']         = $ticketRow['value'] >= $goodsResult['final_sum'] ? $goodsResult['final_sum'] : $ticketRow['value'];
+							$dataArray['prop']          = $tid;
+							$dataArray['promotions']   += $ticketRow['value'];
+							$dataArray['order_amount'] -= $ticketRow['value'];
+							$goodsResult['promotion'][] = array("plan" => "代金券","info" => "使用了¥".$ticketRow['value']."代金券");
+
+							//锁定红包状态
+							$propObj->setData(array('is_close' => 2));
+							$propObj->update('id = '.$tid);
+
+							unset($ticket_id[$tk]);
+							break;
+						}
+					}
+				}
+			}
+
+			//促销规则
+			if(isset($goodsResult['promotion']) && $goodsResult['promotion'])
+			{
+				foreach($goodsResult['promotion'] as $key => $val)
+				{
+					$dataArray['note'] .= join(",",$val)."。";
+				}
+			}
+
+			$dataArray['order_amount'] = $dataArray['order_amount'] <= 0 ? 0 : $dataArray['order_amount'];
+
+			//生成订单插入order表中
+			$orderObj  = new IModel('order');
+			$orderObj->setData($dataArray);
+			$order_id = $orderObj->add();
+
+			if($order_id == false)
+			{
+				IError::show(403,'订单生成错误');
+			}
+
+			/*将订单中的商品插入到order_goods表*/
+	    	$orderInstance = new Order_Class();
+	    	$orderGoodsResult = $orderInstance->insertOrderGoods($order_id,$goodsResult['goodsResult']);
+	    	if($orderGoodsResult !== true)
+	    	{
+	    		IError::show(403,$orderGoodsResult);
+	    	}
+
+			//订单金额小于等于0直接免单
+			if($dataArray['order_amount'] <= 0)
+			{
+				Order_Class::updateOrderStatus($dataArray['order_no']);
+			}
+			else
+			{
+				$orderIdArray[]  = $order_id;
+				$orderNumArray[] = $dataArray['order_no'];
+				$final_sum      += $dataArray['order_amount'];
+			}
+		}
+
+		//记录用户默认习惯的数据
+		if(!isset($memberRow['custom']))
+		{
+			$memberObj = new IModel('member');
+			$memberRow = $memberObj->getObj('user_id = '.$user_id,'custom');
+		}
+
+		$memberData = array(
+			'custom' => serialize(
+				array(
+					'payment'  => $payment,
+					'delivery' => $delivery_id,
+				)
+			),
+		);
+		$memberObj->setData($memberData);
+		$memberObj->update('user_id = '.$user_id);
+
+		//收货地址的处理
+		if($user_id)
+		{
+			$addressDefRow = $addressDB->getObj('user_id = '.$user_id.' and is_default = 1');
+			if(!$addressDefRow)
+			{
+				$addressDB->setData(array('is_default' => 1));
+				$addressDB->update('user_id = '.$user_id.' and id = '.$address_id);
+			}
+		}
+
+		//获取备货时间
+		$this->stockup_time = $this->_siteConfig->stockup_time ? $this->_siteConfig->stockup_time : 2;
+
+		//数据渲染
+		$this->order_id    = join("_",$orderIdArray);
+		$this->final_sum   = $final_sum;
+		$this->order_num   = join(" ",$orderNumArray);
+		$this->payment     = $paymentName;
+		$this->paymentType = $paymentType;
+		$this->delivery    = $deliveryRow['name'];
+		$this->tax_title   = $tax_title;
+		$this->deliveryType= $deliveryRow['type'];
+		plugin::trigger('setCallback','/ucenter/order');
+		//订单金额为0时,订单自动完成
+		if($this->final_sum <= 0)
+		{
+			$this->redirect('/site/success/message/'.urlencode("订单确认成功,等待发货"));
+		}
+		else
+		{
+			$this->setRenderData($dataArray);
+			$this->redirect('cart3');
+		}
+    }
+
+    //到货通知处理动作
+	function arrival_notice()
+	{
+		$user_id  = $this->user['user_id'];
+		$email    = IFilter::act(IReq::get('email'));
+		$mobile   = IFilter::act(IReq::get('mobile'));
+		$goods_id = IFilter::act(IReq::get('goods_id'),'int');
+		$register_time = ITime::getDateTime();
+
+		if(!$goods_id)
+		{
+			IError::show(403,'商品ID不存在');
+		}
+
+		$model = new IModel('notify_registry');
+		$obj = $model->getObj("email = '{$email}' and user_id = '{$user_id}' and goods_id = '$goods_id'");
+		if(empty($obj))
+		{
+			$model->setData(array('email'=>$email,'user_id'=>$user_id,'mobile'=>$mobile,'goods_id'=>$goods_id,'register_time'=>$register_time));
+			$model->add();
+		}
+		else
+		{
+			$model->setData(array('email'=>$email,'user_id'=>$user_id,'mobile'=>$mobile,'goods_id'=>$goods_id,'register_time'=>$register_time,'notify_status'=>0));
+			$model->update('id = '.$obj['id']);
+		}
+		$this->redirect('/site/success',true);
+	}
+
+	/**
+	 * @brief 邮箱找回密码进行
+	 */
+    function find_password_email()
+	{
+		$username = IReq::get('username');
+		if($username === null || !IValidate::name($username)  )
+		{
+			IError::show(403,"请输入正确的用户名");
+		}
+
+		$email = IReq::get("email");
+		if($email === null || !IValidate::email($email ))
+		{
+			IError::show(403,"请输入正确的邮箱地址");
+		}
+
+		$tb_user  = new IModel("user as u,member as m");
+		$username = IFilter::act($username);
+		$email    = IFilter::act($email);
+		$user     = $tb_user->getObj(" u.id = m.user_id and u.username='{$username}' AND m.email='{$email}' ");
+		if(!$user)
+		{
+			IError::show(403,"对不起,用户不存在");
+		}
+		$hash = IHash::md5( microtime(true) .mt_rand());
+
+		//重新找回密码的数据
+		$tb_find_password = new IModel("find_password");
+		$tb_find_password->setData( array( 'hash' => $hash ,'user_id' => $user['id'] , 'addtime' => time() ) );
+
+		if($tb_find_password->query("`hash` = '{$hash}'") || $tb_find_password->add())
+		{
+			$url     = IUrl::getHost().IUrl::creatUrl("/simple/restore_password/hash/{$hash}/user_id/".$user['id']);
+			$content = mailTemplate::findPassword(array("{url}" => $url));
+
+			$smtp   = new SendMail();
+			$result = $smtp->send($user['email'],"您的密码找回",$content);
+
+			if($result===false)
+			{
+				IError::show(403,"发信失败,请重试!或者联系管理员查看邮件服务是否开启");
+			}
+		}
+		else
+		{
+			IError::show(403,"生成HASH重复,请重试");
+		}
+		$message = "恭喜您,密码重置邮件已经发送!请到您的邮箱中去激活";
+		$this->redirect("/site/success/message/".urlencode($message));
+	}
+
+	//手机短信找回密码
+	function find_password_mobile()
+	{
+		$username = IReq::get('username');
+		if($username === null || !IValidate::name($username))
+		{
+			IError::show(403,"请输入正确的用户名");
+		}
+
+		$mobile = IReq::get("mobile");
+		if($mobile === null || !IValidate::mobi($mobile))
+		{
+			IError::show(403,"请输入正确的电话号码");
+		}
+
+		$mobile_code = IFilter::act(IReq::get('mobile_code'));
+		if($mobile_code === null)
+		{
+			IError::show(403,"请输入短信校验码");
+		}
+
+		$userDB = new IModel('user as u , member as m');
+		$userRow = $userDB->getObj('u.username = "'.$username.'" and m.mobile = "'.$mobile.'" and u.id = m.user_id');
+		if($userRow)
+		{
+			$findPasswordDB = new IModel('find_password');
+			$dataRow = $findPasswordDB->getObj('user_id = '.$userRow['user_id'].' and hash = "'.$mobile_code.'"');
+			if($dataRow)
+			{
+				//短信验证码已经过期
+				if(time() - $dataRow['addtime'] > 3600)
+				{
+					$findPasswordDB->del("user_id = ".$userRow['user_id']);
+					IError::show(403,"您的短信校验码已经过期了,请重新找回密码");
+				}
+				else
+				{
+					$this->redirect('/simple/restore_password/hash/'.$mobile_code.'/user_id/'.$userRow['user_id']);
+				}
+			}
+			else
+			{
+				IError::show(403,"您输入的短信校验码错误");
+			}
+		}
+		else
+		{
+			IError::show(403,"用户名与手机号码不匹配");
+		}
+	}
+
+	//找回密码发送手机验证码短信
+	function send_message_mobile()
+	{
+		$username = IFilter::act(IReq::get('username'));
+		$mobile = IFilter::act(IReq::get('mobile'));
+
+		if($username === null || !IValidate::name($username))
+		{
+			die("请输入正确的用户名");
+		}
+
+		if($mobile === null || !IValidate::mobi($mobile))
+		{
+			die("请输入正确的手机号码");
+		}
+
+		$userDB = new IModel('user as u , member as m');
+		$userRow = $userDB->getObj('u.username = "'.$username.'" and m.mobile = "'.$mobile.'" and u.id = m.user_id');
+
+		if($userRow)
+		{
+			$findPasswordDB = new IModel('find_password');
+			$dataRow = $findPasswordDB->query('user_id = '.$userRow['user_id'],'*','addtime desc');
+			$dataRow = current($dataRow);
+
+			//120秒是短信发送的间隔
+			if( isset($dataRow['addtime']) && (time() - $dataRow['addtime'] <= 120) )
+			{
+				die("申请验证码的时间间隔过短,请稍候再试");
+			}
+			$mobile_code = rand(10000,99999);
+			$findPasswordDB->setData(array(
+				'user_id' => $userRow['user_id'],
+				'hash'    => $mobile_code,
+				'addtime' => time(),
+			));
+			if($findPasswordDB->add())
+			{
+				$content = smsTemplate::findPassword(array('{mobile_code}' => $mobile_code));
+				$result = Hsms::send($mobile,$content);
+				if($result == 'success')
+				{
+					die('success');
+				}
+				die($result);
+			}
+		}
+		else
+		{
+			die('手机号码与用户名不符合');
+		}
+	}
+
+	/**
+	 * @brief 重置密码验证
+	 */
+	function restore_password()
+	{
+		$hash = IFilter::act(IReq::get("hash"));
+		$user_id = IFilter::act(IReq::get("user_id"),'int');
+
+		if(!$hash)
+		{
+			IError::show(403,"找不到校验码");
+		}
+		$tb = new IModel("find_password");
+		$addtime = time() - 3600*72;
+		$where  = " `hash`='$hash' AND addtime > $addtime ";
+		$where .= $this->user['user_id'] ? " and user_id = ".$this->user['user_id'] : "";
+
+		$row = $tb->getObj($where);
+		if(!$row)
+		{
+			IError::show(403,"校验码已经超时");
+		}
+
+		if($row['user_id'] != $user_id)
+		{
+			IError::show(403,"验证码不属于此用户");
+		}
+
+		$this->formAction = IUrl::creatUrl("/simple/do_restore_password/hash/$hash/user_id/".$user_id);
+		$this->redirect("restore_password");
+	}
+
+	/**
+	 * @brief 执行密码修改重置操作
+	 */
+	function do_restore_password()
+	{
+		$hash = IFilter::act(IReq::get("hash"));
+		$user_id = IFilter::act(IReq::get("user_id"),'int');
+
+		if(!$hash)
+		{
+			IError::show(403,"找不到校验码");
+		}
+		$tb = new IModel("find_password");
+		$addtime = time() - 3600*72;
+		$where  = " `hash`='$hash' AND addtime > $addtime ";
+		$where .= $this->user['user_id'] ? " and user_id = ".$this->user['user_id'] : "";
+
+		$row = $tb->getObj($where);
+		if(!$row)
+		{
+			IError::show(403,"校验码已经超时");
+		}
+
+		if($row['user_id'] != $user_id)
+		{
+			IError::show(403,"验证码不属于此用户");
+		}
+
+		//开始修改密码
+		$pwd   = IReq::get("password");
+		$repwd = IReq::get("repassword");
+		if($pwd == null || strlen($pwd) < 6 || $repwd!=$pwd)
+		{
+			IError::show(403,"新密码至少六位,且两次输入的密码应该一致。");
+		}
+		$pwd = md5($pwd);
+		$tb_user = new IModel("user");
+		$tb_user->setData(array("password" => $pwd));
+		$re = $tb_user->update("id='{$row['user_id']}'");
+		if($re !== false)
+		{
+			$message = "修改密码成功";
+			$tb->del("`hash`='{$hash}'");
+			$this->redirect("/site/success/message/".urlencode($message));
+			return;
+		}
+		IError::show(403,"密码修改失败,请重试");
+	}
+
+    //添加收藏夹
+    function favorite_add()
+    {
+    	$goods_id = IFilter::act(IReq::get('goods_id'),'int');
+    	$message  = '';
+
+    	if($goods_id == 0)
+    	{
+    		$message = '商品id值不能为空';
+    	}
+    	else if(!isset($this->user['user_id']) || !$this->user['user_id'])
+    	{
+    		$message = '请先登录';
+    	}
+    	else
+    	{
+    		$favoriteObj = new IModel('favorite');
+    		$goodsRow    = $favoriteObj->getObj('user_id = '.$this->user['user_id'].' and rid = '.$goods_id);
+    		if($goodsRow)
+    		{
+    			$message = '您已经收藏过此件商品';
+    		}
+    		else
+    		{
+    			$catObj = new IModel('category_extend');
+    			$catRow = $catObj->getObj('goods_id = '.$goods_id);
+    			$cat_id = $catRow ? $catRow['category_id'] : 0;
+
+	    		$dataArray   = array(
+	    			'user_id' => $this->user['user_id'],
+	    			'rid'     => $goods_id,
+	    			'time'    => ITime::getDateTime(),
+	    			'cat_id'  => $cat_id,
+	    		);
+	    		$favoriteObj->setData($dataArray);
+	    		$favoriteObj->add();
+	    		$message = '收藏成功';
+
+	    		//商品收藏信息更新
+	    		$goodsDB = new IModel('goods');
+	    		$goodsDB->setData(array("favorite" => "favorite + 1"));
+	    		$goodsDB->update("id = ".$goods_id,'favorite');
+    		}
+    	}
+		$result = array(
+			'isError' => true,
+			'message' => $message,
+		);
+
+    	echo JSON::encode($result);
+    }
+
+    //获取oauth登录地址
+    public function oauth_login()
+    {
+    	$id = IFilter::act(IReq::get('id'),'int');
+    	if($id)
+    	{
+    		$oauthObj = new OauthCore($id);
+			$result   = array(
+				'isError' => false,
+				'url'     => $oauthObj->getLoginUrl(),
+			);
+    	}
+    	else
+    	{
+			$result   = array(
+				'isError' => true,
+				'message' => '请选择要登录的平台',
+			);
+    	}
+    	echo JSON::encode($result);
+    }
+
+    //第三方登录回调
+    public function oauth_callback()
+    {
+    	$oauth_name = IFilter::act(IReq::get('oauth_name'));
+    	$oauthObj   = new IModel('oauth');
+    	$oauthRow   = $oauthObj->getObj('file = "'.$oauth_name.'"');
+
+    	if(!$oauth_name && !$oauthRow)
+    	{
+    		IError::show(403,"{$oauth_name} 第三方平台信息不存在");
+    	}
+		$id       = $oauthRow['id'];
+    	$oauthObj = new OauthCore($id);
+    	$result   = $oauthObj->checkStatus($_GET);
+
+    	if($result === true)
+    	{
+    		$oauthObj->getAccessToken($_GET);
+	    	$userInfo = $oauthObj->getUserInfo();
+
+	    	if(isset($userInfo['id']) && isset($userInfo['name']) && $userInfo['id'] && $userInfo['name'])
+	    	{
+	    		$this->bindUser($userInfo,$id);
+	    		return;
+	    	}
+    	}
+    	else
+    	{
+    		IError::show("回调URL参数错误");
+    	}
+    }
+
+    //同步绑定用户数据
+    public function bindUser($userInfo,$oauthId)
+    {
+    	$userObj      = new IModel('user');
+    	$oauthUserObj = new IModel('oauth_user');
+    	$oauthUserRow = $oauthUserObj->getObj("oauth_user_id = '{$userInfo['id']}' and oauth_id = '{$oauthId}' ",'user_id');
+		if($oauthUserRow)
+		{
+			//清理oauth_user和user表不同步匹配的问题
+			$tempRow = $userObj->getObj("id = '{$oauthUserRow['user_id']}'");
+			if(!$tempRow)
+			{
+				$oauthUserObj->del("oauth_user_id = '{$userInfo['id']}' and oauth_id = '{$oauthId}' ");
+			}
+		}
+
+    	//存在绑定账号oauth_user与user表同步正常!
+    	if(isset($tempRow) && $tempRow)
+    	{
+    		$userRow = plugin::trigger("isValidUser",array($tempRow['username'],$tempRow['password']));
+    		plugin::trigger("userLoginCallback",$userRow);
+    		$callback = plugin::trigger('getCallback');
+    		$callback = $callback ? $callback : "/ucenter/index";
+			$this->redirect($callback);
+    	}
+    	//没有绑定账号
+    	else
+    	{
+	    	$userCount = $userObj->getObj("username = '{$userInfo['name']}'",'count(*) as num');
+
+	    	//没有重复的用户名
+	    	if($userCount['num'] == 0)
+	    	{
+	    		$username = $userInfo['name'];
+	    	}
+	    	else
+	    	{
+	    		//随即分配一个用户名
+	    		$username = $userInfo['name'].$userCount['num'];
+	    	}
+			$userInfo['name'] = $username;
+	    	ISession::set('oauth_id',$oauthId);
+	    	ISession::set('oauth_userInfo',$userInfo);
+	    	$this->setRenderData($userInfo);
+	    	$this->redirect('bind_user',false);
+    	}
+    }
+
+	//执行绑定已存在用户
+    public function bind_exists_user()
+    {
+    	$login_info     = IReq::get('login_info');
+    	$password       = IReq::get('password');
+    	$oauth_id       = IFilter::act(ISession::get('oauth_id'));
+    	$oauth_userInfo = IFilter::act(ISession::get('oauth_userInfo'));
+
+    	if(!$oauth_id || !$oauth_userInfo || !isset($oauth_userInfo['id']))
+    	{
+    		IError::show("缺少oauth信息");
+    	}
+
+    	if($userRow = plugin::trigger("isValidUser",array($login_info,md5($password))))
+    	{
+    		$oauthUserObj = new IModel('oauth_user');
+
+    		//插入关系表
+    		$oauthUserData = array(
+    			'oauth_user_id' => $oauth_userInfo['id'],
+    			'oauth_id'      => $oauth_id,
+    			'user_id'       => $userRow['user_id'],
+    			'datetime'      => ITime::getDateTime(),
+    		);
+    		$oauthUserObj->setData($oauthUserData);
+    		$oauthUserObj->add();
+
+    		plugin::trigger("userLoginCallback",$userRow);
+
+			//自定义跳转页面
+			$this->redirect('/site/success?message='.urlencode("登录成功!"));
+    	}
+    	else
+    	{
+    		$this->setError("用户名和密码不匹配");
+    		$_GET['bind_type'] = 'exists';
+    		$this->redirect('bind_user',false);
+    		Util::showMessage("用户名和密码不匹配");
+    	}
+    }
+
+	//执行绑定注册新用户用户
+    public function bind_not_exists_user()
+    {
+    	$oauth_id       = IFilter::act(ISession::get('oauth_id'));
+    	$oauth_userInfo = IFilter::act(ISession::get('oauth_userInfo'));
+
+    	if(!$oauth_id || !$oauth_userInfo || !isset($oauth_userInfo['id']))
+    	{
+    		IError::show("缺少oauth信息");
+    	}
+
+    	//调用_userInfo注册插件
+		$result = plugin::trigger('userRegAct');
+		if(is_array($result))
+		{
+			//插入关系表
+			$oauthUserObj = new IModel('oauth_user');
+			$oauthUserData = array(
+				'oauth_user_id' => $oauth_userInfo['id'],
+				'oauth_id'      => $oauth_id,
+				'user_id'       => $result['id'],
+				'datetime'      => ITime::getDateTime(),
+			);
+			$oauthUserObj->setData($oauthUserData);
+			$oauthUserObj->add();
+			$this->redirect('/site/success?message='.urlencode("注册成功!"));
+		}
+		else
+		{
+    		$this->setError($result);
+    		$this->redirect('bind_user',false);
+    		Util::showMessage($result);
+		}
+    }
+
+	/**
+	 * @brief 商户的增加动作
+	 */
+	public function seller_reg()
+	{
+		$seller_name = IValidate::name(IReq::get('seller_name')) ? IReq::get('seller_name') : "";
+		$email       = IValidate::email(IReq::get('email'))      ? IReq::get('email')       : "";
+		$truename    = IValidate::name(IReq::get('true_name'))   ? IReq::get('true_name')   : "";
+		$phone       = IValidate::phone(IReq::get('phone'))      ? IReq::get('phone')       : "";
+		$mobile      = IValidate::mobi(IReq::get('mobile'))      ? IReq::get('mobile')      : "";
+		$home_url    = IValidate::url(IReq::get('home_url'))     ? IReq::get('home_url')    : "";
+
+		$password    = IFilter::act(IReq::get('password'));
+		$repassword  = IFilter::act(IReq::get('repassword'));
+		$province    = IFilter::act(IReq::get('province'),'int');
+		$city        = IFilter::act(IReq::get('city'),'int');
+		$area        = IFilter::act(IReq::get('area'),'int');
+		$address     = IFilter::act(IReq::get('address'));
+
+		if($password == '')
+		{
+			$errorMsg = '请输入密码!';
+		}
+
+		if($password != $repassword)
+		{
+			$errorMsg = '两次输入的密码不一致!';
+		}
+
+		if(!$seller_name)
+		{
+			$errorMsg = '填写正确的登陆用户名';
+		}
+
+		if(!$truename)
+		{
+			$errorMsg = '填写正确的商户真实全称';
+		}
+
+		//创建商家操作类
+		$sellerDB = new IModel("seller");
+		if($seller_name && $sellerDB->getObj("seller_name = '{$seller_name}'"))
+		{
+			$errorMsg = "登录用户名重复";
+		}
+		else if($truename && $sellerDB->getObj("true_name = '{$truename}'"))
+		{
+			$errorMsg = "商户真实全称重复";
+		}
+
+		//操作失败表单回填
+		if(isset($errorMsg))
+		{
+			$this->sellerRow = IFilter::act($_POST,'text');
+			$this->redirect('seller',false);
+			Util::showMessage($errorMsg);
+		}
+
+		//待更新的数据
+		$sellerRow = array(
+			'true_name' => $truename,
+			'phone'     => $phone,
+			'mobile'    => $mobile,
+			'email'     => $email,
+			'address'   => $address,
+			'province'  => $province,
+			'city'      => $city,
+			'area'      => $area,
+			'home_url'  => $home_url,
+			'is_lock'   => 1,
+		);
+
+		//商户资质上传
+		if(isset($_FILES['paper_img']['name']) && $_FILES['paper_img']['name'])
+		{
+			$uploadObj = new PhotoUpload();
+			$uploadObj->setIterance(false);
+			$photoInfo = $uploadObj->run();
+			if(isset($photoInfo['paper_img']['img']) && file_exists($photoInfo['paper_img']['img']))
+			{
+				$sellerRow['paper_img'] = $photoInfo['paper_img']['img'];
+			}
+		}
+
+		$sellerRow['seller_name'] = $seller_name;
+		$sellerRow['password']    = md5($password);
+		$sellerRow['create_time'] = ITime::getDateTime();
+
+		$sellerDB->setData($sellerRow);
+		$sellerDB->add();
+
+		//短信通知商城平台
+		if($this->_siteConfig->mobile)
+		{
+			$content = smsTemplate::sellerReg(array('{true_name}' => $truename));
+			$result = Hsms::send($this->_siteConfig->mobile,$content,0);
+		}
+
+		$this->redirect('/site/success?message='.urlencode("申请成功!请耐心等待管理员的审核"));
+	}
+
+	//添加地址ajax
+	function address_add()
+	{
+		$id          = IFilter::act(IReq::get('id'),'int');
+		$accept_name = IFilter::act(IReq::get('accept_name'),'name');
+		$province    = IFilter::act(IReq::get('province'),'int');
+		$city        = IFilter::act(IReq::get('city'),'int');
+		$area        = IFilter::act(IReq::get('area'),'int');
+		$address     = IFilter::act(IReq::get('address'));
+		$zip         = IFilter::act(IReq::get('zip'));
+		$telphone    = IFilter::act(IReq::get('telphone'));
+		$mobile      = IFilter::act(IReq::get('mobile'));
+        $user_id     = $this->user['user_id'];
+
+		//整合的数据
+        $sqlData = array(
+        	'user_id'     => $user_id,
+        	'accept_name' => $accept_name,
+        	'zip'         => $zip,
+        	'telphone'    => $telphone,
+        	'province'    => $province,
+        	'city'        => $city,
+        	'area'        => $area,
+        	'address'     => $address,
+        	'mobile'      => $mobile,
+        );
+
+        $checkArray = $sqlData;
+        unset($checkArray['telphone'],$checkArray['zip'],$checkArray['user_id']);
+        foreach($checkArray as $key => $val)
+        {
+        	if(!$val)
+        	{
+        		$result = array('result' => false,'msg' => '请完整填写收件信息');
+				die(JSON::encode($result));
+        	}
+        }
+
+        if($user_id)
+        {
+        	$model = new IModel('address');
+        	$model->setData($sqlData);
+        	if($id)
+        	{
+        		$model->update("id = ".$id." and user_id = ".$user_id);
+        	}
+        	else
+        	{
+        		$id = $model->add();
+        	}
+        	$sqlData['id'] = $id;
+        }
+        //访客地址保存
+        else
+        {
+        	ISafe::set("address",$sqlData);
+        }
+
+        $areaList = area::name($province,$city,$area);
+		$sqlData['province_val'] = $areaList[$province];
+		$sqlData['city_val']     = $areaList[$city];
+		$sqlData['area_val']     = $areaList[$area];
+		$result = array('data' => $sqlData);
+		die(JSON::encode($result));
+	}
+}

+ 837 - 0
src/controllers/site.php

@@ -0,0 +1,837 @@
+<?php
+/**
+ * @copyright Copyright(c) 2011 aircheng.com
+ * @file site.php
+ * @brief
+ * @author webning
+ * @date 2011-03-22
+ * @version 0.6
+ * @note
+ */
+/**
+ * @brief Site
+ * @class Site
+ * @note
+ */
+class Site extends IController
+{
+    public $layout='site';
+
+	function init()
+	{
+
+	}
+
+	function index()
+	{
+		$this->index_slide = Api::run('getBannerList');
+		$this->redirect('index');
+	}
+
+	//[首页]商品搜索
+	function search_list()
+	{
+		$this->word = IFilter::act(IReq::get('word'),'text');
+		$cat_id     = IFilter::act(IReq::get('cat'),'int');
+
+		if(preg_match("|^[\w\x7f\s*-\xff*]+$|",$this->word))
+		{
+			//搜索关键字
+			$tb_sear     = new IModel('search');
+			$search_info = $tb_sear->getObj('keyword = "'.$this->word.'"','id');
+
+			//如果是第一页,相应关键词的被搜索数量才加1
+			if($search_info && intval(IReq::get('page')) < 2 )
+			{
+				//禁止刷新+1
+				$allow_sep = "30";
+				$flag = false;
+				$time = ICookie::get('step');
+				if(isset($time))
+				{
+					if (time() - $time > $allow_sep)
+					{
+						ICookie::set('step',time());
+						$flag = true;
+					}
+				}
+				else
+				{
+					ICookie::set('step',time());
+					$flag = true;
+				}
+				if($flag)
+				{
+					$tb_sear->setData(array('num'=>'num + 1'));
+					$tb_sear->update('id='.$search_info['id'],'num');
+				}
+			}
+			elseif( !$search_info )
+			{
+				//如果数据库中没有这个词的信息,则新添
+				$tb_sear->setData(array('keyword'=>$this->word,'num'=>1));
+				$tb_sear->add();
+			}
+		}
+		else
+		{
+			IError::show(403,'请输入正确的查询关键词');
+		}
+		$this->cat_id = $cat_id;
+		$this->redirect('search_list');
+	}
+
+	//[site,ucenter头部分]自动完成
+	function autoComplete()
+	{
+		$word = IFilter::act(IReq::get('word'));
+		$isError = true;
+		$data    = array();
+
+		if($word != '' && $word != '%' && $word != '_')
+		{
+			$wordObj  = new IModel('keyword');
+			$wordList = $wordObj->query('word like "'.$word.'%" and word != "'.$word.'"','word, goods_nums','',10);
+
+			if(!empty($wordList))
+			{
+				$isError = false;
+				$data = $wordList;
+			}
+		}
+
+		//json数据
+		$result = array(
+			'isError' => $isError,
+			'data'    => $data,
+		);
+
+		echo JSON::encode($result);
+	}
+
+	//[首页]邮箱订阅
+	function email_registry()
+	{
+		$email  = IReq::get('email');
+		$result = array('isError' => true);
+
+		if(!IValidate::email($email))
+		{
+			$result['message'] = '请填写正确的email地址';
+		}
+		else
+		{
+			$emailRegObj = new IModel('email_registry');
+			$emailRow    = $emailRegObj->getObj('email = "'.$email.'"');
+
+			if(!empty($emailRow))
+			{
+				$result['message'] = '此email已经订阅过了';
+			}
+			else
+			{
+				$dataArray = array(
+					'email' => $email,
+				);
+				$emailRegObj->setData($dataArray);
+				$status = $emailRegObj->add();
+				if($status == true)
+				{
+					$result = array(
+						'isError' => false,
+						'message' => '订阅成功',
+					);
+				}
+				else
+				{
+					$result['message'] = '订阅失败';
+				}
+			}
+		}
+		echo JSON::encode($result);
+	}
+
+	//[列表页]商品
+	function pro_list()
+	{
+		$this->catId = IFilter::act(IReq::get('cat'),'int');//分类id
+
+		if($this->catId == 0)
+		{
+			IError::show(403,'缺少分类ID');
+		}
+
+		//查找分类信息
+		$catObj       = new IModel('category');
+		$this->catRow = $catObj->getObj('id = '.$this->catId);
+
+		if($this->catRow == null)
+		{
+			IError::show(403,'此分类不存在');
+		}
+
+		//获取子分类
+		$this->childId = goods_class::catChild($this->catId);
+		$this->redirect('pro_list');
+	}
+	//咨询
+	function consult()
+	{
+		$this->goods_id = IFilter::act(IReq::get('id'),'int');
+		if($this->goods_id == 0)
+		{
+			IError::show(403,'缺少商品ID参数');
+		}
+
+		$goodsObj   = new IModel('goods');
+		$goodsRow   = $goodsObj->getObj('id = '.$this->goods_id);
+		if(!$goodsRow)
+		{
+			IError::show(403,'商品数据不存在');
+		}
+
+		//获取次商品的评论数和平均分
+		$goodsRow['apoint'] = $goodsRow['comments'] ? round($goodsRow['grade']/$goodsRow['comments']) : 0;
+
+		$this->goodsRow = $goodsRow;
+		$this->redirect('consult');
+	}
+
+	//咨询动作
+	function consult_act()
+	{
+		$goods_id   = IFilter::act(IReq::get('goods_id','post'),'int');
+		$captcha    = IFilter::act(IReq::get('captcha','post'));
+		$question   = IFilter::act(IReq::get('question','post'));
+		$_captcha   = ISafe::get('captcha');
+		$message    = '';
+
+    	if(!$captcha || !$_captcha || $captcha != $_captcha)
+    	{
+    		$message = '验证码输入不正确';
+    	}
+    	else if(!$question)
+    	{
+    		$message = '咨询内容不能为空';
+    	}
+    	else if(!$goods_id)
+    	{
+    		$message = '商品ID不能为空';
+    	}
+    	else
+    	{
+    		$goodsObj = new IModel('goods');
+    		$goodsRow = $goodsObj->getObj('id = '.$goods_id);
+    		if(!$goodsRow)
+    		{
+    			$message = '不存在此商品';
+    		}
+    	}
+
+		//有错误情况
+    	if($message)
+    	{
+    		IError::show(403,$message);
+    	}
+    	else
+    	{
+			$dataArray = array(
+				'question' => $question,
+				'goods_id' => $goods_id,
+				'user_id'  => isset($this->user['user_id']) ? $this->user['user_id'] : 0,
+				'time'     => ITime::getDateTime(),
+			);
+			$referObj = new IModel('refer');
+			$referObj->setData($dataArray);
+			$referObj->add();
+			plugin::trigger('setCallback','/site/products/id/'.$goods_id);
+			$this->redirect('/site/success');
+    	}
+	}
+
+	//公告详情页面
+	function notice_detail()
+	{
+		$this->notice_id = IFilter::act(IReq::get('id'),'int');
+		if($this->notice_id == '')
+		{
+			IError::show(403,'缺少公告ID参数');
+		}
+		else
+		{
+			$noObj           = new IModel('announcement');
+			$this->noticeRow = $noObj->getObj('id = '.$this->notice_id);
+			if(empty($this->noticeRow))
+			{
+				IError::show(403,'公告信息不存在');
+			}
+			$this->redirect('notice_detail');
+		}
+	}
+
+	//文章列表页面
+	function article()
+	{
+		$catId  = IFilter::act(IReq::get('id'),'int');
+		$catRow = Api::run('getArticleCategoryInfo',$catId);
+		$queryArticle = $catRow ? Api::run('getArticleListByCatid',$catRow['id']) : Api::run('getArticleList');
+		$this->setRenderData(array("catRow" => $catRow,'queryArticle' => $queryArticle));
+		$this->redirect('article');
+	}
+
+	//文章详情页面
+	function article_detail()
+	{
+		$this->article_id = IFilter::act(IReq::get('id'),'int');
+		if($this->article_id == '')
+		{
+			IError::show(403,'缺少咨询ID参数');
+		}
+		else
+		{
+			$articleObj       = new IModel('article');
+			$this->articleRow = $articleObj->getObj('id = '.$this->article_id);
+			if(empty($this->articleRow))
+			{
+				IError::show(403,'资讯文章不存在');
+				exit;
+			}
+
+			//关联商品
+			$this->relationList = Api::run('getArticleGoods',array("#article_id#",$this->article_id));
+			$this->redirect('article_detail');
+		}
+	}
+
+	//商品展示
+	function products()
+	{
+		$goods_id = IFilter::act(IReq::get('id'),'int');
+
+		if(!$goods_id)
+		{
+			IError::show(403,"传递的参数不正确");
+			exit;
+		}
+
+		//使用商品id获得商品信息
+		$tb_goods = new IModel('goods');
+		$goods_info = $tb_goods->getObj('id='.$goods_id." AND is_del=0");
+		if(!$goods_info)
+		{
+			IError::show(403,"这件商品不存在");
+			exit;
+		}
+
+		//品牌名称
+		if($goods_info['brand_id'])
+		{
+			$tb_brand = new IModel('brand');
+			$brand_info = $tb_brand->getObj('id='.$goods_info['brand_id']);
+			if($brand_info)
+			{
+				$goods_info['brand'] = $brand_info['name'];
+			}
+		}
+
+		//获取商品分类
+		$categoryObj = new IModel('category_extend as ca,category as c');
+		$categoryList= $categoryObj->query('ca.goods_id = '.$goods_id.' and ca.category_id = c.id','c.id,c.name','ca.id desc',1);
+		$categoryRow = null;
+		if($categoryList)
+		{
+			$categoryRow = current($categoryList);
+		}
+		$goods_info['category'] = $categoryRow ? $categoryRow['id'] : 0;
+
+		//商品图片
+		$tb_goods_photo = new IQuery('goods_photo_relation as g');
+		$tb_goods_photo->fields = 'p.id AS photo_id,p.img ';
+		$tb_goods_photo->join = 'left join goods_photo as p on p.id=g.photo_id ';
+		$tb_goods_photo->where =' g.goods_id='.$goods_id;
+		$tb_goods_photo->order =' g.id asc';
+		$goods_info['photo'] = $tb_goods_photo->find();
+
+		//商品是否参加促销活动(团购,抢购)
+		$goods_info['promo']     = IReq::get('promo')     ? IReq::get('promo') : '';
+		$goods_info['active_id'] = IReq::get('active_id') ? IFilter::act(IReq::get('active_id'),'int') : 0;
+		if($goods_info['promo'])
+		{
+			$activeObj    = new Active($goods_info['promo'],$goods_info['active_id'],$this->user['user_id'],$goods_id);
+			$activeResult = $activeObj->data();
+			if(is_string($activeResult))
+			{
+				IError::show(403,$activeResult);
+			}
+			else
+			{
+				$goods_info[$goods_info['promo']] = $activeResult;
+			}
+		}
+
+		//获得扩展属性
+		$tb_attribute_goods = new IQuery('goods_attribute as g');
+		$tb_attribute_goods->join  = 'left join attribute as a on a.id=g.attribute_id ';
+		$tb_attribute_goods->fields=' a.name,g.attribute_value ';
+		$tb_attribute_goods->where = "goods_id='".$goods_id."' and attribute_id!=''";
+		$goods_info['attribute'] = $tb_attribute_goods->find();
+
+		//购买记录
+		$tb_shop = new IQuery('order_goods as og');
+		$tb_shop->join = 'left join order as o on o.id=og.order_id';
+		$tb_shop->fields = 'count(*) as totalNum';
+		$tb_shop->where = 'og.goods_id='.$goods_id.' and o.status = 5';
+		$shop_info = $tb_shop->find();
+		$goods_info['buy_num'] = 0;
+		if($shop_info)
+		{
+			$goods_info['buy_num'] = $shop_info[0]['totalNum'];
+		}
+
+		//购买前咨询
+		$tb_refer    = new IModel('refer');
+		$refeer_info = $tb_refer->getObj('goods_id='.$goods_id,'count(*) as totalNum');
+		$goods_info['refer'] = 0;
+		if($refeer_info)
+		{
+			$goods_info['refer'] = $refeer_info['totalNum'];
+		}
+
+		//网友讨论
+		$tb_discussion = new IModel('discussion');
+		$discussion_info = $tb_discussion->getObj('goods_id='.$goods_id,'count(*) as totalNum');
+		$goods_info['discussion'] = 0;
+		if($discussion_info)
+		{
+			$goods_info['discussion'] = $discussion_info['totalNum'];
+		}
+
+		//获得商品的价格区间
+		$tb_product = new IModel('products');
+		$product_info = $tb_product->getObj('goods_id='.$goods_id,'max(sell_price) as maxSellPrice ,max(market_price) as maxMarketPrice');
+		if(isset($product_info['maxSellPrice']) && $goods_info['sell_price'] != $product_info['maxSellPrice'])
+		{
+			$goods_info['sell_price']   .= "-".$product_info['maxSellPrice'];
+		}
+
+		if(isset($product_info['maxMarketPrice']) && $goods_info['market_price'] != $product_info['maxMarketPrice'])
+		{
+			$goods_info['market_price'] .= "-".$product_info['maxMarketPrice'];
+		}
+
+		//获得会员价
+		$countsumInstance = new countsum();
+		$goods_info['group_price'] = $countsumInstance->groupPriceRange($goods_id);
+
+		//获取商家信息
+		if($goods_info['seller_id'])
+		{
+			$sellerDB = new IModel('seller');
+			$goods_info['seller'] = $sellerDB->getObj('id = '.$goods_info['seller_id']);
+		}
+
+		//增加浏览次数
+		$visit    = ISafe::get('visit');
+		$checkStr = "#".$goods_id."#";
+		if($visit && strpos($visit,$checkStr) !== false)
+		{
+		}
+		else
+		{
+			$tb_goods->setData(array('visit' => 'visit + 1'));
+			$tb_goods->update('id = '.$goods_id,'visit');
+			$visit = $visit === null ? $checkStr : $visit.$checkStr;
+			ISafe::set('visit',$visit);
+		}
+
+		//数据处理用于显示
+		$goods_info['weight'] = common::formatWeight($goods_info['weight']);
+
+		$this->setRenderData($goods_info);
+		$this->redirect('products');
+	}
+	//商品讨论更新
+	function discussUpdate()
+	{
+		$goods_id = IFilter::act(IReq::get('id'),'int');
+		$content  = IFilter::act(IReq::get('content'),'text');
+		$captcha  = IReq::get('captcha');
+		$_captcha = ISafe::get('captcha');
+		$return   = array('isError' => true , 'message' => '');
+
+		if(!$this->user['user_id'])
+		{
+			$return['message'] = '请先登录系统';
+		}
+    	else if(!$captcha || !$_captcha || $captcha != $_captcha)
+    	{
+    		$return['message'] = '验证码输入不正确';
+    	}
+    	else if(trim($content) == '')
+    	{
+    		$return['message'] = '内容不能为空';
+    	}
+    	else
+    	{
+    		$return['isError'] = false;
+
+			//插入讨论表
+			$tb_discussion = new IModel('discussion');
+			$dataArray     = array(
+				'goods_id' => $goods_id,
+				'user_id'  => $this->user['user_id'],
+				'time'     => ITime::getDateTime(),
+				'contents' => $content,
+			);
+			$tb_discussion->setData($dataArray);
+			$tb_discussion->add();
+
+			$return['time']     = $dataArray['time'];
+			$return['contents'] = $content;
+			$return['username'] = $this->user['username'];
+    	}
+    	echo JSON::encode($return);
+	}
+
+	//获取货品数据
+	function getProduct()
+	{
+		$goods_id = IFilter::act(IReq::get('goods_id'),'int');
+		$specJSON = IReq::get('specJSON');
+		if(!$specJSON || !is_array($specJSON))
+		{
+			echo JSON::encode(array('flag' => 'fail','message' => '规格值不符合标准'));
+			exit;
+		}
+
+		//获取货品数据
+		$tb_products = new IModel('products');
+		$procducts_info = $tb_products->getObj("goods_id = ".$goods_id." and spec_array = '".IFilter::act(htmlspecialchars_decode(JSON::encode($specJSON)))."'");
+
+		//匹配到货品数据
+		if(!$procducts_info)
+		{
+			echo JSON::encode(array('flag' => 'fail','message' => '没有找到相关货品'));
+			exit;
+		}
+
+		//获得会员价
+		$countsumInstance = new countsum();
+		$group_price = $countsumInstance->getGroupPrice($procducts_info['id'],'product');
+
+		//会员价格
+		if($group_price !== null)
+		{
+			$procducts_info['group_price'] = $group_price;
+		}
+
+		//处理数据内容
+		$procducts_info['weight'] = common::formatWeight($procducts_info['weight']);
+		echo JSON::encode(array('flag' => 'success','data' => $procducts_info));
+	}
+
+	//顾客评论ajax获取
+	function comment_ajax()
+	{
+		$goods_id = IFilter::act(IReq::get('goods_id'),'int');
+		$page     = IFilter::act(IReq::get('page'),'int') ? IReq::get('page') : 1;
+
+		$commentDB = new IQuery('comment as c');
+		$commentDB->join   = 'left join goods as go on c.goods_id = go.id AND go.is_del = 0 left join user as u on u.id = c.user_id';
+		$commentDB->fields = 'u.head_ico,u.username,c.*';
+		$commentDB->where  = 'c.goods_id = '.$goods_id.' and c.status = 1';
+		$commentDB->order  = 'c.id desc';
+		$commentDB->page   = $page;
+		$data     = $commentDB->find();
+		$pageHtml = $commentDB->getPageBar("javascript:void(0);",'onclick="comment_ajax([page])"');
+
+		echo JSON::encode(array('data' => $data,'pageHtml' => $pageHtml));
+	}
+
+	//购买记录ajax获取
+	function history_ajax()
+	{
+		$goods_id = IFilter::act(IReq::get('goods_id'),'int');
+		$page     = IFilter::act(IReq::get('page'),'int') ? IReq::get('page') : 1;
+
+		$orderGoodsDB = new IQuery('order_goods as og');
+		$orderGoodsDB->join   = 'left join order as o on og.order_id = o.id left join user as u on o.user_id = u.id';
+		$orderGoodsDB->fields = 'o.user_id,og.goods_price,og.goods_nums,o.create_time as completion_time,u.username';
+		$orderGoodsDB->where  = 'og.goods_id = '.$goods_id.' and o.status in (5,2)';
+		$orderGoodsDB->order  = 'o.create_time desc';
+		$orderGoodsDB->page   = $page;
+
+		$data = $orderGoodsDB->find();
+		$pageHtml = $orderGoodsDB->getPageBar("javascript:void(0);",'onclick="history_ajax([page])"');
+
+		echo JSON::encode(array('data' => $data,'pageHtml' => $pageHtml));
+	}
+
+	//讨论数据ajax获取
+	function discuss_ajax()
+	{
+		$goods_id = IFilter::act(IReq::get('goods_id'),'int');
+		$page     = IFilter::act(IReq::get('page'),'int') ? IReq::get('page') : 1;
+
+		$discussDB = new IQuery('discussion as d');
+		$discussDB->join = 'left join user as u on d.user_id = u.id';
+		$discussDB->where = 'd.goods_id = '.$goods_id;
+		$discussDB->order = 'd.id desc';
+		$discussDB->fields = 'u.username,d.time,d.contents';
+		$discussDB->page = $page;
+
+		$data = $discussDB->find();
+		$pageHtml = $discussDB->getPageBar("javascript:void(0);",'onclick="discuss_ajax([page])"');
+
+		echo JSON::encode(array('data' => $data,'pageHtml' => $pageHtml));
+	}
+
+	//买前咨询数据ajax获取
+	function refer_ajax()
+	{
+		$goods_id = IFilter::act(IReq::get('goods_id'),'int');
+		$page     = IFilter::act(IReq::get('page'),'int') ? IReq::get('page') : 1;
+
+		$referDB = new IQuery('refer as r');
+		$referDB->join = 'left join user as u on r.user_id = u.id';
+		$referDB->where = 'r.goods_id = '.$goods_id;
+		$referDB->order = 'r.id desc';
+		$referDB->fields = 'u.username,u.head_ico,r.time,r.question,r.reply_time,r.answer';
+		$referDB->page = $page;
+
+		$data = $referDB->find();
+		$pageHtml = $referDB->getPageBar("javascript:void(0);",'onclick="refer_ajax([page])"');
+
+		echo JSON::encode(array('data' => $data,'pageHtml' => $pageHtml));
+	}
+
+	//评论列表页
+	function comments_list()
+	{
+		$id   = IFilter::act(IReq::get("id"),'int');
+		$type = IFilter::act(IReq::get("type"));
+		$data = array();
+
+		//评分级别
+		$type_config = array('bad'=>'1','middle'=>'2,3,4','good'=>'5');
+		$point       = isset($type_config[$type]) ? $type_config[$type] : "";
+
+		//查询评价数据
+		$this->commentQuery = Api::run('getListByGoods',$id,$point);
+		$this->commentCount = Comment_Class::get_comment_info($id);
+		$this->goods        = Api::run('getGoodsInfo',array("#id#",$id));
+		if(!$this->goods)
+		{
+			IError::show("商品信息不存在");
+		}
+		$this->redirect('comments_list');
+	}
+
+	//提交评论页
+	function comments()
+	{
+		$id = IFilter::act(IReq::get('id'),'int');
+
+		if(!$id)
+		{
+			IError::show(403,"传递的参数不完整");
+		}
+
+		if(!isset($this->user['user_id']) || $this->user['user_id']==null )
+		{
+			IError::show(403,"登录后才允许评论");
+		}
+
+		$result = Comment_Class::can_comment($id,$this->user['user_id']);
+		if(is_string($result))
+		{
+			IError::show(403,$result);
+		}
+
+		$this->comment      = $result;
+		$this->commentCount = Comment_Class::get_comment_info($result['goods_id']);
+		$this->goods        = Comment_Class::goodsInfo($id);
+		if(!$this->goods)
+		{
+			IError::show("商品信息不存在");
+		}
+		$this->redirect("comments");
+	}
+
+	/**
+	 * @brief 进行商品评论 ajax操作
+	 */
+	public function comment_add()
+	{
+		$id      = IFilter::act(IReq::get('id'),'int');
+		$content = IFilter::act(IReq::get("contents"));
+		if(!$id || !$content)
+		{
+			IError::show(403,"填写完整的评论内容");
+		}
+
+		if(!isset($this->user['user_id']) || !$this->user['user_id'])
+		{
+			IError::show(403,"未登录用户不能评论");
+		}
+
+		$data = array(
+			'point'        => IFilter::act(IReq::get('point'),'float'),
+			'contents'     => $content,
+			'status'       => 1,
+			'comment_time' => ITime::getNow("Y-m-d"),
+		);
+
+		if($data['point']==0)
+		{
+			IError::show(403,"请选择分数");
+		}
+
+		$result = Comment_Class::can_comment($id,$this->user['user_id']);
+		if(is_string($result))
+		{
+			IError::show(403,$result);
+		}
+
+		$tb_comment = new IModel("comment");
+		$tb_comment->setData($data);
+		$re         = $tb_comment->update("id={$id}");
+
+		if($re)
+		{
+			$commentRow = $tb_comment->getObj('id = '.$id);
+
+			//同步更新goods表,comments,grade
+			$goodsDB = new IModel('goods');
+			$goodsDB->setData(array(
+				'comments' => 'comments + 1',
+				'grade'    => 'grade + '.$commentRow['point'],
+			));
+			$goodsDB->update('id = '.$commentRow['goods_id'],array('grade','comments'));
+
+			//同步更新seller表,comments,grade
+			$sellerDB = new IModel('seller');
+			$sellerDB->setData(array(
+				'comments' => 'comments + 1',
+				'grade'    => 'grade + '.$commentRow['point'],
+			));
+			$sellerDB->update('id = '.$commentRow['seller_id'],array('grade','comments'));
+			$this->redirect("/site/comments_list/id/".$commentRow['goods_id']);
+		}
+		else
+		{
+			IError::show(403,"评论失败");
+		}
+	}
+
+	function pic_show()
+	{
+		$this->layout="";
+
+		$id   = IFilter::act(IReq::get('id'),'int');
+		$item = Api::run('getGoodsInfo',array('#id#',$id));
+		if(!$item)
+		{
+			IError::show(403,'商品信息不存在');
+		}
+		$photo = Api::run('getGoodsPhotoRelationList',array('#id#',$id));
+		$this->setRenderData(array("id" => $id,"item" => $item,"photo" => $photo));
+		$this->redirect("pic_show");
+	}
+
+	function help()
+	{
+		$id       = IFilter::act(IReq::get("id"),'int');
+		$tb_help  = new IModel("help");
+		$help_row = $tb_help->getObj("id={$id}");
+		if(!$help_row)
+		{
+			IError::show(404,"您查找的页面已经不存在了");
+		}
+		$tb_help_cat    = new IModel("help_category");
+		$this->cat_row  = $tb_help_cat->getObj("id={$help_row['cat_id']}");
+		$this->help_row = $help_row;
+		$this->redirect("help");
+	}
+
+	function help_list()
+	{
+		$id          = IFilter::act(IReq::get("id"),'int');
+		$tb_help_cat = new IModel("help_category");
+		$cat_row     = $tb_help_cat->getObj("id={$id}");
+
+		//帮助分类数据存在
+		if($cat_row)
+		{
+			$this->helpQuery = Api::run('getHelpListByCatId',$id);
+			$this->cat_row   = $cat_row;
+		}
+		else
+		{
+			$this->helpQuery = Api::run('getHelpList');
+			$this->cat_row   = array('id' => 0,'name' => '站点帮助');
+		}
+		$this->redirect("help_list");
+	}
+
+	//团购页面
+	function groupon()
+	{
+		$id = IFilter::act(IReq::get("id"),'int');
+
+		//指定某个团购
+		if($id)
+		{
+			$this->regiment_list = Api::run('getRegimentRowById',array('#id#',$id));
+			$this->regiment_list = $this->regiment_list ? array($this->regiment_list) : array();
+		}
+		else
+		{
+			$this->regiment_list = Api::run('getRegimentList');
+		}
+
+		if(!$this->regiment_list)
+		{
+			IError::show('当前没有可以参加的团购活动');
+		}
+
+		//往期团购
+		$this->ever_list = Api::run('getEverRegimentList');
+		$this->redirect("groupon");
+	}
+
+	//品牌列表页面
+	function brand()
+	{
+		$id   = IFilter::act(IReq::get('id'),'int');
+		$name = IFilter::act(IReq::get('name'));
+		$this->setRenderData(array('id' => $id,'name' => $name));
+		$this->redirect('brand');
+	}
+
+	//品牌专区页面
+	function brand_zone()
+	{
+		$brandId  = IFilter::act(IReq::get('id'),'int');
+		$brandRow = Api::run('getBrandInfo',$brandId);
+		if(!$brandRow)
+		{
+			IError::show(403,'品牌信息不存在');
+		}
+		$this->setRenderData(array('brandId' => $brandId,'brandRow' => $brandRow));
+		$this->redirect('brand_zone');
+	}
+
+	//商家主页
+	function home()
+	{
+		$seller_id = IFilter::act(IReq::get('id'),'int');
+		$sellerRow = Api::run('getSellerInfo',$seller_id);
+		if(!$sellerRow)
+		{
+			IError::show(403,'商户信息不存在');
+		}
+		$this->setRenderData(array('sellerRow' => $sellerRow,'seller_id' => $seller_id));
+		$this->redirect('home');
+	}
+}

+ 1425 - 0
src/controllers/system.php

@@ -0,0 +1,1425 @@
+<?php
+/**
+ * @brief 系统模块
+ * @class System
+ * @note  后台
+ */
+class System extends IController implements adminAuthorization
+{
+	public $checkRight  = array('check' => 'all','uncheck' => array('default','admin_repwd','admin_repwd_act','navigation','navigation_update','navigation_del','navigation_edit','navigation_recycle','navigation_recycle_del','navigation_recycle_restore'));
+	public $layout      = 'admin';
+
+	public function init()
+	{
+
+	}
+
+	//邮件发送测试
+	function test_sendmail()
+	{
+		$site_config                 = array();
+		$site_config['email_type']   = IReq::get('email_type');
+		$site_config['mail_address'] = IReq::get('mail_address');
+		$site_config['smtp']         = IReq::get('smtp');
+		$site_config['smtp_user']    = IReq::get('smtp_user');
+		$site_config['smtp_pwd']     = IReq::get('smtp_pwd');
+		$site_config['smtp_port']    = IReq::get('smtp_port');
+		$site_config['email_safe']   = IReq::get('email_safe');
+		$site_config['name']         = "iWebShop";
+		$test_address                = IReq::get('test_address');
+
+		$smtp = new SendMail($site_config);
+		if($error = $smtp->getError())
+		{
+			$result = array('isError'=>true,'message' => $error);
+		}
+		else
+		{
+			$title    = 'email test';
+			$content  = '您好,这是来自iWebShop系统的测试邮件,如果您能收到此邮件那么恭喜您,系统邮件服务正常。';
+			if($smtp->send($test_address,$title,$content))
+			{
+				$result = array('isError'=>false,'message' => '恭喜你!测试通过');
+			}
+			else
+			{
+				$result = array('isError'=>true,'message' => $smtp->getError());
+			}
+		}
+		echo JSON::encode($result);
+	}
+
+	//列出控制器
+	function list_controller()
+	{
+		$planPath = $this->app->getBasePath().'controllers';
+		$planList = array();
+		$dirRes   = opendir($planPath);
+
+		while(false !== ($dir = readdir($dirRes)))
+		{
+			if($dir[0] == ".")
+			{
+				continue;
+			}
+			$planList[] = basename($dir,'.php');
+		}
+		echo JSON::encode($planList);
+	}
+
+	//列出某个控制器的action动作和视图
+	function list_action()
+	{
+		$ctrlId     = IReq::get('ctrlId');
+		if($ctrlId != '')
+		{
+			$baseContrl = get_class_methods('IController');
+			$advContrl  = get_class_methods($ctrlId);
+			$diffArray  = array_diff($advContrl,$baseContrl);
+			echo JSON::encode($diffArray);
+		}
+	}
+
+	/**
+	 * @brief 配送方式修改
+	 */
+    public function delivery_edit()
+	{
+		$data = array();
+        $id = IFilter::act(IReq::get('id'),'int');
+
+        if($id)
+        {
+            $delivery = new IModel('delivery');
+            $data = $delivery->getObj('id = '.$id);
+		}
+
+		//获取省份
+		$areaData = array();
+		$areaDB = new IModel('areas');
+		$areaList = $areaDB->query('parent_id = 0');
+		foreach($areaList as $val)
+		{
+			$areaData[$val['area_id']] = $val['area_name'];
+		}
+		$this->areaList  = $areaList;
+		$this->data_info = $data;
+		$this->area      = $areaData;
+        $this->redirect('delivery_edit');
+	}
+
+	/**
+	 * @brief 配送方式删除和还原
+	 */
+	public function delivery_operate()
+	{
+		$id = IReq::get('id');
+		$op = IReq::get('op');
+        if(is_array($id)) $id = implode(',',$id);
+
+        if(empty($id))
+        {
+        	if($op == 'del' || $op == 'recover')
+        	{
+        		$this->redirect('delivery_recycle',false);
+        	}
+        	else
+        	{
+        		$this->redirect('delivery',false);
+        	}
+        	Util::showMessage('请选择要操作的选项');
+        	exit;
+        }
+
+		$delivery     =  new IModel('delivery');
+		$deliveryData = $delivery->query('id in ('.$id.')','name');
+		$deliveryName = array();
+		foreach($deliveryData as $val)
+		{
+			$deliveryName[] = $val['name'];
+		}
+
+		$logObj = new log('db');
+
+		//物理删除
+		if($op=='del')
+		{
+			$delivery->del('id in('.$id.')');
+
+			$logObj->write('operation',array("管理员:".$this->admin['admin_name'],"删除了回收站中的配送方式","被删除的配送方式为:".join(',',$deliveryName)));
+
+			$this->redirect('delivery_recycle');
+		}
+		else if($op =='recover')//还原
+		{
+			$delivery->setData(array('is_delete'=>0));
+			if($delivery->update('id in('.$id.')'))
+			{
+				$logObj->write('operation',array('管理员:'.$this->admin['admin_name'],'恢复了回收站中的配送方式','被恢复的配送方式为:'.join(',',$deliveryName)));
+			}
+
+			$this->redirect('delivery_recycle');
+		}
+		else//逻辑删除
+		{
+			$delivery->setData(array('is_delete'=>1));
+			if($delivery->update('id in('.$id.')'))
+			{
+				$logObj->write('operation',array("管理员:".$this->admin['admin_name'],"把配送方式移除到回收站中","被移除到回收站中的配送方式为:".join(',',$deliveryName)));
+			}
+
+			$this->redirect('delivery');
+		}
+	}
+
+	/**
+	 * 配送方式修改
+	 */
+    public function delivery_update()
+    {
+        $delivery = new IModel('delivery');
+        //ID
+        $id   = IFilter::act(IReq::get('id'),'int');
+		//配送方式名称
+		$name = IFilter::act(IReq::get('name'));
+		//类型
+		$type = IFilter::act(IReq::get('type'),'int');
+        //首重重量
+        $first_weight = IFilter::act(IReq::get('first_weight'),'float');
+        //续重重量
+        $second_weight = IFilter::act(IReq::get('second_weight'),'float');
+        //首重价格
+        $first_price = IFilter::act(IReq::get('first_price'),'float');
+        //续重价格
+        $second_price = IFilter::act(IReq::get('second_price'),'float');
+        //是否支持物流保价
+        $is_save_price = IFilter::act(IReq::get('is_save_price'),'int');
+        //地区费用类型
+        $price_type = IFilter::act(IReq::get('price_type'),'int');
+        //启用默认费用
+        $open_default = IFilter::act(IReq::get('open_default'),'int');
+        //支持的配送地区ID
+        $area_groupid = serialize(IReq::get('area_groupid'));
+        //配送地址对应的首重价格
+        $firstprice = serialize(IReq::get('firstprice'));
+        //配送地区对应的续重价格
+        $secondprice = serialize(IReq::get('secondprice'));
+        //排序
+        $sort = IFilter::act(IReq::get('sort'),'int');
+        //状态
+        $status = IFilter::act(IReq::get('status'),'int');
+        //描述
+        $description = IFilter::act(IReq::get('description'),'text');
+        //保价费率
+        $save_rate = IFilter::act(IReq::get('save_rate'),'float');
+        //最低保价
+        $low_price = IFilter::act(IReq::get('low_price'),'float');
+
+        $data = array(
+        	'name'         => $name,
+        	'type'         => $type,
+        	'first_weight' => $first_weight,
+        	'second_weight'=> $second_weight,
+        	'first_price'  => $first_price,
+        	'second_price' => $second_price,
+        	'is_save_price'=> $is_save_price,
+        	'price_type'   => $price_type,
+        	'open_default' => $open_default,
+        	'area_groupid' => $area_groupid,
+        	'firstprice'   => $firstprice,
+        	'secondprice'  => $secondprice,
+        	'sort'         => $sort,
+        	'status'       => $status,
+        	'description'  => $description,
+        	'save_rate'    => $save_rate,
+        	'low_price'    => $low_price,
+        );
+
+        //如果选择指定地区配送就必须要选择地区
+        if($price_type == 1 && !$area_groupid)
+        {
+			die('请设置配送地区');
+        }
+
+        $delivery->setData($data);
+        $logObj = new log('db');
+
+		if($id=="")
+		{
+			if($delivery->add())
+			{
+				$logObj->write('operation',array("管理员:".$this->admin['admin_name'],"添加了配送方式",'添加的配送方式为:'.$name));
+			}
+		}
+		else
+		{
+			if($delivery->update('id = '.$id))
+			{
+				$logObj->write('operation',array("管理员:".$this->admin['admin_name'],"修改了配送方式",'修改的配送方式为:'.$name));
+			}
+		}
+		$this->redirect('delivery');
+    }
+
+   /**
+    * 添加/修改支付方式插件
+    */
+    function payment_edit()
+    {
+        $payment_id = IFilter::act(IReq::get("id"),'int');
+        $paymentRow = array();
+        $paymentObj = new IModel('payment');
+    	$paymentRow = $paymentObj->getObj("id = ".$payment_id);
+    	if($paymentRow)
+    	{
+	        $this->paymentRow = $paymentRow;
+	        $this->redirect('payment_edit');
+    	}
+
+        if(!$paymentRow)
+        {
+        	IError::show(403,"支付方式不存在");
+        }
+    }
+
+ 	/**
+     * @brief 更新支付方式插件
+     */
+    function payment_update()
+    {
+    	//获取Post数据
+    	$payment_id    = IFilter::act(IReq::get("id"),'int');
+    	$name          = IFilter::act(IReq::get("name"));
+    	$poundage_type = IFilter::act(IReq::get("poundage_type"),'int');
+    	$poundage      = IFilter::act(IReq::get("poundage"),'float');
+        $order         = IFilter::act(IReq::get("order"),'int');
+        $note          = IFilter::act(IReq::get('note'),'text');
+        $status        = IFilter::act(IReq::get('status'),'int');
+        $client_type   = IFilter::act(IReq::get('client_type'),'int');
+        $config_param  = array();
+
+        $paymentInstance = Payment::createPaymentInstance($payment_id);
+        $configParam     = $paymentInstance->configParam();
+        foreach($configParam as $key => $val)
+        {
+			$config_param[$key] = IFilter::act(IReq::get($key));
+        }
+        $config_param = IFilter::act(JSON::encode($config_param));
+
+        $updateData = array(
+        	'name'          => $name,
+        	'poundage_type' => $poundage_type,
+        	'poundage'      => $poundage,
+        	'order'         => $order,
+        	'note'          => $note,
+        	'status'        => $status,
+        	'config_param'  => $config_param,
+        	'client_type'   => $client_type,
+        );
+
+        $paymentDB = new IModel('payment');
+        $paymentDB->setData($updateData);
+        $paymentDB->update('id = '.$payment_id);
+
+        //日志记录
+		$logObj = new log('db');
+		$logObj->write('operation',array("管理员:".$this->admin['admin_name'],"修改了支付方式",'修改的支付方式为:'.$name));
+
+		$this->redirect('payment_list');
+    }
+	//[网站管理][站点设置]保存
+	function save_conf()
+	{
+		if(!$_POST)
+		{
+			$this->redirect('conf_base');
+		}
+
+		//错误信息
+		$form_index = IFilter::act(IReq::get('form_index'));
+		switch($form_index)
+		{
+			case "base_conf":
+			{
+				if(isset($_FILES['logo']['name']) && $_FILES['logo']['name']!='')
+				{
+					$uploadObj = new PhotoUpload();
+					$uploadObj->setIterance(false);
+					$photoInfo = $uploadObj->run();
+					if(isset($photoInfo['logo']['img']) && file_exists($photoInfo['logo']['img']))
+					{
+						$_POST['logo'] = $photoInfo['logo']['img'];
+					}
+				}
+			}
+			break;
+
+			case "site_footer_conf":
+			{
+				$_POST['site_footer_code']=preg_replace('![\\r\\n]+!',"",$_POST['site_footer_code']);
+			}
+			break;
+
+			case "index_slide":
+			{
+				$config_slide = array();
+				if(isset($_POST['slide_name']))
+				{
+					foreach($_POST['slide_name'] as $key => $value)
+					{
+						$config_slide[$key]['name'] = $value;
+						$config_slide[$key]['url']  = $_POST['slide_url'][$key];
+						$config_slide[$key]['img']  = $_POST['slide_img'][$key];
+					}
+				}
+
+				if( isset($_FILES['slide_pic']) )
+				{
+					$uploadObj = new PhotoUpload();
+					$uploadObj->setIterance(false);
+					$slideInfo = $uploadObj->run();
+
+					if(isset($slideInfo['slide_pic']['flag']))
+					{
+						$slideInfo['slide_pic'] = array($slideInfo['slide_pic']);
+					}
+
+					if(isset($slideInfo['slide_pic']))
+					{
+						foreach($slideInfo['slide_pic'] as $key=>$value)
+						{
+
+							if($value['flag']==1)
+							{
+								$config_slide[$key]['img']=$value['img'];
+							}
+						}
+					}
+
+				}
+				$_POST = array('index_slide' => serialize( $config_slide ));
+			}
+			break;
+
+			//导航写入数据库,不需要记录配置文件
+			case "guide_conf":
+			{
+				$guideName = IFilter::act(IReq::get('guide_name'));
+				$guideLink = IFilter::act(IReq::get('guide_link'));
+				$data      = array();
+
+				$guideObj = new IModel('guide');
+
+				if(!empty($guideName))
+				{
+					foreach($guideName as $key => $val)
+					{
+						if(!empty($val) && !empty($guideLink[$key]))
+						{
+							$data[$key]['name'] = $val;
+							$data[$key]['link'] = $guideLink[$key];
+						}
+					}
+				}
+
+				//清空导航栏
+				$guideObj->del('all');
+
+				if($data)
+				{
+					//插入数据
+					foreach($data as $order => $rs)
+					{
+						$dataArray = array(
+							'order' => $order,
+							'name'  => $rs['name'],
+							'link'  => $rs['link'],
+						);
+						$guideObj->setData($dataArray);
+						$guideObj->add();
+					}
+				}
+			}
+			break;
+
+			case "other_conf":
+			{
+				if( isset($_POST['auto_finish']) && $_POST['auto_finish']=="" )
+				{
+					$_POST['auto_finish']=="0";
+				}
+			}
+			break;
+
+			case "mail_conf":
+			break;
+			case "system_conf":
+			break;
+		}
+
+		//获取输入的数据
+		$inputArray = $_POST;
+		if($form_index == 'system_conf')
+		{
+			//写入的配置文件
+			$configFile = IWeb::$app->getBasePath().'config/config.php';
+			Config::edit($configFile,$inputArray);
+		}
+		else
+		{
+			$siteObj = new Config('site_config');
+			$siteObj->write($inputArray);
+		}
+		$this->redirect('/system/conf_base/form_index/'.$form_index);
+	}
+
+	//网站设置页面
+	function conf_base()
+	{
+		$this->confRow = array_merge(IWeb::$app->config,$this->_siteConfig->getInfo(),array("form_index" => IFilter::act(IReq::get('form_index'))));
+		$this->redirect('conf_base');
+	}
+
+	//[权限管理][管理员]管理员添加,修改[单页]
+	function admin_edit()
+	{
+		$id =IFilter::act( IReq::get('id'),'int' );
+		if($id)
+		{
+			$adminObj = new IModel('admin');
+			$where = 'id = '.$id;
+			$this->adminRow = $adminObj->getObj($where);
+		}
+		$this->redirect('admin_edit');
+	}
+
+	//[权限管理][管理员]管理员添加,修改[动作]
+	function admin_edit_act()
+	{
+		$id = IFilter::act( IReq::get('id','post') );
+		$adminObj = new IModel('admin');
+
+		$dataArray = array(
+			'id'         => $id,
+			'admin_name' => IFilter::string( IReq::get('admin_name','post') ),
+			'role_id'    => IFilter::act( IReq::get('role_id','post') ),
+			'email'      => IFilter::string( IReq::get('email','post') ),
+		);
+
+		//检查管理员name唯一性
+		$whereString = 'admin_name = "'.$dataArray['admin_name'].'"';
+		$whereString.= $id ? ' and id != '.$id : '';
+		$isPass = $adminObj->getObj($whereString);
+		if($isPass)
+		{
+			$this->setError($dataArray['admin_name'].'管理员已经存在,请更改名字');
+		}
+
+		//提取密码 [ 密码设置 ]
+		$password   = IReq::get('password','post');
+		$repassword = IReq::get('repassword','post');
+
+		if($password || $repassword)
+		{
+			if(!$password || !$repassword || $password != $repassword)
+			{
+				$this->setError('密码不能为空,并且二次输入的必须一致');
+			}
+			else
+			{
+				$dataArray['password'] = md5($password);
+			}
+		}
+
+		//有错误
+		if($this->getError())
+		{
+			$this->adminRow = $dataArray;
+			$this->redirect('admin_edit',false);
+			Util::showMessage($this->getError());
+		}
+
+		//修改操作
+		if($id)
+		{
+			$where = 'id = '.$id;
+			$adminObj->setData($dataArray);
+			$adminObj->update($where);
+
+			//修改为自身密码时
+			if($id == $this->admin['admin_id'])
+			{
+				//同步更新safe
+				ISafe::set('admin_name',$dataArray['admin_name']);
+				if(isset($dataArray['password']))
+				{
+					ISafe::set('admin_pwd',$dataArray['password']);
+				}
+			}
+		}
+		//添加操作
+		else
+		{
+			$dataArray['create_time'] = ITime::getDateTime();
+			$adminObj->setData($dataArray);
+			$adminObj->add();
+		}
+		$this->redirect('admin_list');
+	}
+
+	//[权限管理][管理员]管理员更新操作[回收站操作][物理删除]
+	function admin_update()
+	{
+		$id = IFilter::act( IReq::get('id') ,'int' );
+
+		if($id == 1 || (is_array($id) && in_array(1,$id)))
+		{
+			$this->redirect('admin_list',false);
+			Util::showMessage('不允许删除系统初始化管理员');
+		}
+
+		//是否为回收站操作
+		$isRecycle = IReq::get('recycle');
+
+		if(!empty($id))
+		{
+			$obj   = new IModel('admin');
+			$where = Util::joinStr($id);
+
+			if($isRecycle === null)
+			{
+				$obj->del($where);
+				$this->redirect('admin_recycle');
+			}
+			else
+			{
+				//回收站操作类型
+				$is_del = ($isRecycle == 'del') ? 1 : 0;
+				$obj->setData(array('is_del' => $is_del));
+				$obj->update($where);
+				$this->redirect('admin_list');
+			}
+		}
+		else
+		{
+			if($isRecycle == 'del')
+				$this->redirect('admin_list',false);
+			else
+				$this->redirect('admin_recycle',false);
+
+			Util::showMessage('请选择要操作的管理员ID');
+		}
+	}
+
+	//[权限管理][角色] 角色更新操作[回收站操作][物理删除]
+	function role_update()
+	{
+		$id = IFilter::act( IReq::get('id'),'int' );
+
+		//是否为回收站操作
+		$isRecycle = IReq::get('recycle');
+
+		if(!empty($id))
+		{
+			$obj   = new IModel('admin_role');
+			$where = Util::joinStr($id);
+
+			if($isRecycle === null)
+			{
+				$obj->del($where);
+				$this->redirect('role_recycle');
+			}
+			else
+			{
+				//回收站操作类型
+				$is_del    = ($isRecycle == 'del') ? 1 : 0;
+				$obj->setData(array('is_del' => $is_del));
+				$obj->update($where);
+				$this->redirect('role_list');
+			}
+		}
+		else
+		{
+			if($isRecycle == 'del')
+				$this->redirect('role_list',false);
+			else
+				$this->redirect('role_recycle',false);
+
+			Util::showMessage('请选择要操作的角色ID');
+		}
+	}
+
+	//[权限管理][角色] 角色修改,添加 [单页]
+	function role_edit()
+	{
+		$id = IFilter::act( IReq::get('id'),'int' );
+		if($id)
+		{
+			$adminObj = new IModel('admin_role');
+			$where = 'id = '.$id;
+			$this->roleRow = $adminObj->getObj($where);
+		}
+
+		//获取权限码分组形势
+		$rightObj  = new IModel('right');
+		$rightData = $rightObj->query('is_del = 0','*','name asc');
+
+		$rightArray     = array();
+		$rightUndefined = array();
+		foreach($rightData as $key => $item)
+		{
+			preg_match('/\[.*?\]/',$item['name'],$localPre);
+			if(isset($localPre[0]))
+			{
+				$arrayKey = trim($localPre[0],'[]');
+				$rightArray[$arrayKey][] = $item;
+			}
+			else
+			{
+				$rightUndefined[]      = $item;
+			}
+		}
+
+		$this->rightArray     = $rightArray;
+		$this->rightUndefined = $rightUndefined;
+
+		$this->redirect('role_edit');
+	}
+
+	//[权限管理][角色] 角色修改,添加 [动作]
+	function role_edit_act()
+	{
+		$id = IFilter::act( IReq::get('id','post') );
+		$roleObj = new IModel('admin_role');
+
+		//要入库的数据
+		$dataArray = array(
+			'id'     => $id,
+			'name'   => IFilter::string( IReq::get('name','post') ),
+			'rights' => null,
+		);
+
+		//检查权限码是否为空
+		$rights = IFilter::act( IReq::get('right','post') );
+		if(!$rights || $rights[0]=='')
+		{
+			$this->redirect("/system/role_edit/id/{$id}/_msg/fail");
+			exit;
+		}
+
+		//拼接权限码
+		$rightsArray = array();
+		$rightObj    = new IModel('right');
+		$rightList   = $rightObj->query('id in ('.join(",",$rights).')','`right`');
+		foreach($rightList as $key => $val)
+		{
+			$rightsArray[] = trim($val['right'],',');
+		}
+
+		$dataArray['rights'] = empty($rightsArray) ? '' : ','.join(',',$rightsArray).',';
+		$roleObj->setData($dataArray);
+		if($id)
+		{
+			$where = 'id = '.$id;
+			$roleObj->update($where);
+		}
+		else
+		{
+			$roleObj->add();
+		}
+		$this->redirect('role_list');
+	}
+
+	//[权限管理][权限] 权限修改,添加[单页]
+	function right_edit()
+	{
+		$id = IFilter::act( IReq::get('id'),'int' );
+		if($id)
+		{
+			$adminObj = new IModel('right');
+			$where = 'id = '.$id;
+			$this->rightRow = $adminObj->getObj($where);
+		}
+
+		$this->redirect('right_edit');
+	}
+
+	//[权限管理][权限] 权限修改,添加[动作]
+	function right_edit_act()
+	{
+		$id    = IFilter::act( IReq::get('id','post') );
+		$right = IFilter::act( array_unique(IReq::get('right')) );
+		$name  = IFilter::act( IReq::get('name','post') );
+
+		if(!$right)
+		{
+			$this->rightRow = array(
+				'id'   => $id,
+				'name' => $name,
+			);
+			$this->redirect('right_edit',false);
+			Util::showMessage('权限码不能为空');
+			exit;
+		}
+
+		$dataArray = array(
+			'id'    => $id,
+			'name'  => $name,
+			'right' => join(',',$right),
+		);
+
+		$rightObj = new IModel('right');
+		$rightObj->setData($dataArray);
+		if($id)
+		{
+			$where = 'id = '.$id;
+			$rightObj->update($where);
+		}
+		else
+		{
+			$rightObj->add();
+		}
+		$this->redirect('right_list');
+	}
+
+	//[权限管理][权限] 权限更新操作 [回收站操作][物理删除]
+	function right_update()
+	{
+		$id = IFilter::act(IReq::get('id'),'int');
+
+		//是否为回收站操作
+		$isRecycle = IReq::get('recycle');
+
+		if(!empty($id))
+		{
+			$obj   = new IModel('right');
+			$where = Util::joinStr($id);
+
+			if($isRecycle === null)
+			{
+				$obj->del($where);
+				$this->redirect('right_recycle');
+			}
+			else
+			{
+				//回收站操作类型
+				$is_del    = ($isRecycle == 'del') ? 1 : 0;
+				$obj->setData(array('is_del' => $is_del));
+				$obj->update($where);
+				$this->redirect('right_list');
+			}
+		}
+		else
+		{
+			if($isRecycle == 'del')
+				$this->redirect('right_list',false);
+			else
+				$this->redirect('right_recycle',false);
+
+			Util::showMessage('请选择要操作的权限ID');
+		}
+	}
+
+	//清理缓存
+	function clearCache()
+	{
+		$runtimePath = IWeb::$app->getBasePath().'runtime';
+		$result      = IFile::clearDir($runtimePath);
+
+		if($result == true)
+			echo 1;
+		else
+			echo -1;
+	}
+
+	//主题列表
+	function conf_ui()
+	{
+		$themeType = IReq::get('type') ? IFilter::act(IReq::get('type')) : 'site';
+		$themeList = themeroute::themeTypeList($themeType);
+		if(!$themeList)
+		{
+			IError::show(403,'主题信息不存在');
+		}
+		$themeTypeName = themeroute::themeTypeTxt($themeType);
+		$this->setRenderData(
+			array('themeTypeName' => $themeTypeName,'themeList' => $themeList)
+		);
+		$this->redirect('conf_ui');
+	}
+
+	//启用主题
+	function applyTheme()
+	{
+		$type = IFilter::act(IReq::get('type'));
+		$issetConfig = IWeb::$app->config['theme'];
+		foreach(IClient::supportClient() as $key => $client)
+		{
+			$clientTheme = IReq::get($client);
+			if($clientTheme)
+			{
+				$clientData = JSON::decode($clientTheme);
+
+				//配置文件中是否已经存在
+				if(isset( $issetConfig[$client] ))
+				{
+					//此次启用的主题类型
+					$themeType = themeroute::themeType( key($clientData) );
+					if(!$themeType)
+					{
+						die($clientTheme."无法识别主题类型");
+					}
+
+					foreach($issetConfig[$client] as $theme => $skin)
+					{
+						$issetThemeType = themeroute::themeType($theme);
+						if(!$issetThemeType || $themeType == $issetThemeType)
+						{
+							unset($issetConfig[$client][$theme]);
+						}
+					}
+				}
+				else
+				{
+					$issetConfig[$client] = array();
+				}
+				$issetConfig[$client] = array_merge($issetConfig[$client],$clientData);
+			}
+		}
+
+		if($issetConfig != IWeb::$app->config['theme'])
+		{
+			IWeb::$app->config['theme'] = $issetConfig;
+			Config::edit('config/config.php',array("theme" => IWeb::$app->config['theme']));
+		}
+		$this->redirect('/system/conf_ui/type/'.$type.'/_msg/success');
+	}
+
+	//管理员添加快速导航
+	function navigation_edit()
+	{
+		$id = IFilter::act(IReq::get('id'),'int');
+		if($id)
+		{
+			$navigationObj = new IModel('quick_naviga');
+			$where = 'id = '.$id;
+			$this->navigationRow = $navigationObj->getObj($where);
+		}
+		$this->redirect('navigation_edit');
+	}
+	//保存管理员添加快速导航
+	function navigation_update()
+	{
+		$id = IFilter::act(IReq::get('id','post'),'int');
+		$navigationObj = new IModel('quick_naviga');
+		$navigationObj->setData(array(
+			'admin_id'=>$this->admin['admin_id'],
+			'naviga_name'=>IFilter::act(IReq::get('naviga_name')),
+			'url'=>IFilter::act(IReq::get('url')),
+		));
+		if($id)
+		{
+			$navigationObj->update('id='.$id);
+		}
+		else
+		{
+			$navigationObj->add();
+		}
+		$this->redirect('navigation');
+	}
+	/**
+	 * @brief 删除管理员快速导航到回收站
+	 */
+	function navigation_del()
+	{
+		$ad_id = $this->admin['admin_id'];
+		$data['ad_id'] = $ad_id;
+		$this->setRenderData($data);
+		//post数据
+    	$id = IFilter::act(IReq::get('id'),'int');
+    	//生成order对象
+    	$tb_order = new IModel('quick_naviga');
+    	$tb_order->setData(array('is_del'=>1));
+    	if(!empty($id))
+		{
+			if(is_array($id) && isset($id[0]) && $id[0]!='')
+			{
+				$id_str = join(',',$id);
+				$where = ' id in ('.$id_str.')';
+			}
+			else
+			{
+				$where = 'id = '.$id;
+			}
+			$tb_order->update($where);
+			$this->redirect('navigation');
+		}
+		else
+		{
+			$this->redirect('navigation',false);
+			Util::showMessage('请选择要删除的数据');
+		}
+	}
+	//管理员快速导航_回收站
+	function navigation_recycle()
+	{
+		$data = array();
+		$ad_id = $this->admin['admin_id'];
+		$data['ad_id'] = $ad_id;
+		$this->setRenderData($data);
+		$this->redirect('navigation_recycle');
+	}
+	//彻底删除快速导航
+	function navigation_recycle_del()
+    {
+    	$ad_id = $this->admin['admin_id'];
+		$data['ad_id'] = $ad_id;
+		$this->setRenderData($data);
+    	//post数据
+    	$id = IFilter::act(IReq::get('id'),'int');
+    	//生成order对象
+    	$tb_order = new IModel('quick_naviga');
+    	if(!empty($id))
+		{
+			if(is_array($id) && isset($id[0]) && $id[0]!='')
+			{
+				$id_str = join(',',$id);
+				$where = ' id in ('.$id_str.')';
+			}
+			else
+			{
+				$where = 'id = '.$id;
+			}
+			$tb_order->del($where);
+			$this->redirect('navigation_recycle');
+		}
+		else
+		{
+			$this->redirect('navigation_recycle',false);
+			Util::showMessage('请选择要删除的数据');
+		}
+    }
+    //恢复快速导航
+	 function navigation_recycle_restore()
+    {
+    	$ad_id = $this->admin['admin_id'];
+		$data['ad_id'] = $ad_id;
+		$this->setRenderData($data);
+    	//post数据
+    	$id = IFilter::act(IReq::get('id'),'int');
+    	//生成order对象
+    	$tb_order = new IModel('quick_naviga');
+    	$tb_order->setData(array('is_del'=>0));
+    	if(!empty($id))
+		{
+			if(is_array($id) && isset($id[0]) && $id[0]!='')
+			{
+				$id_str = join(',',$id);
+				$where = ' id in ('.$id_str.')';
+			}
+			else
+			{
+				$where = 'id = '.$id;
+			}
+			$tb_order->update($where);
+			$this->redirect('navigation_recycle');
+		}
+		else
+		{
+			$this->redirect('navigation_recycle',false);
+			Util::showMessage('请选择要还原的数据');
+		}
+    }
+    /**
+     * 添加物流公司
+     * */
+    public function freight_edit()
+    {
+    	$id   = IFilter::act(IReq::get('id'),'int');
+    	$data = array();
+    	if($id)
+    	{
+    		$tb_freight = new IModel('freight_company');
+    		$data = $tb_freight->getObj('id='.$id);
+    	}
+
+    	$this->data = $data;
+    	$this->redirect('freight_edit');
+    }
+    /**
+     * 保存添加或修改的物流公司
+     * */
+    public function freight_update()
+    {
+    	$id = IFilter::act(IReq::get('id'),'int');
+    	$freight_type = IReq::get('freight_type');
+    	$freight_name = IReq::get('freight_name');
+    	$url = IReq::get('url');
+    	$sort = IReq::get('sort');
+
+    	$tb_freight = new IModel('freight_company');
+    	$tb_freight->setData(array(
+    		'freight_type' => $freight_type,
+    		'freight_name' => $freight_name,
+    		'url'		   => $url,
+    		'sort'		   => $sort
+    	));
+
+    	if($id)
+    	{
+    		$tb_freight->update('id='.$id);
+    	}
+    	else
+    	{
+    		$tb_freight->add();
+    	}
+    	$this->redirect('freight_list');
+    }
+    /**
+     * 逻辑删除物流公司
+     * */
+	function freight_del()
+    {
+    	$id = IReq::get('id');
+		if(!empty($id))
+		{
+			$obj = new IModel('freight_company');
+			$obj->setData(array('is_del'=>1));
+			if(is_array($id) && isset($id[0]) && $id[0]!='')
+			{
+				$id_str = join(',',$id);
+				$where = ' id in ('.$id_str.')';
+			}
+			else
+			{
+				$where = 'id = '.$id;
+			}
+			$obj->update($where);
+			$this->redirect('freight_list');
+		}
+		else
+		{
+			$this->redirect('freight_list',false);
+			Util::showMessage('请选择要删除的物流公司');
+		}
+    }
+	/**
+     * 物流公司回收站还原
+     * */
+    public function freight_recycle_restore()
+    {
+    	$id = IReq::get('id');
+		if(!empty($id))
+		{
+			$obj = new IModel('freight_company');
+			$obj->setData(array('is_del'=>0));
+			if(is_array($id) && isset($id[0]) && $id[0]!='')
+			{
+				$id_str = join(',',$id);
+				$where = ' id in ('.$id_str.')';
+			}
+			else
+			{
+				$where = 'id = '.$id;
+			}
+			$obj->update($where);
+			$this->redirect('freight_recycle');
+		}
+		else
+		{
+			$this->redirect('freight_recycle',false);
+			Util::showMessage('请选择要还原的物流公司');
+		}
+    }
+	/**
+     * 物流公司回收站彻底删除
+     * */
+    public function freight_recycle_del()
+    {
+    	$id = IReq::get('id');
+		if(!empty($id))
+		{
+			$obj = new IModel('freight_company');
+			$obj->setData(array('is_del'=>0));
+			if(is_array($id) && isset($id[0]) && $id[0]!='')
+			{
+				$id_str = join(',',$id);
+				$where = ' id in ('.$id_str.')';
+			}
+			else
+			{
+				$where = 'id = '.$id;
+			}
+			$obj->del($where);
+			$this->redirect('freight_recycle');
+		}
+		else
+		{
+			$this->redirect('freight_recycle',false);
+			Util::showMessage('请选择要删除的物流公司');
+		}
+    }
+    //修改oauth单页
+    public function oauth_edit()
+    {
+    	$id = IFilter::act(IReq::get('id'));
+    	if($id == 0)
+    	{
+    		$this->redirect('oauth_list',false);
+    		Util::showMessage('请选择要修改的登录平台');exit;
+    	}
+
+    	$oauthDBObj = new IModel('oauth');
+		$oauthRow = $oauthDBObj->getObj('id = '.$id);
+		if(empty($oauthRow))
+		{
+    		$this->redirect('oauth_list',false);
+    		Util::showMessage('请选择要修改的登录平台');exit;
+		}
+
+		//获取字段数据
+		$oauthObj           = new OauthCore($id);
+		$oauthRow['fields'] = $oauthObj->getFields();
+
+		$this->oauthRow = $oauthRow;
+		$this->redirect('oauth_edit',false);
+    }
+
+    //修改oauth动作
+    public function oauth_edit_act()
+    {
+    	$id = IFilter::act(IReq::get('id'));
+    	if($id == 0)
+    	{
+    		$this->redirect('oauth_list',false);
+    		Util::showMessage('请选择要修改的登录平台');exit;
+    	}
+
+    	$oauthDBObj = new IModel('oauth');
+		$oauthRow = $oauthDBObj->getObj('id = '.$id);
+		if(empty($oauthRow))
+		{
+    		$this->redirect('oauth_list',false);
+    		Util::showMessage('请选择要修改的登录平台');exit;
+		}
+
+		$dataArray = array(
+			'name'        => IFilter::act(IReq::get('name')),
+			'is_close'    => IFilter::act(IReq::get('is_close')),
+			'description' => IFilter::act(IReq::get('description')),
+			'config'      => array(),
+		);
+
+		//获取字段数据
+		$oauthObj    = new OauthCore($id);
+		$oauthFields = $oauthObj->getFields();
+
+		if(!empty($oauthFields))
+		{
+			$parmsArray = array_keys($oauthFields);
+			foreach($parmsArray as $val)
+			{
+				$dataArray['config'][$val] = IFilter::act(IReq::get($val));
+			}
+		}
+
+		$dataArray['config'] = serialize($dataArray['config']);
+		$oauthDBObj->setData($dataArray);
+		$oauthDBObj->update('id = '.$id);
+		$this->redirect('oauth_list');
+    }
+
+    /**
+     * @brief 地域更新
+     */
+    public function area_update()
+    {
+    	$area_id   = IFilter::act(IReq::get('area_id'));
+    	$area_name = IFilter::act(IReq::get('area_name'));
+    	$area_sort = IFilter::act(IReq::get('area_sort'));
+    	$parent_id = IFilter::act(IReq::get('parent_id'));
+
+		$areasDB = new IModel('areas');
+
+    	//添加
+    	if($parent_id !== '')
+    	{
+    		$addData = array('parent_id' => $parent_id,'area_name' => $area_name,'sort' => 99);
+    		$areasDB->setData($addData);
+    		$area_id = $areasDB->add();
+    		$addData['area_id'] = $area_id;
+    		die(JSON::encode(array('isSuccess' => true,'data' => $addData)));
+    	}
+    	//修改
+    	else
+    	{
+    		$updateData = array();
+    		if($area_name)
+    		{
+    			$updateData['area_name'] = $area_name;
+    		}
+
+    		if($area_sort)
+    		{
+    			$updateData['sort'] = $area_sort;
+    		}
+    		$areasDB->setData($updateData);
+    		$areasDB->update('area_id = '.$area_id);
+    	}
+    }
+
+	/**
+	 * @brief 地域删除
+	 */
+    public function area_del()
+    {
+    	$area_id = IFilter::act(IReq::get('id'),'int');
+    	$areasDB = new IModel('areas');
+    	$areasDB->del('area_id = '.$area_id);
+    }
+
+
+    /**
+	 * 自提点添加和修改
+	 */
+	public function takeself_update()
+	{
+		$id       = IFilter::act(IReq::get('id'),'int');
+    	$name     = IFilter::act(IReq::get('name'));
+    	$sort     = IFilter::act(IReq::get('sort'),'int');
+    	$province = IFilter::act(IReq::get('province'),'int');
+    	$city     = IFilter::act(IReq::get('city'),'int');
+    	$area     = IFilter::act(IReq::get('area'),'int');
+    	$address  = IFilter::act(IReq::get('address'));
+		$phone    = IFilter::act(IReq::get('phone'));
+		$mobile   = IFilter::act(IReq::get('mobile'));
+
+		$takeselfDB = new IModel('takeself');
+	    $data = array(
+        	'name'         => $name,
+        	'sort'         => $sort,
+        	'province'     => $province,
+        	'city'         => $city,
+        	'area'         => $area,
+        	'address'      => $address,
+        	'phone'        => $phone,
+        	'mobile'       => $mobile,
+        );
+        $takeselfDB->setData($data);
+        if($id)
+    	{
+    		$takeselfDB->update('id='.$id);
+    	}
+    	else
+    	{
+    		$takeselfDB->add();
+    	}
+
+	    $this->redirect("takeself_list");
+	}
+
+
+     /**
+	 * 自提点添加和修改视图
+	 */
+	public function takeself_edit()
+	{
+	    $id = IFilter::act(IReq::get('id'),'int');
+	    if($id)
+	    {
+			$takeselfDB        = new IModel('takeself');
+			$this->takeselfRow = $takeselfDB->getObj('id = '.$id );
+        }
+		$this->redirect("takeself_edit");
+	}
+
+    //删除自提点
+	public function takeself_operate()
+	{
+		$id = IFilter::act(IReq::get('id'));
+        if(is_array($id))
+        {
+        	$id = join(',',$id);
+        }
+
+        if($id)
+        {
+			$takeself =  new IModel('takeself');
+			$takeself->del('id in('.$id.')');
+			$this->redirect('takeself_list');
+        }
+        else
+        {
+        	$this->redirect('takeself_list',false);
+        	Util::showMessage('请选择要操作的选项');
+        }
+	}
+
+	/**
+	 *修改管理员密码
+	 */
+	function admin_repwd_act()
+	{
+		//提取密码 [ 密码设置 ]
+		$password   = IReq::get('password','post');
+		$repassword = IReq::get('repassword','post');
+
+		if($password && $password === $repassword)
+		{
+			$passwordMd5 = md5($password);
+			$adminObj = new IModel('admin');
+			$adminObj->setData(array('password' => $passwordMd5));
+			$adminObj->update('id = '.$this->admin['admin_id']);
+
+			//同步更新safe
+			ISafe::set('admin_pwd',$passwordMd5);
+
+			$this->redirect('default');
+		}
+		else
+		{
+			$message = '密码不能为空,并且二次输入的必须一致';
+			$this->redirect('admin_repwd',false);
+			Util::showMessage($message);
+		}
+	}
+
+	// 短信发送测试
+	function test_sendhsms()
+	{
+		$siteConfig = new Config('site_config');
+		if( !$siteConfig->sms_username || !$siteConfig->sms_pwd )
+		{
+			die( JSON::encode(array('isError' => true,'message' => '请先<保存>短信配置')) );
+		}
+
+		$mobile = IFilter::act(IReq::get('mobile'));
+		if($mobile === null || !IValidate::mobi($mobile))
+		{
+			die( JSON::encode(array('isError' => true,'message' => '请输入正确的手机号码')) );
+		}
+
+		$mobile_code = rand(10000,99999);
+		$content     = smsTemplate::checkCode(array('{mobile_code}' => $mobile_code));
+		$send_result = Hsms::send($mobile,$content);
+		if($send_result == 'success')
+		{
+			$result = array('isError' => false,'message' => '恭喜你!测试通过');
+		}
+		else
+		{
+			$result = array('isError' => true,'message' => $send_result);
+		}
+		echo JSON::encode($result);
+	}
+
+	//支付列表
+	function payment_list()
+	{
+		//重置货到付款预留
+		$paymentDB = new IModel('payment');
+		$paymentDB->setData(array('id' => 0));
+		$paymentDB->update('class_name = "freight_collect"');
+		$this->redirect('payment_list');
+	}
+}

+ 83 - 0
src/controllers/systemadmin.php

@@ -0,0 +1,83 @@
+<?php
+/**
+ * @class SystemAdmin
+ * @brief 后台登陆处理
+ */
+class SystemAdmin extends IController
+{
+	public $layout='';
+
+	//后台登陆
+	function login_act()
+	{
+		$admin_name = IFilter::act(IReq::get('admin_name'));
+		$password   = IReq::get('password');
+		$captcha    = IReq::get('captcha','post');
+		$_captcha   = ISafe::get('captcha');
+
+		$message    = '';
+
+		if($admin_name == '')
+		{
+			$message = '登录名不能为空';
+		}
+		else if($password == '')
+		{
+			$message = '密码不能为空';
+		}
+		else if(!$captcha || !$_captcha || $captcha != $_captcha)
+		{
+            $message = '验证码输入不正确';
+        }
+        else
+		{
+			$adminObj = new IModel('admin');
+			$adminRow = $adminObj->getObj('admin_name = "'.$admin_name.'"');
+			if(!empty($adminRow) && ($adminRow['password'] == md5($password)) && ($adminRow['is_del'] == 0))
+			{
+				$dataArray = array(
+					'last_ip'   => IClient::getIp(),
+					'last_time' => ITime::getDateTime(),
+				);
+				$adminObj->setData($dataArray);
+				$where = 'id = '.$adminRow["id"];
+				$adminObj->update($where);
+
+				//根据角色分配权限
+				if($adminRow['role_id'] == 0)
+				{
+					ISafe::set('admin_role_name','超级管理员');
+				}
+				else
+				{
+					$roleObj = new IModel('admin_role');
+					$where   = 'id = '.$adminRow["role_id"].' and is_del = 0';
+					$roleRow = $roleObj->getObj($where);
+					ISafe::set('admin_role_name',$roleRow['name']);
+				}
+				ISafe::set('admin_id',$adminRow['id']);
+				ISafe::set('admin_name',$adminRow['admin_name']);
+				ISafe::set('admin_pwd',$adminRow['password']);
+				$this->redirect('/system/default');
+			}
+			else
+			{
+				$message = '用户名与密码不匹配';
+			}
+		}
+
+		if($message != '')
+		{
+			$this->admin_name = $admin_name;
+			$this->redirect('index',false);
+			Util::showMessage($message);
+		}
+	}
+
+	//后台登出
+	function logout()
+	{
+		plugin::trigger('clearAdmin');
+    	$this->redirect('index');
+	}
+}

+ 68 - 0
src/controllers/systemseller.php

@@ -0,0 +1,68 @@
+<?php
+/**
+ * @brief 商家登录控制器
+ * @class Seller
+ * @author chendeshan
+ * @datetime 2014/7/19 15:18:56
+ */
+class SystemSeller extends IController
+{
+	public $layout = '';
+
+	/**
+	 * @brief 商家登录动作
+	 */
+	public function login()
+	{
+		$seller_name = IFilter::act(IReq::get('username'));
+		$password    = IReq::get('password');
+		$message     = '';
+
+		if($seller_name == '')
+		{
+			$message = '登录名不能为空';
+		}
+		else if($password == '')
+		{
+			$message = '密码不能为空';
+		}
+        else
+		{
+			$sellerObj = new IModel('seller');
+			$sellerRow = $sellerObj->getObj('seller_name = "'.$seller_name.'" and is_del = 0 and is_lock = 0');
+			if($sellerRow && ($sellerRow['password'] == md5($password)))
+			{
+				$dataArray = array(
+					'login_time' => ITime::getDateTime(),
+				);
+				$sellerObj->setData($dataArray);
+				$where = 'id = '.$sellerRow["id"];
+				$sellerObj->update($where);
+
+				//存入私密数据
+				ISafe::set('seller_id',$sellerRow['id']);
+				ISafe::set('seller_name',$sellerRow['seller_name']);
+				ISafe::set('seller_pwd',$sellerRow['password']);
+
+				$this->redirect('/seller/index');
+			}
+			else
+			{
+				$message = '用户名与密码不匹配';
+			}
+		}
+
+		if($message != '')
+		{
+			$this->redirect('index',false);
+			Util::showMessage($message);
+		}
+	}
+
+	//后台登出
+	function logout()
+	{
+		plugin::trigger('clearSeller');
+    	$this->redirect('index');
+	}
+}

+ 996 - 0
src/controllers/tools.php

@@ -0,0 +1,996 @@
+<?php
+/**
+ * @brief 工具模块
+ * @class Tools
+ * @note  后台
+ */
+class Tools extends IController implements adminAuthorization
+{
+	public $layout='admin';
+	public $checkRight = array('check' => 'all','uncheck' => array('seo_sitemaps'));
+
+	function init()
+	{
+
+	}
+
+	public function seo_sitemaps()
+	{
+		$siteMaps =  new SiteMaps();
+		$url = IUrl::getHost().IUrl::creatUrl("");
+		$date = ITime::getNow('Y-m-d');
+		$maps = array(
+			array('loc'=>$url.'sitemap_goods.xml','lastmod'=>$date),
+			array('loc'=>$url.'sitemap_article.xml','lastmod'=>$date)
+		);
+		$siteMaps->create($maps,$url.'sitemaps.xsl');
+		$this->seo_items('goods');
+		$this->seo_items('article');
+		$this->redirect('seo_sitemaps');
+	}
+	public function seo_items($item)
+	{
+		$weburl = IUrl::getHost().IUrl::creatUrl("");
+		switch($item)
+		{
+			case 'goods':
+			{
+				$url = '/site/products/id/';
+				$query        = new IQuery('goods');
+				$query->fields= "concat('$url',id) as loc,DATE_FORMAT(create_time,'%Y-%m-%d') as lastmod";
+				$query->where = "is_del = 0";
+				$items = $query->find();
+
+				//对url进行处理
+				foreach($items as $key => $val)
+				{
+					$items[$key]['loc'] = IUrl::getHost().IUrl::creatUrl($val['loc']);
+				}
+				SiteMaps::create_map($items,'sitemap_goods.xml',$weburl.'sitemaps.xsl');
+				break;
+			}
+			case 'article':
+			{
+				$url   = '/site/article_detail/id/';
+				$query = new IQuery('article');
+				$query->fields="concat('$url',id) as loc,DATE_FORMAT(create_time,'%Y-%m-%d') as lastmod";
+				$items = $query->find();
+
+				//对url进行处理
+				foreach($items as $key => $val)
+				{
+					$items[$key]['loc'] = IUrl::getHost().IUrl::creatUrl($val['loc']);
+				}
+				SiteMaps::create_map($items,'sitemap_article.xml',$weburl.'sitemaps.xsl');
+			}
+		}
+	}
+
+	//上传sql附件进行还原
+	function upload_sql()
+	{
+		$this->layout = '';
+		$this->redirect('upload_sql');
+	}
+
+	//[备份还原]数据备份动作(ajax操作)
+	function db_act_bak()
+	{
+		//要备份的数据表
+		$tableName = IReq::get('name','post');
+		$tableName = IFilter::act($tableName,"string");
+
+		//分卷大小限制(KB)
+		$partSize = 4000;
+
+		if(is_array($tableName) && isset($tableName[0]) && $tableName[0]!='')
+		{
+			$backupObj = new DBBackup($tableName);
+			$backupObj->setPartSize($partSize);   //设置分卷大小
+			$backupObj->runBak();                 //开始执行
+			$result = array(
+				'isError' => false,
+				'redirect'=> IUrl::creatUrl('/tools/db_res'),
+			);
+		}
+		else
+		{
+			$result = array(
+				'isError' => true,
+				'message' => '请选择要备份的数据表',
+			);
+		}
+		echo JSON::encode($result);
+	}
+
+	//[备份还原]下载数据库
+	function download()
+	{
+		$file = IFilter::act(IReq::get('file'),'filename');
+		$backupObj = new DBBackup;
+		$backupObj->download($file);
+	}
+
+	//[备份还原]删除备份
+	function backup_del()
+	{
+		$name = IReq::get('name');
+		$name = IFilter::act($name,'string');
+		if(!empty($name) && !is_array($name))
+			$name = array($name);
+
+		if(is_array($name) && isset($name[0]) && $name[0]!='')
+		{
+			$backupObj = new DBBackup($name);
+			$backupObj->del();
+			$this->redirect('db_res');
+		}
+		else
+		{
+			$backupObj = new DBBackup;
+			$resList = $backupObj->getList();
+			$this->setRenderData($resList);
+			$this->redirect('db_res',false);
+			Util::showMessage('请选择要删除的备份文件');
+		}
+	}
+
+	//[备份还原]导入数据(ajax)
+	function res_act()
+	{
+		$name = IFilter::act(IReq::get('name'));
+		if(is_array($name) && $name)
+		{
+			$backupObj = new DBBackup($name);
+			$backupObj->runRes();
+			$result = array(
+				'isError' => false,
+				'redirect'=> IUrl::creatUrl('/tools/db_bak'),
+			);
+		}
+		else
+		{
+			$result = array(
+				'isError' => true,
+				'message' => '请选择要导入的SQL文件',
+			);
+		}
+		echo JSON::encode($result);
+	}
+
+	//本地上传sql文件导入
+	public function localUpload()
+	{
+		if(isset($_FILES['attach']['tmp_name']) && file_exists($_FILES['attach']['tmp_name']))
+		{
+			$fileName  = $_FILES['attach']['tmp_name'];
+			$backupObj = new DBBackup();
+			$backupObj->parseSQL($fileName);
+			die('<script type="text/javascript">parent.uploadSuccess();</script>');
+		}
+		else
+		{
+			die('<script type="text/javascript">parent.uploadFail();</script>');
+		}
+	}
+
+	//[备份还原]打包下载
+	function download_pack()
+	{
+		$name = IFilter::act(IReq::get('name'));
+
+		if($name)
+		{
+			$backupObj = new DBBackup($name);
+			$fileName  = $backupObj->packDownload();
+			if($fileName === false)
+			{
+				$this->redirect('db_res',false);
+				Util::showMessage('环境不支持zip扩展');
+				exit;
+			}
+
+			$db_fileName = $backupObj->download($fileName);
+			if(is_file($db_fileName))
+			{
+				@unlink($db_fileName);
+			}
+		}
+		else
+		{
+			$this->redirect('db_res',false);
+			Util::showMessage('请选择要打包的文件');
+			exit;
+		}
+	}
+
+	//[文章]删除
+	function article_del()
+	{
+		$id = IFilter::act( IReq::get('id') ,'int' );
+		if(!empty($id))
+		{
+			$obj = new IModel('article');
+			$relationObj = new IModel('relation');
+
+			if(is_array($id) && isset($id[0]) && $id[0]!='')
+			{
+				$id_str = join(',',$id);
+				$where1 = ' id in ('.$id_str.')';
+				$where2 = ' article_id in ('.$id_str.')';
+			}
+			else
+			{
+				$where1 = 'id = '.$id;
+				$where2 = 'article_id = '.$id;
+			}
+			$obj->del($where1);               //删除商品
+			$relationObj->del($where2);       //删除关联商品表
+			$this->redirect('article_list');
+		}
+		else
+		{
+			$this->redirect('article_list',false);
+			Util::showMessage('请选择要删除的文章');
+		}
+	}
+
+	//[文章]单页
+	function article_edit()
+	{
+		$data = array();
+		$id   = IFilter::act(IReq::get('id'),'int');
+		if($id)
+		{
+			//获取文章信息
+			$articleObj       = new IModel('article');
+			$this->articleRow = $articleObj->getObj('id = '.$id);
+			if(!$this->articleRow)
+			{
+				IError::show(403,"文章信息不存在");
+			}
+		}
+		$this->redirect('article_edit');
+	}
+
+	//[文章]增加修改
+	function article_edit_act()
+	{
+		$id = IFilter::act(IReq::get('id'),'int');
+
+		$articleObj = new IModel('article');
+		$dataArray  = array(
+			'title'       => IFilter::act(IReq::get('title','post')),
+			'content'     => IFilter::act(IReq::get('content','post'),'text'),
+			'category_id' => IFilter::act(IReq::get('category_id','post'),'int'),
+			'create_time' => ITime::getDateTime(),
+			'keywords'    => IFilter::act(IReq::get('keywords','post')),
+			'description' => IFilter::act(IReq::get('description','post'),'text'),
+			'visibility'   => IFilter::act(IReq::get('visibility','post'),'int'),
+			'top'         => IFilter::act(IReq::get('top','post'),'int'),
+			'sort'        => IFilter::act(IReq::get('sort','post'),'int'),
+			'style'       => IFilter::act(IReq::get('style','post')),
+			'color'       => IFilter::act(IReq::get('color','post')),
+		);
+
+		//检查catid是否为空
+		if($dataArray['category_id'] == 0)
+		{
+			$this->articleRow = $dataArray;
+			$this->redirect('article_edit',false);
+			Util::showMessage('请选择分类');
+		}
+		$articleObj->setData($dataArray);
+
+		if($id)
+		{
+			//开始更新操作
+			$where = 'id = '.$id;
+			$is_success = $articleObj->update($where);
+		}
+		else
+		{
+			$id = $articleObj->add();
+			$is_success = $id ? true : false;
+		}
+
+		if($is_success)
+		{
+			$ralationObj = new IModel('relation');
+			$ralationObj->del('article_id = '.$id);
+
+			/*article关联商品操作*/
+			//获取新 article关联goods ID
+			$goodsId = IFilter::act(IReq::get('goods_id','post'));
+			if($goodsId)
+			{
+				foreach($goodsId as $key => $val)
+				{
+					$reData = array(
+						'goods_id'   => $val,
+						'article_id' => $id,
+					);
+					$ralationObj->setData($reData);
+					$ralationObj->add();
+				}
+			}
+		}
+		else
+		{
+			$this->articleRow = $dataArray;
+			$this->redirect('article_edit',false);
+			Util::showMessage('插入数据时发生错误');
+		}
+
+		$this->redirect('article_list');
+	}
+
+	//[公告]增加修改
+	function notice_edit_act()
+	{
+		$id = intval(IReq::get('id','post'));
+
+		$noticeObj = new IModel('announcement');
+		$dataArray  = array(
+			'title'       => IFilter::act(IReq::get('title','post')),
+			'content'     => IFilter::act(IReq::get('content','post'),'text')
+		);
+		$dataArray['time'] = date("Y-m-d H:i:s");
+		$noticeObj->setData($dataArray);
+
+		if($id)
+		{
+			$is_success = $noticeObj->update( "id={$id}" );
+		}
+		else
+		{
+			$noticeObj->add();
+		}
+		$this->redirect('notice_list');
+	}
+
+	//[公告]删除
+	function notice_del()
+	{
+		$id = IFilter::act( IReq::get('id') , 'int'  );
+		if(!is_array($id))
+		{
+			$id = array($id);
+		}
+		$id = implode(",",$id);
+
+		$noticeObj = new IModel('announcement');
+		$noticeObj->del( "id IN ({$id})" );
+		$this->redirect('notice_list');
+	}
+
+	//[公告]单页
+	function notice_edit()
+	{
+		$id = IFilter::act( IReq::get('id') , 'int'  );
+		if($id)
+		{
+			//获取文章信息
+			$noticeObj       = new IModel('announcement');
+			$this->noticeRow = $noticeObj->getObj('id = '.$id);
+			if(!$this->noticeRow)
+			{
+				IError::show(403,"信息不存在");
+			}
+		}
+
+		$this->redirect('notice_edit',false);
+	}
+	//[文章分类] 增加和修改动作
+	function cat_edit_act()
+	{
+		$id        = IFilter::act( IReq::get('id','post') );
+		$parent_id = IFilter::act( IReq::get('parent_id','post') ) ;
+
+		$catObj    = new IModel('article_category');
+		$DataArray = array(
+			'parent_id' => $parent_id,
+			'name'      => IFilter::act( IReq::get('name','post'),'string'),
+			'issys'     => IFilter::act( IReq::get('issys','post') ),
+			'sort'      => IFilter::act( IReq::get('sort','post') ),
+		);
+
+		/*开始--获取path信息*/
+		//1,修改操作
+		if($id)
+		{
+			$where  = 'id = '.$id;
+			$catRow = $catObj->getObj($where);
+			if($catRow['parent_id']==$parent_id)
+			{
+				$isMoveNode = false;
+				$DataArray['path'] = $catRow['path'];
+			}
+			else
+				$isMoveNode = true;
+
+			$localId = $id;
+		}
+		//2,新增操作
+		else
+		{
+			$max_id  = $catObj->getObj('','max(id) as max_id');
+			$localId = $max_id['max_id'] ? $max_id['max_id']+1 : 1;
+		}
+
+		//如果不存在path数据时,计算path数据
+		if(!isset($DataArray['path']))
+		{
+			//获取父节点的path路径
+			if($parent_id==0)
+				$DataArray['path'] = ','.$localId.',';
+			else
+			{
+				$where     = 'id = '.$parent_id;
+				$parentRow = $catObj->getObj($where);
+				$DataArray['path'] = $parentRow['path'].$localId.',';
+			}
+		}
+		/*结束--获取path信息*/
+		//设置数据值
+		$catObj->setData($DataArray);
+
+		//1,修改操作
+		if($id)
+		{
+			//节点移动
+			if($isMoveNode == true)
+			{
+				if($parentRow['path']!=null && strpos($parentRow['path'],','.$id.',')!==false)
+				{
+					$this->catRow = array(
+						'parent_id' => $DataArray['parent_id'],
+						'name'      => $DataArray['name'],
+						'issys'     => $DataArray['issys'],
+						'sort'      => $DataArray['sort'],
+						'id'        => $id,
+					);
+					$this->redirect('article_cat_edit',false);
+					Util::showMessage('不能该节点移动到其子节点的位置上');
+				}
+				else
+				{
+					//其子节点批量移动
+					$childObj = new IModel('article_category');
+					$oldPath  = $catRow['path'];
+					$newPath  = $DataArray['path'];
+
+					$where = 'path like "'.$oldPath.'%"';
+					$updateData = array(
+						'path' => "replace(path,'".$oldPath."','".$newPath."')",
+					);
+					$childObj->setData($updateData);
+					$childObj->update($where,array('path'));
+				}
+			}
+			$where = 'id = '.$id;
+			$catObj->update($where);
+		}
+		//2,新增操作
+		else
+			$catObj->add();
+
+		$this->redirect('article_cat_list');
+	}
+
+	//[文章分类] 增加修改单页
+	function cat_edit()
+	{
+		$data = array();
+		$id = IFilter::act( IReq::get('id'),'int' );
+
+		if($id)
+		{
+			$catObj = new IModel('article_category');
+			$where  = 'id = '.$id;
+			$data = $catObj->getObj($where);
+			if(count($data)>0)
+			{
+				$this->catRow = $data;
+				$this->redirect('article_cat_edit',false);
+			}
+		}
+		if(count($data)==0)
+		{
+			$this->redirect('article_cat_list');
+		}
+	}
+
+	//[文章分类] 删除
+	function cat_del()
+	{
+		$id = IFilter::act( IReq::get('id'),'int' );
+		$catObj = new IModel('article_category');
+
+		//是否执行删除检测值
+		$isCheck=true;
+
+		//检测是否有parent_id 为 $id
+		$where   = 'parent_id = '.$id;
+		$catData = $catObj->getObj($where);
+		if(!empty($catData))
+		{
+			$isCheck=false;
+			$message='此分类下还有子分类';
+		}
+
+		//检测是否有article的category_id 为 $id
+		else
+		{
+			$articleObj = new IModel('article');
+			$where = 'category_id = '.$id;
+			$catData = $articleObj->getObj($where);
+
+			if(!empty($catData))
+			{
+				$isCheck=false;
+				$message='此分类下还有文章';
+			}
+		}
+
+		if($isCheck == false)
+		{
+			$message = isset($message) ? $message : '删除失败';
+			$this->redirect('article_cat_list',false);
+			Util::showMessage($message);
+		}
+		else
+		{
+			$where  = 'id = '.$id;
+			$result = $catObj->del($where);
+			$this->redirect('article_cat_list');
+		}
+	}
+
+	//[广告位] 删除
+	function ad_position_del()
+	{
+		$id = IFilter::act( IReq::get('id') , 'int' );
+		if(!empty($id))
+		{
+			$obj = new IModel('ad_position');
+			if(is_array($id) && isset($id[0]) && $id[0]!='')
+			{
+				$id_str = join(',',$id);
+				$where = ' id in ('.$id_str.')';
+			}
+			else
+			{
+				$where = 'id = '.$id;
+			}
+			$obj->del($where);
+			$this->redirect('ad_position_list');
+		}
+		else
+		{
+			$this->redirect('ad_position_list',false);
+			Util::showMessage('请选择要删除的广告位');
+		}
+	}
+
+	//[广告位] 添加修改 (单页)
+	function ad_position_edit()
+	{
+		$id   = IFilter::act( IReq::get('id'),'int' );
+		$name = IFilter::act( IReq::get('name'),'text' );
+
+		$obj = new IModel('ad_position');
+		if($name)
+		{
+			$positionRow = $obj->getObj('name="'.$name.'"');
+		}
+		else if($id)
+		{
+			$positionRow = $obj->getObj('id = '.$id);
+		}
+		$this->positionRow = isset($positionRow) && $positionRow ? $positionRow : array('name' => $name);
+		$this->redirect('ad_position_edit',false);
+	}
+
+	//[广告位] 添加和修改动作
+	function ad_position_edit_act()
+	{
+		$id = IFilter::act( IReq::get('id') );
+
+		$obj = new IModel('ad_position');
+
+		$dataArray = array(
+			'name'         => IFilter::act( IReq::get('name','post') ,'string' ),
+			'width'        => IFilter::act( IReq::get('width','post') ),
+			'height'       => IFilter::act( IReq::get('height','post') ),
+			'fashion'      => IFilter::act( IReq::get('fashion','post'),'int' ),
+			'status'       => IFilter::act( IReq::get('status','post'),'int' )
+		);
+		$obj->setData($dataArray);
+
+		if($id)
+		{
+			$where = 'id = '.$id;
+			$result = $obj->update($where);
+		}
+		else
+			$result = $obj->add();
+
+		$this->redirect('ad_position_list');
+	}
+
+	//[广告] 删除
+	function ad_del()
+	{
+		$id = IFilter::act( IReq::get('id') , 'int' );
+		if(!empty($id))
+		{
+			$obj = new IModel('ad_manage');
+			if(is_array($id) && isset($id[0]) && $id[0]!='')
+			{
+				$id_str = join(',',$id);
+				$where = ' id in ('.$id_str.')';
+			}
+			else
+			{
+				$where = 'id = '.$id;
+			}
+			$obj->del($where);
+			$this->redirect('ad_list');
+		}
+		else
+		{
+			$this->redirect('ad_list',false);
+			Util::showMessage('请选择要删除的广告');
+		}
+	}
+
+	//[广告] 添加修改 (单页)
+	function ad_edit()
+	{
+		$id          = IFilter::act(IReq::get('id'),'int');
+		$positionId  = IFilter::act(IReq::get('pid'),'int');
+		$this->adRow = array('position_id' => $positionId);
+		if($id)
+		{
+			$obj = new IModel('ad_manage');
+			$this->adRow = $obj->getObj('id = '.$id);
+		}
+		$this->redirect('ad_edit');
+	}
+
+	//[广告] 添加和修改动作
+	function ad_edit_act()
+	{
+		$id      = IFilter::act( IReq::get('id'),'int' );
+		$content = IReq::get('content');
+
+		//附件上传
+		if(isset($_FILES) && $_FILES)
+		{
+			$upType = isset($_FILES['img']) ? array("gif","png","jpg") : array('flv','swf');
+			$upObj  = new IUpload("5000",$upType);
+			$dir    = IWeb::$app->config['upload'].'/'.date('Y')."/".date('m')."/".date('d');
+			$upObj->setDir($dir);
+			$upState = $upObj->execute();
+			$result = $upState ? current($upState) : "";
+			if($result && isset($result[0]['flag']) && $result[0]['flag'] == 1)
+			{
+				//最终附件路径
+				$content = $dir.'/'.$result[0]['name'];
+			}
+			else if(!$content)
+			{
+				IError::show(403,"请上传正确的附件数据");
+			}
+		}
+
+		$adObj = new IModel('ad_manage');
+		$dataArray = array(
+			'content'     => IFilter::addSlash($content),
+			'name'        => IFilter::act(IReq::get('name')),
+			'position_id' => IFilter::act(IReq::get('position_id')),
+			'type'        => IFilter::act(IReq::get('type')),
+			'link'        => IFilter::addSlash(IReq::get('link')),
+			'start_time'  => IFilter::act(IReq::get('start_time')),
+			'end_time'    => IFilter::act(IReq::get('end_time')),
+			'description' => IFilter::act(IReq::get('description'),'text'),
+			'order'       => IFilter::act(IReq::get('order'),'int'),
+			'goods_cat_id'=> IFilter::act(IReq::get('goods_cat_id'),'int'),
+		);
+
+		$adObj->setData($dataArray);
+		if($id)
+		{
+			$where = 'id = '.$id;
+			$adObj->update($where);
+		}
+		else
+		{
+			$adObj->add();
+		}
+		$this->redirect("ad_list");
+	}
+
+	function help_list()
+	{
+		$query = new IQuery("help AS help");
+		$query->join = "LEFT JOIN help_category AS cat ON help.cat_id=cat.id";
+		if(IReq::get('cat_id')!==null)
+		{
+			$query->where = "help.cat_id = ".intval(IReq::get('cat_id'));
+		}
+		$query->fields = "help.*,cat.name AS cat_name";
+		$query->order = "help.`sort` ASC,help.id DESC";
+		$query->page = isset($_GET['page'])?$_GET['page']:1;
+		$this->query = $query;
+		$this->list = $query->find();
+		$this->redirect("help_list");
+	}
+
+	function help_edit()
+	{
+		$id = intval(IReq::get("id"));
+		$this->help_row=array('id'=>$id,'name'=>'','cat_id'=>0,'content'=>"",'sort'=>0);
+		if($id)
+		{
+			$this->help_row=SiteHelp::get_help_by_id($id);
+			if(!isset($this->help_row[$id]))
+			{
+				$this->redirect("help_list",true);
+				Util::showMessage( "没有这条记录" );
+			}
+			$this->help_row=$this->help_row[$id];
+		}
+		$this->redirect("help_edit");
+	}
+
+	function help_edit_act()
+	{
+		//数据在Sitemap里过滤了
+		$data['id'] = IReq::get("id");
+		$data['cat_id'] = IReq::get('cat_id') ;
+		$data['name'] = IReq::get('name');
+		$data['sort'] = IReq::get("sort");
+		$data['content'] = IReq::get("content");
+
+		$re = SiteHelp::help_edit($data);
+		if($re['flag']===true)
+		{
+			$this->redirect("help_list");
+		}
+		else
+		{
+			$this->redirect("help_edit",false);
+			Util::showMessage($re['data']);
+		}
+	}
+
+	function help_del()
+	{
+		$id = IReq::get("id");
+		if($id===null)
+		{
+			$this->redirect('/tools/help_list');
+		}
+		$re = SiteHelp::help_del($id);
+
+		if($re['flag']===true)
+		{
+			$this->redirect('/tools/help_list');
+		}
+		else
+		{
+			$this->redirect('/tools/help_list');
+		}
+	}
+	function help_cat_edit()
+	{
+		$id=IReq::get("id");
+		$this->cat_row=array('name'=>'','position_left'=>0,'position_foot'=>0,'sort'=>'');
+		if($id!==null)
+		{
+			$this->cat_row=SiteHelp::get_cat_by_id($id);
+			if(!isset($this->cat_row[$id]))
+				Util::showMessage( "没有这条记录" );
+			$this->cat_row=$this->cat_row[$id];
+		}
+		$this->redirect("help_cat_edit");
+	}
+
+	function help_cat_edit_act()
+	{
+		$data["id"] = IReq::get("id","post");
+		$data["name"] = IReq::get("name","post");
+		$data["position_left"] = IReq::get("position_left","post");
+		$data["position_foot"] = IReq::get("position_foot","post");
+		$data["sort"] = IReq::get("sort");
+
+		$re=SiteHelp::cat_edit($data);
+		if($re['flag']!==true)
+		{
+			Util::showMessage($re['data']);
+			die();
+		}
+		$this->redirect('help_cat_list');
+	}
+
+	function help_cat_position()
+	{
+		$id = IReq::get("id");
+		$position = IReq::get("position");
+		$value = IReq::get("value");
+		if($id===null || $position===null || $value===null)
+			die("错误的参数");
+
+		$re=SiteHelp::mod_cat_position($id,$position,$value);
+		if($re['flag']===false)
+			die($re['data']);
+		die("设置成功");
+	}
+
+	//帮助分类删除
+	function help_cat_del()
+	{
+		$id = IReq::get('id');
+		if($id===null)
+			die("错误的参数");
+		$re = SiteHelp::del_cat($id);
+		if($re['flag']===false)
+			die($re['data']);
+		die("success");
+	}
+
+	//[关键词管理]添加
+	function keyword_add()
+	{
+		$word  = IFilter::act(IReq::get('word'));
+		$hot   = intval(IReq::get('hot'));
+		$order = IReq::get('order') ? intval(IReq::get('order')) : 99;
+
+		$re = keywords::add($word ,$hot,$order);
+
+		if($re['flag']==true)
+		{
+			$this->redirect('keyword_list');
+		}
+		else
+		{
+			$this->redirect('keyword_edit');
+			Util::showMessage($re['data']);
+		}
+	}
+
+	//[关键词管理]删除
+	function keyword_del()
+	{
+		$id = IFilter::act(IReq::get('id'));
+		if(!empty($id))
+		{
+			$keywordObj = new IModel('keyword');
+			if(is_array($id))
+			{
+				$ids = '"'.join('","',$id).'"';
+				$keywordObj->del('word in ('.$ids.')');
+			}
+			else
+			{
+				$keywordObj->del('word = "'.$id.'"');
+			}
+		}
+		else
+		{
+			$message = '请选择要删除的关键词';
+		}
+
+		if(isset($message))
+		{
+			$this->redirect('keyword_list',false);
+			Util::showMessage($message);
+		}
+		else
+		{
+			$this->redirect('keyword_list');
+		}
+	}
+
+	//[关键词管理]设置hot
+	function keyword_hot()
+	{
+		$id  = IFilter::act(IReq::get('id'));
+
+		$keywordObj = new IModel('keyword');
+		$dataArray  = array('hot' => 'abs(hot - 1)');
+		$keywordObj->setData($dataArray);
+		$is_result  = $keywordObj->update('word = "'.$id.'"','hot');
+
+		$keywordRow = $keywordObj->getObj('word = "'.$id.'"');
+		if($is_result!==false)
+		{
+			echo JSON::encode(array('isError' => false,'hot' => $keywordRow['hot']));
+		}
+		else
+		{
+			echo JSON::encode(array('isError'=>true,'message'=>'设置失败'));
+		}
+	}
+
+	//[关键词管理]统计商品数量
+	function keyword_account()
+	{
+		$word = IFilter::act(IReq::get('id'));
+		if(!$word)
+		{
+			$this->redirect('keyword_list',false);
+			Util::showMessage('请选择要同步的关键词');
+		}
+
+		$keywordObj = new IModel('keyword');
+		foreach($word as $key => $val)
+		{
+			//获取各个关键词的管理商品数量
+			$resultCount = keywords::count($val);
+			$dataArray = array(
+				'goods_nums' => $resultCount,
+			);
+			$keywordObj->setData($dataArray);
+			$keywordObj->update('word = "'.$val.'"');
+		}
+		$this->redirect('keyword_list');
+	}
+	//关键词排序
+	function keyword_order()
+	{
+		$word  = IFilter::act(IReq::get('id'));
+		$order = IReq::get('order') ? intval(IReq::get('order')) : 99;
+
+		$keywordObj = new IModel('keyword');
+		$dataArray = array('order' => $order);
+		$keywordObj->setData($dataArray);
+		$is_success = $keywordObj->update('word = "'.$word.'"');
+
+		if($is_success === false)
+		{
+			$result = array(
+				'isError' => true,
+				'message' => '更新排序失败',
+			);
+		}
+		else
+		{
+			$result = array(
+				'isError' => false,
+			);
+		}
+		echo JSON::encode($result);
+	}
+
+	/**
+	 * 查询删除
+	 */
+	function search_del()
+	{
+		$id = IFilter::act(IReq::get('id'),'int');
+
+		//生成search对象
+	    $tb_search = new IModel('search');
+	    if(!empty($id))
+		{
+			if(is_array($id) && isset($id[0]) && $id[0]!='')
+			{
+				$id_str = join(',',$id);
+				$where = ' id in ('.$id_str.')';
+			}
+			else
+			{
+				$where = 'id = '.$id;
+			}
+			$tb_search->del($where);
+		}
+		else
+		{
+			Util::showMessage('请选择要删除的数据');
+		}
+		$this->redirect("search_list");
+	}
+}

+ 920 - 0
src/controllers/ucenter.php

@@ -0,0 +1,920 @@
+<?php
+/**
+ * @brief 用户中心模块
+ * @class Ucenter
+ * @note  前台
+ */
+class Ucenter extends IController implements userAuthorization
+{
+	public $layout = 'ucenter';
+
+	public function init()
+	{
+
+	}
+    public function index()
+    {
+    	//获取用户基本信息
+		$user = Api::run('getMemberInfo',$this->user['user_id']);
+
+		//获取用户各项统计数据
+		$statistics = Api::run('getMemberTongJi',$this->user['user_id']);
+
+		//获取用户站内信条数
+		$msgObj = new Mess($this->user['user_id']);
+		$msgNum = $msgObj->needReadNum();
+
+		//获取用户代金券
+		$propIds = trim($user['prop'],',');
+		$propIds = $propIds ? $propIds : 0;
+		$propData= Api::run('getPropTongJi',$propIds);
+
+		$this->setRenderData(array(
+			"user"       => $user,
+			"statistics" => $statistics,
+			"msgNum"     => $msgNum,
+			"propData"   => $propData,
+		));
+
+        $this->initPayment();
+        $this->redirect('index');
+    }
+
+	//[用户头像]上传
+	function user_ico_upload()
+	{
+		$result = array(
+			'isError' => true,
+		);
+
+		if(isset($_FILES['attach']['name']) && $_FILES['attach']['name'] != '')
+		{
+			$photoObj = new PhotoUpload();
+			$photo    = $photoObj->run();
+
+			if(isset($photo['attach']['img']) && $photo['attach']['img'])
+			{
+				$user_id   = $this->user['user_id'];
+				$user_obj  = new IModel('user');
+				$dataArray = array(
+					'head_ico' => $photo['attach']['img'],
+				);
+				$user_obj->setData($dataArray);
+				$where  = 'id = '.$user_id;
+				$isSuss = $user_obj->update($where);
+
+				if($isSuss !== false)
+				{
+					$result['isError'] = false;
+					$result['data'] = IUrl::creatUrl().$photo['attach']['img'];
+					ISafe::set('head_ico',$dataArray['head_ico']);
+				}
+				else
+				{
+					$result['message'] = '上传失败';
+				}
+			}
+			else
+			{
+				$result['message'] = '上传失败';
+			}
+		}
+		else
+		{
+			$result['message'] = '请选择图片';
+		}
+		echo '<script type="text/javascript">parent.callback_user_ico('.JSON::encode($result).');</script>';
+	}
+
+    /**
+     * @brief 我的订单列表
+     */
+    public function order()
+    {
+		header("Cache-Control: no-store, no-cache, must-revalidate");
+		header("Cache-Control: post-check=0, pre-check=0",false);
+        $this->initPayment();
+        $this->redirect('order');
+
+    }
+    /**
+     * @brief 初始化支付方式
+     */
+    private function initPayment()
+    {
+        $payment = new IQuery('payment');
+        $payment->fields = 'id,name,type';
+        $payments = $payment->find();
+        $items = array();
+        foreach($payments as $pay)
+        {
+            $items[$pay['id']]['name'] = $pay['name'];
+            $items[$pay['id']]['type'] = $pay['type'];
+        }
+        $this->payments = $items;
+    }
+    /**
+     * @brief 订单详情
+     * @return String
+     */
+    public function order_detail()
+    {
+        $id = IFilter::act(IReq::get('id'),'int');
+
+        $orderObj = new order_class();
+        $this->order_info = $orderObj->getOrderShow($id,$this->user['user_id']);
+
+        if(!$this->order_info)
+        {
+        	IError::show(403,'订单信息不存在');
+        }
+        $orderStatus = Order_Class::getOrderStatus($this->order_info);
+        $this->setRenderData(array('orderStatus' => $orderStatus));
+        $this->redirect('order_detail',false);
+    }
+
+    //操作订单状态
+	public function order_status()
+	{
+		$op    = IFilter::act(IReq::get('op'));
+		$id    = IFilter::act( IReq::get('order_id'),'int' );
+		$model = new IModel('order');
+
+		switch($op)
+		{
+			case "cancel":
+			{
+				$model->setData(array('status' => 3));
+				if($model->update("id = ".$id." and distribution_status = 0 and status = 1 and user_id = ".$this->user['user_id']))
+				{
+					order_class::resetOrderProp($id);
+				}
+				$this->redirect("order_detail/id/$id");
+			}
+			break;
+
+			case "confirm":
+			{
+				$model->setData(array('status' => 5,'completion_time' => ITime::getDateTime()));
+				if($model->update("id = ".$id." and distribution_status = 1 and user_id = ".$this->user['user_id']))
+				{
+					$orderRow = $model->getObj('id = '.$id);
+
+					//确认收货后进行支付
+					Order_Class::updateOrderStatus($orderRow['order_no']);
+
+		    		//增加用户评论商品机会
+		    		Order_Class::addGoodsCommentChange($id);
+
+		    		//确认收货以后直接跳转到评论页面
+		    		$this->redirect('evaluation');
+				}
+			}
+			break;
+		}
+	}
+    /**
+     * @brief 我的地址
+     */
+    public function address()
+    {
+		//取得自己的地址
+		$query = new IQuery('address');
+        $query->where = 'user_id = '.$this->user['user_id'];
+		$address = $query->find();
+		$areas   = array();
+
+		if($address)
+		{
+			foreach($address as $ad)
+			{
+				$temp = area::name($ad['province'],$ad['city'],$ad['area']);
+				if(isset($temp[$ad['province']]) && isset($temp[$ad['city']]) && isset($temp[$ad['area']]))
+				{
+					$areas[$ad['province']] = $temp[$ad['province']];
+					$areas[$ad['city']]     = $temp[$ad['city']];
+					$areas[$ad['area']]     = $temp[$ad['area']];
+				}
+			}
+		}
+
+		$this->areas = $areas;
+		$this->address = $address;
+        $this->redirect('address');
+    }
+    /**
+     * @brief 收货地址管理
+     */
+	public function address_edit()
+	{
+		$id          = IFilter::act(IReq::get('id'),'int');
+		$accept_name = IFilter::act(IReq::get('accept_name'),'name');
+		$province    = IFilter::act(IReq::get('province'),'int');
+		$city        = IFilter::act(IReq::get('city'),'int');
+		$area        = IFilter::act(IReq::get('area'),'int');
+		$address     = IFilter::act(IReq::get('address'));
+		$zip         = IFilter::act(IReq::get('zip'),'zip');
+		$telphone    = IFilter::act(IReq::get('telphone'),'phone');
+		$mobile      = IFilter::act(IReq::get('mobile'),'mobile');
+		$default     = IReq::get('is_default')!= 1 ? 0 : 1;
+        $user_id     = $this->user['user_id'];
+
+		$model = new IModel('address');
+		$data  = array('user_id'=>$user_id,'accept_name'=>$accept_name,'province'=>$province,'city'=>$city,'area'=>$area,'address'=>$address,'zip'=>$zip,'telphone'=>$telphone,'mobile'=>$mobile,'is_default'=>$default);
+
+        //如果设置为首选地址则把其余的都取消首选
+        if($default==1)
+        {
+            $model->setData(array('is_default' => 0));
+            $model->update("user_id = ".$this->user['user_id']);
+        }
+
+		$model->setData($data);
+
+		if($id == '')
+		{
+			$model->add();
+		}
+		else
+		{
+			$model->update('id = '.$id);
+		}
+		$this->redirect('address');
+	}
+    /**
+     * @brief 收货地址删除处理
+     */
+	public function address_del()
+	{
+		$id = IFilter::act( IReq::get('id'),'int' );
+		$model = new IModel('address');
+		$model->del('id = '.$id.' and user_id = '.$this->user['user_id']);
+		$this->redirect('address');
+	}
+    /**
+     * @brief 设置默认的收货地址
+     */
+    public function address_default()
+    {
+        $id = IFilter::act( IReq::get('id'),'int' );
+        $default = IFilter::act(IReq::get('is_default'));
+        $model = new IModel('address');
+        if($default == 1)
+        {
+            $model->setData(array('is_default' => 0));
+            $model->update("user_id = ".$this->user['user_id']);
+        }
+        $model->setData(array('is_default' => $default));
+        $model->update("id = ".$id." and user_id = ".$this->user['user_id']);
+        $this->redirect('address');
+    }
+    /**
+     * @brief 退款申请页面
+     */
+    public function refunds_update()
+    {
+        $order_goods_id = IFilter::act( IReq::get('order_goods_id'),'int' );
+        $order_id       = IFilter::act( IReq::get('order_id'),'int' );
+        $user_id        = $this->user['user_id'];
+        $content        = IFilter::act(IReq::get('content'),'text');
+        $message        = '';
+
+        if(!$content || !$order_goods_id)
+        {
+        	$message = "请填写退款理由和选择要退款的商品";
+	        $this->redirect('refunds',false);
+	        Util::showMessage($message);
+        }
+
+        $orderDB      = new IModel('order');
+        $orderRow     = $orderDB->getObj("id = ".$order_id." and user_id = ".$user_id);
+        $refundResult = Order_Class::isRefundmentApply($orderRow,$order_goods_id);
+
+        //判断退款申请是否有效
+        if($refundResult === true)
+        {
+			//退款单数据
+    		$updateData = array(
+				'order_no'       => $orderRow['order_no'],
+				'order_id'       => $order_id,
+				'user_id'        => $user_id,
+				'time'           => ITime::getDateTime(),
+				'content'        => $content,
+				'seller_id'      => $orderRow['seller_id'],
+				'order_goods_id' => join(",",$order_goods_id),
+			);
+
+    		//写入数据库
+    		$refundsDB = new IModel('refundment_doc');
+    		$refundsDB->setData($updateData);
+    		$refundsDB->add();
+
+    		$this->redirect('refunds');
+        }
+        else
+        {
+        	$message = $refundResult;
+	        $this->redirect('refunds',false);
+	        Util::showMessage($message);
+        }
+    }
+    /**
+     * @brief 退款申请删除
+     */
+    public function refunds_del()
+    {
+        $id = IFilter::act( IReq::get('id'),'int' );
+        $model = new IModel("refundment_doc");
+        $result= $model->del("id = ".$id." and pay_status = 0 and user_id = ".$this->user['user_id']);
+        $this->redirect('refunds');
+    }
+    /**
+     * @brief 查看退款申请详情
+     */
+    public function refunds_detail()
+    {
+        $id = IFilter::act( IReq::get('id'),'int' );
+        $refundDB = new IModel("refundment_doc");
+        $refundRow = $refundDB->getObj("id = ".$id." and user_id = ".$this->user['user_id']);
+        if($refundRow)
+        {
+        	//获取商品信息
+        	$orderGoodsDB   = new IModel('order_goods');
+        	$orderGoodsList = $orderGoodsDB->query("id in (".$refundRow['order_goods_id'].")");
+        	if($orderGoodsList)
+        	{
+        		$refundRow['goods'] = $orderGoodsList;
+        		$this->data = $refundRow;
+        	}
+        	else
+        	{
+	        	$this->redirect('refunds',false);
+	        	Util::showMessage("没有找到要退款的商品");
+        	}
+        	$this->redirect('refunds_detail');
+        }
+        else
+        {
+        	$this->redirect('refunds',false);
+        	Util::showMessage("退款信息不存在");
+        }
+    }
+    /**
+     * @brief 查看退款申请详情
+     */
+	public function refunds_edit()
+	{
+		$order_id = IFilter::act(IReq::get('order_id'),'int');
+		if($order_id)
+		{
+			$orderDB  = new IModel('order');
+			$orderRow = $orderDB->getObj('id = '.$order_id.' and user_id = '.$this->user['user_id']);
+			if($orderRow)
+			{
+				$this->orderRow = $orderRow;
+				$this->redirect('refunds_edit');
+				return;
+			}
+		}
+		$this->redirect('refunds');
+	}
+
+    /**
+     * @brief 建议中心
+     */
+    public function complain_edit()
+    {
+        $id = IFilter::act( IReq::get('id'),'int' );
+        $title = IFilter::act(IReq::get('title'),'string');
+        $content = IFilter::act(IReq::get('content'),'string' );
+        $user_id = $this->user['user_id'];
+        $model = new IModel('suggestion');
+        $model->setData(array('user_id'=>$user_id,'title'=>$title,'content'=>$content,'time'=>ITime::getDateTime()));
+        if($id =='')
+        {
+            $model->add();
+        }
+        else
+        {
+            $model->update('id = '.$id.' and user_id = '.$this->user['user_id']);
+        }
+        $this->redirect('complain');
+    }
+    //站内消息
+    public function message()
+    {
+    	$msgObj = new Mess($this->user['user_id']);
+    	$msgIds = $msgObj->getAllMsgIds();
+    	$msgIds = $msgIds ? $msgIds : 0;
+		$this->setRenderData(array('msgIds' => $msgIds,'msgObj' => $msgObj));
+    	$this->redirect('message');
+    }
+    /**
+     * @brief 删除消息
+     * @param int $id 消息ID
+     */
+    public function message_del()
+    {
+        $id = IFilter::act( IReq::get('id') ,'int' );
+        $msg = new Mess($this->user['user_id']);
+        $msg->delMessage($id);
+        $this->redirect('message');
+    }
+    public function message_read()
+    {
+        $id = IFilter::act( IReq::get('id'),'int' );
+        $msg = new Mess($this->user['user_id']);
+        echo $msg->writeMessage($id,1);
+    }
+
+    //[修改密码]修改动作
+    function password_edit()
+    {
+    	$user_id    = $this->user['user_id'];
+
+    	$fpassword  = IReq::get('fpassword');
+    	$password   = IReq::get('password');
+    	$repassword = IReq::get('repassword');
+
+    	$userObj    = new IModel('user');
+    	$where      = 'id = '.$user_id;
+    	$userRow    = $userObj->getObj($where);
+
+		if(!preg_match('|\w{6,32}|',$password))
+		{
+			$message = '密码格式不正确,请重新输入';
+		}
+    	else if($password != $repassword)
+    	{
+    		$message  = '二次密码输入的不一致,请重新输入';
+    	}
+    	else if(md5($fpassword) != $userRow['password'])
+    	{
+    		$message  = '原始密码输入错误';
+    	}
+    	else
+    	{
+    		$passwordMd5 = md5($password);
+	    	$dataArray = array(
+	    		'password' => $passwordMd5,
+	    	);
+
+	    	$userObj->setData($dataArray);
+	    	$result  = $userObj->update($where);
+	    	if($result)
+	    	{
+	    		ISafe::set('user_pwd',$passwordMd5);
+	    		$message = '密码修改成功';
+	    	}
+	    	else
+	    	{
+	    		$message = '密码修改失败';
+	    	}
+		}
+
+    	$this->redirect('password',false);
+    	Util::showMessage($message);
+    }
+
+    //[个人资料]展示 单页
+    function info()
+    {
+    	$user_id = $this->user['user_id'];
+
+    	$userObj       = new IModel('user');
+    	$where         = 'id = '.$user_id;
+    	$this->userRow = $userObj->getObj($where);
+
+    	$memberObj       = new IModel('member');
+    	$where           = 'user_id = '.$user_id;
+    	$this->memberRow = $memberObj->getObj($where);
+    	$this->redirect('info');
+    }
+
+    //[个人资料] 修改 [动作]
+    function info_edit_act()
+    {
+		$email     = IFilter::act( IReq::get('email'),'string');
+		$mobile    = IFilter::act( IReq::get('mobile'),'string');
+
+    	$user_id   = $this->user['user_id'];
+    	$memberObj = new IModel('member');
+    	$where     = 'user_id = '.$user_id;
+
+		if($email)
+		{
+			$memberRow = $memberObj->getObj('user_id != '.$user_id.' and email = "'.$email.'"');
+			if($memberRow)
+			{
+				IError::show('邮箱已经被注册');
+			}
+		}
+
+		if($mobile)
+		{
+			$memberRow = $memberObj->getObj('user_id != '.$user_id.' and mobile = "'.$mobile.'"');
+			if($memberRow)
+			{
+				IError::show('手机已经被注册');
+			}
+		}
+
+    	//地区
+    	$province = IFilter::act( IReq::get('province','post') ,'string');
+    	$city     = IFilter::act( IReq::get('city','post') ,'string' );
+    	$area     = IFilter::act( IReq::get('area','post') ,'string' );
+    	$areaArr  = array_filter(array($province,$city,$area));
+
+    	$dataArray       = array(
+    		'email'        => $email,
+    		'true_name'    => IFilter::act( IReq::get('true_name') ,'string'),
+    		'sex'          => IFilter::act( IReq::get('sex'),'int' ),
+    		'birthday'     => IFilter::act( IReq::get('birthday') ),
+    		'zip'          => IFilter::act( IReq::get('zip') ,'string' ),
+    		'qq'           => IFilter::act( IReq::get('qq') , 'string' ),
+    		'contact_addr' => IFilter::act( IReq::get('contact_addr'), 'string'),
+    		'mobile'       => $mobile,
+    		'telephone'    => IFilter::act( IReq::get('telephone'),'string'),
+    		'area'         => $areaArr ? ",".join(",",$areaArr)."," : "",
+    	);
+
+    	$memberObj->setData($dataArray);
+    	$memberObj->update($where);
+    	$this->info();
+    }
+
+    //[账户余额] 展示[单页]
+    function withdraw()
+    {
+    	$user_id   = $this->user['user_id'];
+
+    	$memberObj = new IModel('member','balance');
+    	$where     = 'user_id = '.$user_id;
+    	$this->memberRow = $memberObj->getObj($where);
+    	$this->redirect('withdraw');
+    }
+
+	//[账户余额] 提现动作
+    function withdraw_act()
+    {
+    	$user_id = $this->user['user_id'];
+    	$amount  = IFilter::act( IReq::get('amount','post') ,'float' );
+    	$message = '';
+
+    	$dataArray = array(
+    		'name'   => IFilter::act( IReq::get('name','post') ,'string'),
+    		'note'   => IFilter::act( IReq::get('note','post'), 'string'),
+			'amount' => $amount,
+			'user_id'=> $user_id,
+			'time'   => ITime::getDateTime(),
+    	);
+
+		$mixAmount = 0;
+		$memberObj = new IModel('member');
+		$where     = 'user_id = '.$user_id;
+		$memberRow = $memberObj->getObj($where,'balance');
+
+		//提现金额范围
+		if($amount <= $mixAmount)
+		{
+			$message = '提现的金额必须大于'.$mixAmount.'元';
+		}
+		else if($amount > $memberRow['balance'])
+		{
+			$message = '提现的金额不能大于您的帐户余额';
+		}
+		else
+		{
+	    	$obj = new IModel('withdraw');
+	    	$obj->setData($dataArray);
+	    	$obj->add();
+	    	$this->redirect('withdraw');
+		}
+
+		if($message != '')
+		{
+			$this->memberRow = array('balance' => $memberRow['balance']);
+			$this->withdrawRow = $dataArray;
+			$this->redirect('withdraw',false);
+			Util::showMessage($message);
+		}
+    }
+
+    //[账户余额] 提现详情
+    function withdraw_detail()
+    {
+    	$user_id = $this->user['user_id'];
+
+    	$id  = IFilter::act( IReq::get('id'),'int' );
+    	$obj = new IModel('withdraw');
+    	$where = 'id = '.$id.' and user_id = '.$user_id;
+    	$this->withdrawRow = $obj->getObj($where);
+    	$this->redirect('withdraw_detail');
+    }
+
+    //[提现申请] 取消
+    function withdraw_del()
+    {
+    	$id = IFilter::act( IReq::get('id'),'int');
+    	if($id)
+    	{
+    		$dataArray   = array('is_del' => 1);
+    		$withdrawObj = new IModel('withdraw');
+    		$where = 'id = '.$id.' and user_id = '.$this->user['user_id'];
+    		$withdrawObj->setData($dataArray);
+    		$withdrawObj->update($where);
+    	}
+    	$this->redirect('withdraw');
+    }
+
+    //[余额交易记录]
+    function account_log()
+    {
+    	$user_id   = $this->user['user_id'];
+
+    	$memberObj = new IModel('member');
+    	$where     = 'user_id = '.$user_id;
+    	$this->memberRow = $memberObj->getObj($where);
+    	$this->redirect('account_log');
+    }
+
+    //[收藏夹]备注信息
+    function edit_summary()
+    {
+    	$user_id = $this->user['user_id'];
+
+    	$id      = IFilter::act( IReq::get('id'),'int' );
+    	$summary = IFilter::act( IReq::get('summary'),'string' );
+
+    	//ajax返回结果
+    	$result  = array(
+    		'isError' => true,
+    	);
+
+    	if(!$id)
+    	{
+    		$result['message'] = '收藏夹ID值丢失';
+    	}
+    	else if(!$summary)
+    	{
+    		$result['message'] = '请填写正确的备注信息';
+    	}
+    	else
+    	{
+	    	$favoriteObj = new IModel('favorite');
+	    	$where       = 'id = '.$id.' and user_id = '.$user_id;
+
+	    	$dataArray   = array(
+	    		'summary' => $summary,
+	    	);
+
+	    	$favoriteObj->setData($dataArray);
+	    	$is_success = $favoriteObj->update($where);
+
+	    	if($is_success === false)
+	    	{
+	    		$result['message'] = '更新信息错误';
+	    	}
+	    	else
+	    	{
+	    		$result['isError'] = false;
+	    	}
+    	}
+    	echo JSON::encode($result);
+    }
+
+    //[收藏夹]删除
+    function favorite_del()
+    {
+    	$user_id = $this->user['user_id'];
+    	$id      = IReq::get('id');
+
+		if(!empty($id))
+		{
+			$id = IFilter::act($id,'int');
+
+			$favoriteObj = new IModel('favorite');
+
+			if(is_array($id))
+			{
+				$idStr = join(',',$id);
+				$where = 'user_id = '.$user_id.' and id in ('.$idStr.')';
+			}
+			else
+			{
+				$where = 'user_id = '.$user_id.' and id = '.$id;
+			}
+
+			$favoriteObj->del($where);
+			$this->redirect('favorite');
+		}
+		else
+		{
+			$this->redirect('favorite',false);
+			Util::showMessage('请选择要删除的数据');
+		}
+    }
+
+    //[我的积分] 单页展示
+    function integral()
+    {
+    	/*获取积分增减的记录日期时间段*/
+    	$this->historyTime = IFilter::string( IReq::get('history_time','post') );
+    	$defaultMonth = 3;//默认查找最近3个月内的记录
+
+		$lastStamp    = ITime::getTime(ITime::getNow('Y-m-d')) - (3600*24*30*$defaultMonth);
+		$lastTime     = ITime::getDateTime('Y-m-d',$lastStamp);
+
+		if($this->historyTime != null && $this->historyTime != 'default')
+		{
+			$historyStamp = ITime::getDateTime('Y-m-d',($lastStamp - (3600*24*30*$this->historyTime)));
+			$this->c_datetime = 'datetime >= "'.$historyStamp.'" and datetime < "'.$lastTime.'"';
+		}
+		else
+		{
+			$this->c_datetime = 'datetime >= "'.$lastTime.'"';
+		}
+
+    	$memberObj         = new IModel('member');
+    	$where             = 'user_id = '.$this->user['user_id'];
+    	$this->memberRow   = $memberObj->getObj($where,'point');
+    	$this->redirect('integral',false);
+    }
+
+    //[我的积分]积分兑换代金券 动作
+    function trade_ticket()
+    {
+    	$ticketId = IFilter::act( IReq::get('ticket_id','post'),'int' );
+    	$message  = '';
+    	if(intval($ticketId) == 0)
+    	{
+    		$message = '请选择要兑换的代金券';
+    	}
+    	else
+    	{
+    		$nowTime   = ITime::getDateTime();
+    		$ticketObj = new IModel('ticket');
+    		$ticketRow = $ticketObj->getObj('id = '.$ticketId.' and point > 0 and start_time <= "'.$nowTime.'" and end_time > "'.$nowTime.'"');
+    		if(empty($ticketRow))
+    		{
+    			$message = '对不起,此代金券不能兑换';
+    		}
+    		else
+    		{
+	    		$memberObj = new IModel('member');
+	    		$where     = 'user_id = '.$this->user['user_id'];
+	    		$memberRow = $memberObj->getObj($where,'point');
+
+	    		if($ticketRow['point'] > $memberRow['point'])
+	    		{
+	    			$message = '对不起,您的积分不足,不能兑换此类代金券';
+	    		}
+	    		else
+	    		{
+	    			//生成红包
+					$dataArray = array(
+						'condition' => $ticketRow['id'],
+						'name'      => $ticketRow['name'],
+						'card_name' => 'T'.IHash::random(8),
+						'card_pwd'  => IHash::random(8),
+						'value'     => $ticketRow['value'],
+						'start_time'=> $ticketRow['start_time'],
+						'end_time'  => $ticketRow['end_time'],
+						'is_send'   => 1,
+					);
+					$propObj = new IModel('prop');
+					$propObj->setData($dataArray);
+					$insert_id = $propObj->add();
+
+					//更新用户prop字段
+					$memberArray = array('prop' => "CONCAT(IFNULL(prop,''),'{$insert_id},')");
+					$memberObj->setData($memberArray);
+					$result = $memberObj->update('user_id = '.$this->user["user_id"],'prop');
+
+					//代金券成功
+					if($result)
+					{
+						$pointConfig = array(
+							'user_id' => $this->user['user_id'],
+							'point'   => '-'.$ticketRow['point'],
+							'log'     => '积分兑换代金券,扣除了 -'.$ticketRow['point'].'积分',
+						);
+						$pointObj = new Point;
+						$pointObj->update($pointConfig);
+					}
+	    		}
+    		}
+    	}
+
+    	//展示
+    	if($message != '')
+    	{
+    		$this->integral();
+    		Util::showMessage($message);
+    	}
+    	else
+    	{
+    		$this->redirect('redpacket');
+    	}
+    }
+
+    /**
+     * 余额付款
+     * T:支付失败;
+     * F:支付成功;
+     */
+    function payment_balance()
+    {
+    	$urlStr  = '';
+    	$user_id = intval($this->user['user_id']);
+
+    	$return['attach']     = IReq::get('attach');
+    	$return['total_fee']  = IReq::get('total_fee');
+    	$return['order_no']   = IReq::get('order_no');
+    	$return['sign']       = IReq::get('sign');
+
+		$paymentDB  = new IModel('payment');
+		$paymentRow = $paymentDB->getObj('class_name = "balance" ');
+		if(!$paymentRow)
+		{
+			IError::show(403,'余额支付方式不存在');
+		}
+
+		$paymentInstance = Payment::createPaymentInstance($paymentRow['id']);
+		$payResult       = $paymentInstance->callback($return,$paymentRow['id'],$money,$message,$orderNo);
+		if($payResult == false)
+		{
+			IError::show(403,$message);
+		}
+
+    	$memberObj = new IModel('member');
+    	$memberRow = $memberObj->getObj('user_id = '.$user_id);
+
+    	if(empty($memberRow))
+    	{
+    		IError::show(403,'用户信息不存在');
+    	}
+
+    	if($memberRow['balance'] < $return['total_fee'])
+    	{
+    		IError::show(403,'账户余额不足');
+    	}
+
+		//检查订单状态
+		$orderObj = new IModel('order');
+		$orderRow = $orderObj->getObj('order_no  = "'.$return['order_no'].'" and pay_status = 0 and status = 1 and user_id = '.$user_id);
+		if(!$orderRow)
+		{
+			IError::show(403,'订单号【'.$return['order_no'].'】已经被处理过,请查看订单状态');
+		}
+
+		//扣除余额并且记录日志
+		$logObj = new AccountLog();
+		$config = array(
+			'user_id'  => $user_id,
+			'event'    => 'pay',
+			'num'      => $return['total_fee'],
+			'order_no' => str_replace("_",",",$return['attach']),
+		);
+		$is_success = $logObj->write($config);
+		if(!$is_success)
+		{
+			$orderObj->rollback();
+			IError::show(403,$logObj->error ? $logObj->error : '用户余额更新失败');
+		}
+
+		//订单批量结算缓存机制
+		$moreOrder = Order_Class::getBatch($orderNo);
+		if($money >= array_sum($moreOrder))
+		{
+			foreach($moreOrder as $key => $item)
+			{
+				$order_id = Order_Class::updateOrderStatus($key);
+				if(!$order_id)
+				{
+					$orderObj->rollback();
+					IError::show(403,'订单修改失败');
+				}
+			}
+		}
+		else
+		{
+			$orderObj->rollback();
+			IError::show(403,'付款金额与订单金额不符合');
+		}
+
+		//支付成功结果
+		plugin::trigger('setCallback','/ucenter/order');
+		$this->redirect('/site/success/message/'.urlencode("支付成功"));
+    }
+
+    //我的代金券
+    function redpacket()
+    {
+		$member_info = Api::run('getMemberInfo',$this->user['user_id']);
+		$propIds     = trim($member_info['prop'],',');
+		$propIds     = $propIds ? $propIds : 0;
+		$this->setRenderData(array('propId' => $propIds));
+		$this->redirect('redpacket');
+    }
+}

+ 45 - 0
src/controllers/update.php

@@ -0,0 +1,45 @@
+<?php
+/**
+ * @brief 升级更新控制器
+ */
+class Update extends IController
+{
+	/**
+	 * @brief iwebshop16060600 版本升级更新
+	 */
+	public function index()
+	{
+		set_time_limit(0);
+
+		$sql = array(
+			"ALTER TABLE `{pre}refundment_doc` ADD  `trade_no` varchar(255) NOT NULL default '' COMMENT '支付平台退款流水号';",
+			"ALTER TABLE `{pre}order` ADD `prorule_ids` varchar(255) NOT NULL default '' COMMENT '促销活动规格ID串,逗号分隔';",
+			"UPDATE `{pre}right` SET `right`= 'market@sale_edit,market@sale_edit_act,market@sale_list'  WHERE name = '[营销]特价添加修改';",
+			"UPDATE `{pre}right` SET `right`= 'comment@seller_message_send,comment@start_seller_message,member@search_seller,member@filter_seller'  WHERE name = '[会员]商户消息发送';",
+		);
+		foreach($sql as $key => $val)
+		{
+			IDBFactory::getDB()->query( $this->_c($val) );
+		}
+
+		die("升级成功!! V4.8版本");
+	}
+
+	public function _c($sql)
+	{
+		return str_replace('{pre}',IWeb::$app->config['DB']['tablePre'],$sql);
+	}
+
+	//查询规格标准
+	public function searchSpec($specVal,$specValueArray)
+	{
+		foreach($specValueArray as $tip => $item)
+		{
+			if($item == $specVal && !is_numeric($tip))
+			{
+				return $tip;
+			}
+		}
+		return "";
+	}
+}

+ 2 - 0
src/docs/.htaccess

@@ -0,0 +1,2 @@
+Order deny,allow
+Deny from all

+ 1 - 0
src/docs/version.php

@@ -0,0 +1 @@
+<?php return '4.8.17070700';

BIN
src/favicon.ico


+ 6 - 0
src/index.php

@@ -0,0 +1,6 @@
+<?php
+$iweb = dirname(__FILE__)."/lib/iweb.php";
+$config = dirname(__FILE__)."/config/config.php";
+require($iweb);
+IWeb::createWebApp($config)->run();
+?>

+ 5 - 0
src/language/zh_sc/config.php

@@ -0,0 +1,5 @@
+<?php
+return array(
+	'name' => '中文(简体)',
+);
+?>

+ 13 - 0
src/language/zh_sc/form_validation_lang.php

@@ -0,0 +1,13 @@
+<?php
+$prefix = 'fv_';
+return array(
+	$prefix.'email'		=>'格式不正确',
+	$prefix.'tel'		=>'手机验证不通过',
+	$prefix.'qq'		=>'qq验证不通过',
+	$prefix.'id'		=>'ID验证不通过',
+	$prefix.'ip'		=>'IP验证不通过',
+	$prefix.'ip'		=>'IP验证不通过',
+	$prefix.'zip'		=>'ZIP验证不通过',
+	$prefix.'phone'		=>'电话验证不通过',
+	$prefix.'required'	=>'不能为空',
+);

+ 12 - 0
src/language/zh_sc/goods_edit_lang.php

@@ -0,0 +1,12 @@
+<?php
+$prefix = 'add_';
+return array(
+	$prefix.'goods_name'		=>'商品名称:',
+	$prefix.'goods_model'		=>'商品类型:',
+	$prefix.'attribute'			=>'商品标签:',
+	$prefix.'name_note'			=>'* 商品名称(必填)',
+	$prefix.'code_note'			=>'商品编号可以有效管理商品',
+	$prefix.'required_note'		=>'商品编号可以有效管理商品',
+	$prefix.'label_name'		=>'商品名称',
+	$prefix.'label_code'		=>'商品模型',
+);

+ 2 - 0
src/lib/.htaccess

@@ -0,0 +1,2 @@
+Order deny,allow
+Deny from all

+ 187 - 0
src/lib/core/application_class.php

@@ -0,0 +1,187 @@
+<?php
+/**
+ * @copyright Copyright(c) 2010 aircheng.com
+ * @file application.php
+ * @brief 应用的基本类文件,cli命令行或web方式都要集成此类
+ * @author nswe
+ * @date 2014/10/12 20:55:14
+ * @version 4.7
+ */
+
+/**
+ * @brief IApplication 创建应用的基本类
+ * @class IApplication
+ */
+abstract class IApplication
+{
+	//应用的名称
+    public $name = 'iWebShop';
+
+    //应用的编码
+    public $charset = 'UTF-8';
+
+    //应用的语言
+    public $language = 'zh_sc';
+
+	//默认语言包目录
+    public $defaultLanguageDir = "language";
+
+    //程序运行的实际路径
+	public $runtimePath;
+
+    //应用的config信息
+    public $config;
+
+    //应用位置实际路径
+    protected $basePath;
+
+	//默认控制器名称
+	protected $defaultController = 'site';
+
+    //渲染时的数据
+    private $renderData = array();
+
+    /**
+     * @brief 构造函数
+     * @param array or string $config 配置数组或者配置文件名称
+     */
+    public function __construct($config)
+    {
+		if(version_compare(PHP_VERSION, '5.4.1', '<'))
+		{
+			die('Your host needs to use PHP 5.4 or higher to run this version of iWebShop!');
+		}
+
+    	IWeb::setApplication($this);
+
+    	if(is_string($config) && is_file($config))
+    	{
+    		$config = require($config);
+    	}
+
+        $this->config = is_array($config) ? $config : array();
+
+		//配置文件中设置实际路径,如果是cli命令行方式则此参数必须传
+		if(isset($this->config['basePath']) && $this->config['basePath'])
+		{
+			$this->basePath = $this->config['basePath'];
+		}
+
+		date_default_timezone_set(isset($config['timezone']) ? $config['timezone'] : 'Asia/Shanghai');
+		IWeb::setClasses(isset($config['classes']) ? $config['classes'] : 'classes.*');
+		$this->charset  = isset($config['charset']) ? $config['charset'] : $this->charset;
+		$this->language = isset($config['lang']) ? $config['lang'] : $this->language;
+		$this->setDebugMode($config['debug']);
+		$this->defaultLanguageDir = isset($config['langPath']) ? $config['langPath'] : $this->defaultLanguageDir;
+
+		//开始向拦截器里注册类
+		if( isset($config['interceptor']) && is_array($config['interceptor']) )
+		{
+			IInterceptor::reg($config['interceptor']);
+			register_shutdown_function(array('IInterceptor',"shutDown"));
+		}
+    }
+
+    //执行请求
+    abstract public function execRequest();
+    /**
+     * @brief 应用运行的方法
+     * @return Void
+     */
+    public function run()
+    {
+		IInterceptor::run("onCreateApp");
+        $this->execRequest();
+		IInterceptor::run("onFinishApp");
+    }
+
+    /**
+     * @brief 设置调试模式
+     * @param $flag 0:关闭; 1:部分; 2:全部
+     */
+    private function setDebugMode($flag)
+    {
+    	switch($flag)
+    	{
+    		//部分
+    		case 1:
+    		{
+    			ini_set("display_errors","on");
+    			IException::setDebugMode(true);
+    			error_reporting(E_ERROR | E_PARSE);
+    			set_error_handler("IException::phpError",E_ERROR | E_PARSE | E_WARNING);
+    		}
+    		break;
+
+			//全部
+    		case 2:
+    		{
+    			ini_set("display_errors","on");
+    			IException::setDebugMode(true);
+    			error_reporting(E_ALL | E_STRICT);
+    			set_error_handler("IException::phpError" ,E_ALL | E_STRICT );
+    		}
+    		break;
+
+			//关闭
+    		default:
+    		{
+    			ini_set("display_errors","off");
+    			IException::setDebugMode(false);
+    			error_reporting(0);
+    			set_error_handler("IException::phpError" ,E_ALL | E_STRICT );
+    		}
+    	}
+		set_exception_handler("IException::phpException");
+    }
+
+    /**
+     * @brief 取得应用的路径
+     * @return String 路径地址
+     */
+    public function getBasePath()
+    {
+        return $this->basePath;
+    }
+    /**
+     * @brief 得到当前的运行实际路径
+     * @return String 实际路径
+     */
+    public function getRuntimePath()
+    {
+        if($this->runtimePath == null)
+        {
+            $this->runtimePath = $this->getBasePath().'runtime'.DIRECTORY_SEPARATOR;
+        }
+        return $this->runtimePath;
+	}
+
+    /**
+     * @brief 得到当前的语言包实际路径
+     * @return String 实际路径
+     */
+	public function getLanguagePath()
+	{
+        return $this->getBasePath().$this->defaultLanguageDir.DIRECTORY_SEPARATOR;
+	}
+
+    /**
+     * @brief 设置渲染数据
+     * @param array $data 数组的形式存储,渲染后键值将作为变量名。
+     */
+    public function setRenderData($data)
+    {
+        if(is_array($data))
+        {
+            $this->renderData = array_merge($this->renderData,$data);
+        }
+    }
+    /**
+     * @brief 取得应用级的渲染数据
+     * @return array
+     */
+    public function getRenderData()
+    {
+        return $this->renderData;
+    }
+}

+ 112 - 0
src/lib/core/cache/cache_class.php

@@ -0,0 +1,112 @@
+<?php
+/**
+ * @copyright (c) 2011 aircheng.com
+ * @file cache.php
+ * @brief 缓存类
+ * @author chendeshan
+ * @date 2011-7-8 16:02:31
+ * @version 0.6
+ */
+
+/**
+ * @brief 缓存类
+ * @class ICache
+ */
+class ICache
+{
+	private $cache     = null;    //缓存对象
+	private $cacheType = 'file';  //默认缓存类型
+	private $expire    = 2592000; //默认缓存过期时间,单位:秒,默认:1个月
+	private $timeout   = 0;       //默认缓存删除延迟时间,单位:秒
+
+	/**
+	 * @brief  根据缓存类型创建缓存对象
+	 * @param  string $cacheType 缓存类型值
+	 */
+	public function __construct($cacheType = '')
+	{
+		$this->cacheType = $cacheType ? $cacheType : $this->cacheType;
+		$this->expire    = isset(IWeb::$app->config['cache']['expire'])  ? IWeb::$app->config['cache']['expire']  : $this->expire;
+		$this->timeout   = isset(IWeb::$app->config['cache']['timeout']) ? IWeb::$app->config['cache']['timeout'] : $this->timeout;
+
+		//当前系统支持的缓存类型
+		switch($this->cacheType)
+		{
+			case "memcache":
+			$this->cache = new IMemCache();
+			break;
+
+			default:
+			$this->cache = new IFileCache();
+			break;
+		}
+	}
+
+	/**
+	 * @brief  写入缓存
+	 * @param  string $key     缓存的唯一key值
+	 * @param  mixed  $data    要写入的缓存数据
+	 * @param  int    $expire  缓存数据失效时间,单位:秒
+	 * @return bool   true:成功;false:失败;
+	 */
+	public function set($key,$data,$expire = '')
+	{
+		if($expire === '')
+		{
+			$expire = $this->expire;
+		}
+		$data = serialize($data);
+		return $this->cache->set($key,$data,$expire);
+	}
+
+	/**
+	 * @brief  读取缓存
+	 * @param  string $key 缓存的唯一key值,当要返回多个值时可以写成数组
+	 * @return mixed  读取出的缓存数据;null:没有取到数据;
+	 */
+	public function get($key)
+	{
+		$data = $this->cache->get($key);
+		if($data)
+		{
+			return unserialize($data);
+		}
+		else
+		{
+			return null;
+		}
+	}
+
+	/**
+	 * @brief  删除缓存
+	 * @param  string $key     缓存的唯一key值
+	 * @param  int    $timeout 在间隔单位时间内自动删除,单位:秒
+	 * @return bool   true:成功; false:失败;
+	 */
+	public function del($key,$timeout = '')
+	{
+		if($timeout === '')
+		{
+			$timeout = $this->timeout;
+		}
+		return $this->cache->del($key,$timeout);
+	}
+
+	/**
+	 * @brief  删除全部缓存
+	 * @return bool   true:成功;false:失败;
+	 */
+	public function flush()
+	{
+		return $this->cache->flush();
+	}
+
+	/**
+	 * @brief  获取缓存类型
+	 * @return string 缓存类型
+	 */
+	public function getCacheType()
+	{
+		return $this->cacheType;
+	}
+}

+ 46 - 0
src/lib/core/cache/cache_inte.php

@@ -0,0 +1,46 @@
+<?php
+/**
+ * @copyright (c) 2011 aircheng.com
+ * @file cache_inte.php
+ * @brief 缓存接口
+ * @author chendeshan
+ * @date 2011-7-8 16:02:31
+ * @version 0.6
+ */
+
+/**
+ * @brief 缓存接口
+ * @class ICacheInte
+ */
+interface ICacheInte
+{
+	/**
+	 * @brief  写入缓存
+	 * @param  string $key     缓存的唯一key值
+	 * @param  mixed  $data    要写入的缓存数据
+	 * @param  int    $expire  缓存数据失效时间,单位:秒
+	 * @return bool   true:成功;false:失败;
+	 */
+	public function set($key,$data,$expire = '');
+
+	/**
+	 * @brief  读取缓存
+	 * @param  string $key 缓存的唯一key值,当要返回多个值时可以写成数组
+	 * @return mixed  读取出的缓存数据;null:没有取到数据;
+	 */
+	public function get($key);
+
+	/**
+	 * @brief  删除缓存
+	 * @param  string $key     缓存的唯一key值
+	 * @param  int    $timeout 在间隔单位时间内自动删除,单位:秒
+	 * @return bool   true:成功; false:失败;
+	 */
+	public function del($key,$timeout = '');
+
+	/**
+	 * @brief  删除全部缓存
+	 * @return bool   true:成功;false:失败;
+	 */
+	public function flush();
+}

+ 144 - 0
src/lib/core/cache/filecache_class.php

@@ -0,0 +1,144 @@
+<?php
+/**
+ * @copyright (c) 2011 aircheng.com
+ * @file IFile_cache.php
+ * @brief 文件级缓存类
+ * @author chendeshan
+ * @date 2011-7-8 16:02:31
+ * @version 0.6
+ */
+
+/**
+ * @brief 文件级缓存类
+ * @class IFileCache
+ */
+class IFileCache implements ICacheInte
+{
+	private $cachePath      = 'runtime/cache'; //默认文件缓存存放路径
+	private $cacheExt       = '.data';         //默认文件缓存扩展名
+	private $directoryLevel = 1;               //目录层级,基于$cachePath之下的
+
+	/**
+	 * @brief  构造函数
+	 */
+	public function __construct()
+	{
+		$this->cachePath = isset(IWeb::$app->config['cache']['path']) ? IWeb::$app->config['cache']['path'] : $this->cachePath;
+		$this->cacheExt  = isset(IWeb::$app->config['cache']['ext'])  ? IWeb::$app->config['cache']['ext']  : $this->cacheExt;
+	}
+
+	/**
+	 * @brief  根据key值计算缓存文件名
+	 * @param  string $key 缓存的唯一key值
+	 * @return string 缓存文件路径
+	 */
+	private function getFileName($key)
+	{
+		$key      = str_replace(' ','',$key);
+		$cacheDir = rtrim($this->cachePath,'\\/').'/';
+		if($this->directoryLevel > 0)
+		{
+			$hash      = abs(crc32($key));
+			$cacheDir .= $hash % 1024;
+			for($i = 1;$i < $this->directoryLevel;++$i)
+			{
+				if(($prefix = substr($hash,$i,2)) !== false)
+				{
+					$cacheDir .= '/'.$prefix;
+				}
+			}
+		}
+		return $cacheDir.'/'.md5($key).$this->cacheExt;
+	}
+
+	/**
+	 * @brief  写入缓存
+	 * @param  string $key     缓存的唯一key值
+	 * @param  mixed  $data    要写入的缓存数据
+	 * @param  int    $expire  缓存数据失效时间,单位:秒
+	 * @return bool   true:成功;false:失败;
+	 */
+	public function set($key,$data,$expire = '')
+	{
+		$fileName = $this->getFileName($key);
+		if(!file_exists($dirname=dirname($fileName)))
+		{
+			IFile::mkdir($dirname);
+		}
+
+		$writeLen = file_put_contents($fileName,$data);
+
+		if($writeLen == 0)
+		{
+			return false;
+		}
+		else
+		{
+			$expire = time() + $expire;
+			touch($fileName,$expire);
+			return true;
+		}
+	}
+
+	/**
+	 * @brief  读取缓存
+	 * @param  string $key 缓存的唯一key值,当要返回多个值时可以写成数组
+	 * @return mixed  读取出的缓存数据;null:没有取到数据或者缓存已经过期了;
+	 */
+	public function get($key)
+	{
+		$fileName = $this->getFileName($key);
+		if(file_exists($fileName))
+		{
+			if(time() > filemtime($fileName))
+			{
+				$this->del($key,0);
+				return null;
+			}
+			else
+			{
+				return file_get_contents($fileName);
+			}
+		}
+		else
+		{
+			return null;
+		}
+	}
+
+	/**
+	 * @brief  删除缓存
+	 * @param  string $key     缓存的唯一key值
+	 * @param  int    $timeout 在间隔单位时间内自动删除,单位:秒
+	 * @return bool   true:成功; false:失败;
+	 */
+	public function del($key,$timeout = '')
+	{
+		$fileName = $this->getFileName($key);
+		if(file_exists($fileName))
+		{
+			if($timeout > 0)
+			{
+				$timeout = time() + $timeout;
+				return touch($fileName,$timeout);
+			}
+			else
+			{
+				return unlink($fileName);
+			}
+		}
+		else
+		{
+			return true;
+		}
+	}
+
+	/**
+	 * @brief  删除全部缓存
+	 * @return bool   true:成功;false:失败;
+	 */
+	public function flush()
+	{
+		return IFile::clearDir($this->cachePath);
+	}
+}

+ 196 - 0
src/lib/core/interceptor_class.php

@@ -0,0 +1,196 @@
+<?php
+/**
+ * @copyright Copyright(c) 2011 aircheng.com
+ * @file interceptor_class.php
+ * @brief 内核拦截器,观察者模式,类似框架事件机制
+ * @author nswe
+ * @date 2016/2/27 21:44:02
+ * @version 4.3
+ */
+
+/**
+ * 内核拦截器
+ *
+ * 在app中使用这个类,需要在config.php里配置interceptor
+ * 'interceptor'=>array(
+ *		'classname', //将classname类注册到所有位置
+ *		'classname1@onFinishApp', //将classname1类注册到onFinishApp这个位置
+ * );
+ *
+ * <ul>
+ *     <li>onPhpShutDown一旦注册,便肯定会执行,即使程序中调用了die和exit</li>
+ * </ul>
+ *
+ * 在使用拦截器时,建议一个拦截器只完成一方面的工作,比如IBlog@onFinishApp,IUser@onCreateApp
+ * 虽然IBlog和IUser的逻辑可以写在一类里,但为了以后维护的方便,建议拆分开
+ *
+ * @author nswe
+ */
+class IInterceptor
+{
+	/**
+	 * @brief 系统中预定的事件位置
+	 */
+	private static $validPosition = array(
+		'onCreateApp',
+		'onFinishApp',
+		'onBeforeCreateController',
+		'onCreateController',
+		'onFinishController',
+		'onBeforeCreateAction',
+		'onCreateAction',
+		'onFinishAction',
+		'onBeforeCreateView',
+		'onCreateView',
+		'onFinishView',
+		'onPhpShutDown',
+	);
+
+	private static $obj = array();
+
+	/**
+	 * 向系统中的拦截位置注册类
+	 * @param string|array $value 可以为 "iclass_name","class_name@position",也可以是由他们组成的数组
+	 */
+	public static function reg($value)
+	{
+		if( is_array($value) )
+		{
+			foreach($value as $v)
+			{
+				self::reg($v);
+			}
+		}
+		else
+		{
+			$tmp = explode("@",trim($value));
+
+			//指定拦截器具体位置
+			if( count($tmp) == 2 )
+			{
+				self::regIntoPosition($tmp[0] , $tmp[1]);
+			}
+			//所有拦截器位置都拦截
+			else
+			{
+				foreach(self::$validPosition as $value)
+				{
+					self::regIntoPosition($tmp[0] , $value);
+				}
+			}
+		}
+	}
+
+	/**
+	 * 直接像某位置注册类
+	 * @param string $className 处理类名称
+	 * @param string $position  位置
+	 */
+	public static function regIntoPosition($className,$position)
+	{
+		$validPos = in_array($position,self::$validPosition);
+		$haveDone = isset(self::$obj[$position]) && in_array($className,self::$obj[$position]);
+		if( $validPos && !$haveDone )
+		{
+			self::$obj[$position][] = $className;
+		}
+	}
+
+	/**
+	 * 调用注册到某个位置的拦截器
+	 * @param string $position  位置
+	 * @param mixed $ctrlInfo   控制器参数信息
+	 * @param mixed $actionInfo 动作参数信息
+	 */
+	public static function run($position,$ctrlInfo = null,$actionInfo = null)
+	{
+		if( !isset(self::$obj[$position]) || !in_array($position,self::$validPosition) )
+		{
+			return;
+		}
+
+		foreach( self::$obj[$position] as $value )
+		{
+			call_user_func( array($value,$position),$ctrlInfo,$actionInfo);
+		}
+	}
+
+	/**
+	 * 删除某个位置的所有拦截器,如果$className!=null,则只删除它一个
+	 * @param string $position
+	 * @param string|null $className
+	 */
+	public static function del($position,$className = null)
+	{
+		if(!isset(self::$obj[$position]))
+		{
+			if($className!==null)
+			{
+				foreach(self::$obj[$position] as $key=>$value)
+				{
+					if( $className==$value )
+					{
+						unset(self::$obj[$position][$key]);
+						break;
+					}
+				}
+			}
+			else
+			{
+				unset(self::$obj[$position]);
+			}
+		}
+	}
+
+	/**
+	 * 清空所有拦截器
+	 */
+	public static function delAll()
+	{
+		self::$obj = array();
+	}
+
+	/**
+	 * php结束自动回调,触发onFinishApp事件
+	 */
+	public static function shutDown()
+	{
+		self::run("onPhpShutDown");
+	}
+}
+
+/**
+ * 拦截器基类,建议大家在创建拦截器对象的时候继承此类。
+ */
+abstract class IInterceptorBase
+{
+	//获取当前app对象
+	public static function app()
+	{
+		return IWeb::$app;
+	}
+
+	//获取当前controller对象
+	public static function controller()
+	{
+		return IWeb::$app->getController();
+	}
+
+	//获取当前action对象
+	public static function action()
+	{
+		return IWeb::$app->getController()->getAction();
+	}
+
+	public static function onCreateApp(){}
+	public static function onFinishApp(){}
+	public static function onBeforeCreateController($ctrlId){}
+	public static function onCreateController($ctrlObj){}
+	public static function onFinishController($ctrlObj){}
+	public static function onBeforeCreateAction($ctrlObj,$actionId){}
+	public static function onCreateAction($ctrlObj,$actinObj){}
+	public static function onFinishAction($ctrlObj,$actinObj){}
+	public static function onCreateView($ctrlObj,$actinObj){}
+	public static function onFinishView($ctrlObj,$actinObj){}
+	public static function onPhpShutDown(){}
+}

Daži faili netika attēloti, jo izmaiņu fails ir pārāk liels