Authored by yangyang
Commit b84c0b7512ddc3787d15fbf76e3100adec09fa12 2 parents 4cb876f2 17f762a6 master ... develop feature/brandCoupon feature/changeQr feature/encryptionUid feature/filter-age feature/mobile feature/newInvoice feature/order-show feature/payMethod feature/paymentTip feature/rcmnd4U feature/rebuy feature/shopBaseTlp feature/ticket feature/userInfoTip hotfix/cancelOrder hotfix/catlog hotfix/delWap hotfix/deleteOrderStyle hotfix/detail hotfix/editOrder hotfix/guang-goodsgroup hotfix/itemApiurl hotfix/loophole hotfix/making-order hotfix/new-girls hotfix/orders hotfix/productDetail hotfix/receipt hotfix/register hotfix/returnImage hotfix/rtrngdsstyl hotfix/validate patch-1 release/4.7 release/4.8 release/outlets 4.8.2 4.7.2 4.6.2.1 4.6.2 4.6 1.3.22 1.3.21 1.3.20 1.3.19 1.3.18 1.3.17 1.3.16 1.3.15 1.3.14 1.3.13 1.3.12 1.3.11 1.3.10 1.3.9 1.3.8 1.3.7 1.3.7.g 1.3.7.f 1.3.7.e 1.3.7.d 1.3.7.c 1.3.7.b 1.3.7.a 1.3.6 1.3.5 wap.3.2.5 wap.1.4.22 wap.1.4.21 wap.1.4.20 wap.1.4.19 wap.1.4.18 wap.1.4.17 wap.1.4.16.3 wap.1.4.16.2 wap.1.4.16.1 wap.1.4.16 wap.1.4.15 wap.1.4.14 wap.1.4.13 wap.1.4.12 wap.1.4.11 wap.1.4.10 wap.1.4.9 wap.1.4.8 wap.1.4.7 wap.1.4.6 wap.1.4.5 wap.1.4.4 wap.1.4.3 wap.1.4.2 wap.1.4.1 wap.1.4.0 pchttps pc4.5 pc.1.4.24 pc.1.4.23 pc.1.4.22 pc.1.4.21 pc.1.4.20 pc.1.4.19 pc.1.4.18 pc.1.4.17 pc.1.4.16 pc.1.4.15 pc.1.4.14 pc.1.4.13 pc.1.4.12 pc.1.4.11 pc.1.4.10 pc.1.4.9 pc.1.4.8 pc.1.4.7 pc.1.4.6 pc.1.0.7 pc.1.0.6 pc.1.0.5 pc.1.0.4 pc.1.0.3 pc.1.0.2 pc.1.0.1 pc.1.0.0 fix-ip-login-limit fix-ip-limit

Merge branch 'master' of http://git.dev.yoho.cn/web/yohobuy into lingquan3/yangyang

Showing 43 changed files with 1273 additions and 1130 deletions

Too many changes to show.

To preserve performance only 43 of 43+ files are displayed.

... ... @@ -45,7 +45,7 @@ class BrandData
$param['method'] = 'app.brand.brandlist';
$param['yh_channel'] = $channel;
$param['client_secret'] = Sign::getSign($param);
$urlList['brandList'] = Yohobuy::httpBuildQuery(Yohobuy::API_URL, $param);
$urlList['brandList'] = Yohobuy::httpBuildQuery(Yohobuy::API_URL, $param);
return Yohobuy::getMulti($urlList, array(), 3600); // 有缓存1小时
}
... ... @@ -201,7 +201,7 @@ class BrandData
return Yohobuy::get(Yohobuy::API_URL, $param);
}
/**
* 获取品牌LOGO信息
*
... ... @@ -210,10 +210,10 @@ class BrandData
*/
public static function getBrandLogo($id)
{
return Yohobuy::yarClient(Yohobuy::SERVICE_URL . '/shops/service/v1/brand', 'getBrandByids', array($id ));
return Yohobuy::yarClient(Yohobuy::SERVICE_URL . '/shops/service/v1/brand', 'getBrandByids', array($id));
}
/**
/**
* 通过域名获取品牌LOGO信息
*
* @param int $id 用户ID
... ... @@ -221,7 +221,7 @@ class BrandData
*/
public static function getBrandLogoByDomain($domain)
{
return Yohobuy::yarClient(Yohobuy::SERVICE_URL . '/shops/service/v1/brand', 'getBrandByDomain', array($domain ));
return Yohobuy::yarClient(Yohobuy::SERVICE_URL . '/shops/service/v1/brand', 'getBrandByDomain', array($domain));
}
}
... ...
... ... @@ -51,7 +51,7 @@ class ActivityData
$param = array();
$param['uid'] = $uid;
$param['activity_id'] = $activityId;
return Yohobuy::get(Yohobuy::SERVICE_URL . self::URI_GET_ALL_COUPON, $param);
}
... ... @@ -78,7 +78,7 @@ class ActivityData
{
//调用接口发送站内信
return Yohobuy::yarClient(Yohobuy::SERVICE_URL . self::URI_SEND_MESSAGE, 'setSingleMessage', array(
$uid, $title, $content, $type, $verify_key, $send_uid, $call_back
$uid, $title, $content, $type, $verify_key, $send_uid, $call_back
));
}
... ...
... ... @@ -45,7 +45,7 @@ class DetailData
// 先尝试获取二级缓存(slave), 有数据则直接返回.
$cached = Cache::get($key, 'master');
if (!empty($cached)) {
$article = Yohobuy::yarClient(Yohobuy::SERVICE_URL . self::URI_PACKAGE_ARTICLE, 'getArticle', array($id, $clientType), false, 1000);
$article = Yohobuy::yarClient(Yohobuy::SERVICE_URL . self::URI_PACKAGE_ARTICLE, 'getArticle', array($id, $clientType), false, 1000);
if (isset($article['pageViews'])) {
$cached['getArticle']['pageViews'] = $article['pageViews'];
}
... ... @@ -54,7 +54,7 @@ class DetailData
}
// 获取资讯
$article = Yohobuy::yarClient(Yohobuy::SERVICE_URL . self::URI_PACKAGE_ARTICLE, 'getArticle', array($id, $clientType), false);
$article = Yohobuy::yarClient(Yohobuy::SERVICE_URL . self::URI_PACKAGE_ARTICLE, 'getArticle', array($id, $clientType), false);
if (!isset($article['author_id'])) {
return $result;
}
... ... @@ -140,7 +140,7 @@ class DetailData
return $result;
}
/**
* 获取详情信息
*/
... ...
... ... @@ -17,6 +17,7 @@ use Plugin\Cache;
*/
class ListData
{
const URI_CATEGORY = 'guang/api/v1/category/get';
const URI_ARTICLELIST = 'guang/api/v2/article/getList';
const URI_AUTHOR = 'guang/service/v1/author/';
... ... @@ -70,9 +71,9 @@ class ListData
$param['limit'] = $limit;
}
$param['client_secret'] = Sign::getSign($param);
$cache = $useCache ? 300 : false;
return Yohobuy::get(Yohobuy::SERVICE_URL . self::URI_ARTICLELIST, $param, $cache); // 缓存5分钟
}
... ...
... ... @@ -162,7 +162,6 @@ class PlusstarData
// $result['getUidBrandFav'] = (isset($retval['message']) && $retval['message'] == 'favorite') ? true : false;
// });
// }
// 相关资讯列表 (3篇)
$result['getArticleByBrand'] = array();
Yohobuy::yarConcurrentCall(Yohobuy::SERVICE_URL . self::URI_BRANDINFO_ARTICLE, 'getArticleByBrand', array($brandInfo['data']['brand_id'], 3, $udid), function($retval) use(&$result) {
... ...
... ... @@ -27,176 +27,176 @@ class CartData
* @param null|int $promotionId 促销id,默认null(加价购有关)
* @param null|int $uid 用户UID,可以不传
* @param string $shoppingKey 未登录用户唯一识别码,可以不传
* @return array 加入购物车接口返回的数据
*/
public static function addToCart($productSku, $buyNumber, $goodsType, $isEdit = 0, $promotionId = null, $uid = null, $shoppingKey = null)
{
$param = Yohobuy::param();
$param['method'] = 'app.Shopping.add';
$param['product_sku'] = $productSku;
$param['buy_number'] = $buyNumber;
$param['goods_type'] = $goodsType;
$param['edit_product_sku'] = $isEdit;
$param['selected'] = 'Y';
$param['promotion_id'] = $promotionId;
if (!empty($uid)) {
$param['uid'] = $uid;
}
if ($shoppingKey !== null) {
$param['shopping_key'] = $shoppingKey;
}
$param['client_secret'] = Sign::getSign($param);
return Yohobuy::get(Yohobuy::API_URL, $param);
}
/**
* 购物车商品选择与取消接口
*
* @param int $uid 用户ID
* @param string $sku 商品sku列表
* @param string $shoppingKey 未登录用户唯一识别码
* @return array 购物车接口返回的数据
*/
public static function selectGoods($uid, $sku, $shoppingKey)
{
$param = Yohobuy::param();
$param['method'] = 'app.Shopping.selected';
$param['product_sku_list'] = $sku;
if (!empty($uid)) {
$param['uid'] = $uid;
}
if (!empty($shoppingKey)) {
$param['shopping_key'] = $shoppingKey;
}
$param['client_secret'] = Sign::getSign($param);
return Yohobuy::get(Yohobuy::API_URL, $param);
}
/**
* 购物车数据
*
* @param int $uid 用户ID
* @param string $shoppingKey 未登录用户唯一识别码
* @return array 购物车接口返回的数据
*/
public static function cartData($uid, $shoppingKey)
{
$param = Yohobuy::param();
$param['method'] = 'app.Shopping.cart';
if (!empty($uid)) {
$param['uid'] = $uid;
}
if (!empty($shoppingKey)) {
$param['shopping_key'] = $shoppingKey;
}
$param['client_secret'] = Sign::getSign($param);
return Yohobuy::get(Yohobuy::API_URL, $param);
}
/**
* 移出购物车
*
* @param int $uid 用户ID
* @param string $sku 商品sku列表
* @param string $shoppingKey 未登录用户唯一识别码
* @return array 接口返回的数据
*/
public static function removeFromCart($uid, $sku, $shoppingKey)
{
$param = Yohobuy::param();
$param['method'] = 'app.Shopping.remove';
$param['product_sku_list'] = $sku;
if (!empty($uid)) {
$param['uid'] = $uid;
}
if (!empty($shoppingKey)) {
$param['shopping_key'] = $shoppingKey;
}
$param['client_secret'] = Sign::getSign($param);
return Yohobuy::get(Yohobuy::API_URL, $param);
}
/**
* 移入收藏夹
*
* @param int $uid 用户ID
* @param string $sku 商品sku列表
* @return array 接口返回的数据
*/
public static function addToFav($uid, $sku)
{
$param = Yohobuy::param();
$param['method'] = 'app.Shopping.addfavorite';
$param['product_sku_list'] = $sku;
$param['uid'] = $uid;
$param['client_secret'] = Sign::getSign($param);
return Yohobuy::get(Yohobuy::API_URL, $param);
}
/**
* 获取购物车商品数据
*
* @param int $uid 用户ID
* @param int $skn 商品skn
* @return array 接口返回的数据
*/
public static function cartProductData($uid, $skn)
{
$param = Yohobuy::param();
$param['method'] = 'app.product.data';
$param['product_skn'] = $skn;
$param['showcomment'] = 'N';
$param['uid'] = $uid;
$param['client_secret'] = Sign::getSign($param);
return Yohobuy::get(Yohobuy::API_URL, $param);
}
/**
* 获取加价购商品数据
*
* @param int $skn 商品skn
* @param int $promotionId 加价购商品促销ID
* @return array 接口返回的数据
*/
public static function giftProductData($skn, $promotionId)
{
$param = Yohobuy::param();
$param['method'] = 'app.product.gift';
$param['product_skn'] = $skn;
$param['promotion_id'] = $promotionId;
$param['client_secret'] = Sign::getSign($param);
return Yohobuy::get(Yohobuy::API_URL, $param);
}
/**
* 增减购物车商品数量
*
* @param int $uid 用户ID
* @param string $sku 商品SKU
* @param int $increaseNum 增加的数目
* @param int $decreaseNum 减少的数目
* @param string $shoppingKey 未登录用户唯一识别码
* @return array 接口返回的数据
*/
public static function modifyProductNum($uid, $sku, $increaseNum, $decreaseNum, $shoppingKey)
{
$param = Yohobuy::param();
$param['method'] = 'app.Shopping.increase';
$param['product_sku'] = $sku;
* @return array 加入购物车接口返回的数据
*/
public static function addToCart($productSku, $buyNumber, $goodsType, $isEdit = 0, $promotionId = null, $uid = null, $shoppingKey = null)
{
$param = Yohobuy::param();
$param['method'] = 'app.Shopping.add';
$param['product_sku'] = $productSku;
$param['buy_number'] = $buyNumber;
$param['goods_type'] = $goodsType;
$param['edit_product_sku'] = $isEdit;
$param['selected'] = 'Y';
$param['promotion_id'] = $promotionId;
if (!empty($uid)) {
$param['uid'] = $uid;
}
if ($shoppingKey !== null) {
$param['shopping_key'] = $shoppingKey;
}
$param['client_secret'] = Sign::getSign($param);
return Yohobuy::get(Yohobuy::API_URL, $param);
}
/**
* 购物车商品选择与取消接口
*
* @param int $uid 用户ID
* @param string $sku 商品sku列表
* @param string $shoppingKey 未登录用户唯一识别码
* @return array 购物车接口返回的数据
*/
public static function selectGoods($uid, $sku, $shoppingKey)
{
$param = Yohobuy::param();
$param['method'] = 'app.Shopping.selected';
$param['product_sku_list'] = $sku;
if (!empty($uid)) {
$param['uid'] = $uid;
}
if (!empty($shoppingKey)) {
$param['shopping_key'] = $shoppingKey;
}
$param['client_secret'] = Sign::getSign($param);
return Yohobuy::get(Yohobuy::API_URL, $param);
}
/**
* 购物车数据
*
* @param int $uid 用户ID
* @param string $shoppingKey 未登录用户唯一识别码
* @return array 购物车接口返回的数据
*/
public static function cartData($uid, $shoppingKey)
{
$param = Yohobuy::param();
$param['method'] = 'app.Shopping.cart';
if (!empty($uid)) {
$param['uid'] = $uid;
}
if (!empty($shoppingKey)) {
$param['shopping_key'] = $shoppingKey;
}
$param['client_secret'] = Sign::getSign($param);
return Yohobuy::get(Yohobuy::API_URL, $param);
}
/**
* 移出购物车
*
* @param int $uid 用户ID
* @param string $sku 商品sku列表
* @param string $shoppingKey 未登录用户唯一识别码
* @return array 接口返回的数据
*/
public static function removeFromCart($uid, $sku, $shoppingKey)
{
$param = Yohobuy::param();
$param['method'] = 'app.Shopping.remove';
$param['product_sku_list'] = $sku;
if (!empty($uid)) {
$param['uid'] = $uid;
}
if (!empty($shoppingKey)) {
$param['shopping_key'] = $shoppingKey;
}
$param['client_secret'] = Sign::getSign($param);
return Yohobuy::get(Yohobuy::API_URL, $param);
}
/**
* 移入收藏夹
*
* @param int $uid 用户ID
* @param string $sku 商品sku列表
* @return array 接口返回的数据
*/
public static function addToFav($uid, $sku)
{
$param = Yohobuy::param();
$param['method'] = 'app.Shopping.addfavorite';
$param['product_sku_list'] = $sku;
$param['uid'] = $uid;
$param['client_secret'] = Sign::getSign($param);
return Yohobuy::get(Yohobuy::API_URL, $param);
}
/**
* 获取购物车商品数据
*
* @param int $uid 用户ID
* @param int $skn 商品skn
* @return array 接口返回的数据
*/
public static function cartProductData($uid, $skn)
{
$param = Yohobuy::param();
$param['method'] = 'app.product.data';
$param['product_skn'] = $skn;
$param['showcomment'] = 'N';
$param['uid'] = $uid;
$param['client_secret'] = Sign::getSign($param);
return Yohobuy::get(Yohobuy::API_URL, $param);
}
/**
* 获取加价购商品数据
*
* @param int $skn 商品skn
* @param int $promotionId 加价购商品促销ID
* @return array 接口返回的数据
*/
public static function giftProductData($skn, $promotionId)
{
$param = Yohobuy::param();
$param['method'] = 'app.product.gift';
$param['product_skn'] = $skn;
$param['promotion_id'] = $promotionId;
$param['client_secret'] = Sign::getSign($param);
return Yohobuy::get(Yohobuy::API_URL, $param);
}
/**
* 增减购物车商品数量
*
* @param int $uid 用户ID
* @param string $sku 商品SKU
* @param int $increaseNum 增加的数目
* @param int $decreaseNum 减少的数目
* @param string $shoppingKey 未登录用户唯一识别码
* @return array 接口返回的数据
*/
public static function modifyProductNum($uid, $sku, $increaseNum, $decreaseNum, $shoppingKey)
{
$param = Yohobuy::param();
$param['method'] = 'app.Shopping.increase';
$param['product_sku'] = $sku;
if (!empty($increaseNum)) {
$param['increase_number'] = $increaseNum;
... ... @@ -258,7 +258,7 @@ class CartData
$param['uid'] = $uid;
$param['client_secret'] = Sign::getSign($param);
return Yohobuy::get(Yohobuy::API_URL, $param);
return Yohobuy::get(Yohobuy::API_URL, $param);
}
/**
... ... @@ -377,7 +377,7 @@ class CartData
return Yohobuy::get(Yohobuy::API_URL, $param);
}
/**
* 购物车数量
*
... ...
... ... @@ -12,46 +12,48 @@ use Api\Sign;
class GradeData
{
/**
* 获取会员等级数据
* @param string $yh_channel 频道数据,1->男,2->女,3->潮童,4->创意生活,5->其他
* @param string $uid 用户id
* @return array 接口返回的会员等级数据
*/
public static function getGradeData($channel, $uid) {
$urlList = array();
//获取会员等级数据
$param = Yohobuy::param();
$param['yh_channel'] = $channel;
$param['uid'] = $uid;
$param['method'] = 'app.Passport.vip';
$param['client_secret'] = Sign::getSign($param);
$urlList['grade'] = Yohobuy::httpBuildQuery(Yohobuy::API_URL, $param);
//获取用户基本信息数据(用来得到username)
$param = Yohobuy::param();
$param['uid'] = $uid;
$param['method'] = 'app.passport.profile';
$param['client_secret'] = Sign::getSign($param);
$urlList['userProfile'] = Yohobuy::httpBuildQuery(Yohobuy::API_URL, $param);
return Yohobuy::getMulti($urlList);
}
/**
* 获取会员特权详情数据
* @param string $yh_channel 频道数据,1->男,2->女,3->潮童,4->创意生活,5->其他
* @param string $uid 用户id
* @return array 接口返回的会员特权详情数据
*/
public static function getPreferentialData($channel, $uid) {
$param = Yohobuy::param();
$param['yh_channel'] = $channel;
$param['uid'] = $uid;
$param['method'] = 'app.passport.getPrivilege';
$param['client_secret'] = Sign::getSign($param);
return Yohobuy::get(Yohobuy::API_URL, $param);
}
/**
* 获取会员等级数据
* @param string $yh_channel 频道数据,1->男,2->女,3->潮童,4->创意生活,5->其他
* @param string $uid 用户id
* @return array 接口返回的会员等级数据
*/
public static function getGradeData($channel, $uid)
{
$urlList = array();
//获取会员等级数据
$param = Yohobuy::param();
$param['yh_channel'] = $channel;
$param['uid'] = $uid;
$param['method'] = 'app.Passport.vip';
$param['client_secret'] = Sign::getSign($param);
$urlList['grade'] = Yohobuy::httpBuildQuery(Yohobuy::API_URL, $param);
//获取用户基本信息数据(用来得到username)
$param = Yohobuy::param();
$param['uid'] = $uid;
$param['method'] = 'app.passport.profile';
$param['client_secret'] = Sign::getSign($param);
$urlList['userProfile'] = Yohobuy::httpBuildQuery(Yohobuy::API_URL, $param);
return Yohobuy::getMulti($urlList);
}
/**
* 获取会员特权详情数据
* @param string $yh_channel 频道数据,1->男,2->女,3->潮童,4->创意生活,5->其他
* @param string $uid 用户id
* @return array 接口返回的会员特权详情数据
*/
public static function getPreferentialData($channel, $uid)
{
$param = Yohobuy::param();
$param['yh_channel'] = $channel;
$param['uid'] = $uid;
$param['method'] = 'app.passport.getPrivilege';
$param['client_secret'] = Sign::getSign($param);
return Yohobuy::get(Yohobuy::API_URL, $param);
}
}
... ...
... ... @@ -4,44 +4,41 @@ namespace LibModels\Wap\Home;
use Api\Yohobuy;
use Api\Sign;
/**
* 帮助中心数据模型
*
*/
class HelpData
{
/*
* 获取帮助列表(分类),缓存1h
* clientType客户端
*/
public static function serviceInfo()
{
//构建必传参数
//构建必传参数
$param = Yohobuy::param();
$param['method'] = 'app.help.li';
$param['client_secret'] = Sign::getSign($param);
return Yohobuy::post(Yohobuy::API_URL, $param);
return Yohobuy::post(Yohobuy::API_URL, $param);
}
/*
* 获取帮助中心列表
*/
public static function serviceDetail($code)
{
//构建必传参数
//构建必传参数
$param = Yohobuy::param();
$param['method'] = 'app.help.detail';
$param['code'] = $code;
$param['code'] = $code;
$param['return_type'] = 'html';
$param['client_secret'] = Sign::getSign($param);
return Yohobuy::post(Yohobuy::API_OLD, $param, true);
return Yohobuy::post(Yohobuy::API_OLD, $param, true);
}
}
... ...
... ... @@ -27,10 +27,10 @@ class IndexData
{
// 构建必传参数
$param = Yohobuy::param();
$param['content_code'] = $contentCode;
$param['content_code'] = $contentCode;
$param['client_secret'] = Sign::getSign($param);
return Yohobuy::get(Yohobuy::SERVICE_URL . 'operations/api/v5/resource/get', $param);
return Yohobuy::get(Yohobuy::SERVICE_URL . 'operations/api/v5/resource/get', $param);
}
/**
... ... @@ -64,10 +64,10 @@ class IndexData
$param['page'] = $page;
$param['limit'] = $limit;
$param['client_secret'] = Sign::getSign($param);
return Yohobuy::get(Yohobuy::SERVICE_URL . 'operations/api/v5/resource/home', $param);
return Yohobuy::get(Yohobuy::SERVICE_URL . 'operations/api/v5/resource/home', $param);
}
/**
* 获取频道选择页数据
*
... ... @@ -77,7 +77,7 @@ class IndexData
{
$param = Yohobuy::param();
$param['client_secret'] = Sign::getSign($param);
return Yohobuy::get(Yohobuy::SERVICE_URL . 'operations/api/v5/entrance/getEntrance', $param);
}
... ...
... ... @@ -15,15 +15,17 @@ use Api\Yohobuy;
*/
class OnlineData
{
const ONLINE_URI = 'operations/api/v1/help/';
/*
* 获取帮助列表(分类),缓存1h
* clientType客户端
*/
public static function getOnlineServiceInfo($clientType='iphone')
public static function getOnlineServiceInfo($clientType = 'iphone')
{
return Yohobuy::get(Yohobuy::SERVICE_URL .self::ONLINE_URI.'getCategory', array('client_type'=>$clientType),3600);
return Yohobuy::get(Yohobuy::SERVICE_URL . self::ONLINE_URI . 'getCategory', array('client_type' => $clientType), 3600);
}
/*
... ... @@ -31,9 +33,10 @@ class OnlineData
* cateId问题分类ID
* clientType客户端
*/
public static function getOnlineServiceDetail($cateId, $clientType = 'iphone')
{
return Yohobuy::get(Yohobuy::SERVICE_URL .self::ONLINE_URI.'getHelp', array('category_id'=>$cateId,'client_type'=>$clientType),3600);
return Yohobuy::get(Yohobuy::SERVICE_URL . self::ONLINE_URI . 'getHelp', array('category_id' => $cateId, 'client_type' => $clientType), 3600);
}
}
... ...
... ... @@ -14,6 +14,7 @@ class OrderData
/*
* 获取订单数据
*/
public static function getOrderData($type, $page, $limit, $gender, $channel, $uid)
{
//构建必传参数
... ... @@ -33,6 +34,7 @@ class OrderData
/*
* 取消订单
*/
public static function cancelOrderData($orderCode, $uid, $gender, $channel)
{
//构建必传参数
... ... @@ -50,6 +52,7 @@ class OrderData
/*
* 删除订单
*/
public static function deleteOrderData($orderCode, $uid, $gender, $channel)
{
//构建必传参数
... ... @@ -63,7 +66,7 @@ class OrderData
//调用接口删除订单
return Yohobuy::get(Yohobuy::API_URL, $param);
}
/**
* 查看订单详情
*
... ... @@ -80,7 +83,7 @@ class OrderData
$param['uid'] = $uid;
$param['session_key'] = $sessionKey;
$param['client_secret'] = Sign::getSign($param);
return Yohobuy::get(Yohobuy::API_URL, $param);
}
... ... @@ -91,6 +94,7 @@ class OrderData
* @param int $uid 用户ID
* @return array
*/
public static function LogisticsData($orderCode, $uid)
{
//构建必传参数
... ... @@ -107,6 +111,7 @@ class OrderData
* 支付页面的资源位
* To change this template file, choose Tools | Templates
*/
public static function paymentData($gender, $yh_channel, $code)
{
//构建必传参数
... ... @@ -124,6 +129,7 @@ class OrderData
*
* 备注:暂不使用
*/
public static function strollData($gender, $yh_channel, $code)
{
//构建必传参数
... ... @@ -135,10 +141,11 @@ class OrderData
//调用接口获得数据
return Yohobuy::get(Yohobuy::SERVICE_URL . '/operations/api/v5/resource/get', $param);
}
/*
* 微信支付签名
*/
public static function weixinPaySign($orderCode)
{
//构建必传参数
... ...
... ... @@ -16,9 +16,10 @@ use Api\Yohobuy;
*/
class SideData
{
const URI_LEFTNAV_ENTRANCE = 'operations/api/v5/entrance/getEntrance';
const URI_LEFTNAV_CATEGORY = 'operations/api/v5/category/getCategory';
/**
* 左侧边栏的分类和图标数据
*
... ... @@ -36,12 +37,12 @@ class SideData
// $urlList['getCategory'] = Yohobuy::SERVICE_URL . self::URI_LEFTNAV_CATEGORY . $query;
//
// return Yohobuy::getMulti($urlList);
$param = Yohobuy::param();
$param['client_type'] = 'h5'; // 调用H5手机网站的
$param['client_secret'] = Sign::getSign($param);
return Yohobuy::get(Yohobuy::SERVICE_URL . self::URI_LEFTNAV_CATEGORY, $param);
}
}
... ...
... ... @@ -215,7 +215,7 @@ class UserData
* @param string $type 请求类型 get,post
* @return array YOHO币接口返回的数据
*/
public static function yohoCoinData($uid, $page = 1, $limit = 10,$type = 'get')
public static function yohoCoinData($uid, $page = 1, $limit = 10, $type = 'get')
{
$param = Yohobuy::param();
$param['method'] = 'app.yohocoin.lists';
... ... @@ -386,7 +386,7 @@ class UserData
{
$param = Yohobuy::param();
$param['uid'] = $uid;
$param['udid'] = $udid . '13686403';// 为了兼容udid长度
$param['udid'] = $udid . '13686403'; // 为了兼容udid长度
$param['is_reliable'] = $reliable;
$param['suggest_id'] = $suggest_id;
$param['client_secret'] = Sign::getSign($param);
... ... @@ -458,24 +458,24 @@ class UserData
public static function helpListData()
{
$param = Yohobuy::param();
$param['method'] = 'app.help.li';
$param['method'] = 'app.help.li';
$param['client_secret'] = Sign::getSign($param);
return Yohobuy::get(Yohobuy::API_URL, $param);
}
/**
* 帮助详情接口
*
* @param string $code 具体一条帮助的code
* @return array 接口返回的数据
*/
/**
* 帮助详情接口
*
* @param string $code 具体一条帮助的code
* @return array 接口返回的数据
*/
public static function helpDetailData($code)
{
$param = Yohobuy::param();
$param['method'] = 'app.help.detail';
$param['return_type'] = 'html';
$param['code'] = $code;
$param['method'] = 'app.help.detail';
$param['return_type'] = 'html';
$param['code'] = $code;
$param['client_secret'] = Sign::getSign($param);
return Yohobuy::get(Yohobuy::API_URL, $param, true, true);
... ...
<?php
namespace LibModels\Wap\Passport;
use Api\Yohobuy;
... ... @@ -15,19 +16,20 @@ use Api\Sign;
*/
class BackData
{
/**
* 获取地区数据
*
* @return array 地区数据
*/
/**
* 获取地区数据
*
* @return array 地区数据
*/
public static function getAreasData()
{
// 构建必传参数
$param = Yohobuy::param();
// 构建必传参数
$param = Yohobuy::param();
$param['method'] = 'app.passport.getArea';
$param['method'] = 'app.passport.getArea';
$param['client_secret'] = Sign::getSign($param);
return Yohobuy::get(Yohobuy::API_URL, $param);
}
... ... @@ -39,13 +41,13 @@ class BackData
*/
public static function sendCodeToEmail($email)
{
// 构建必传参数
$param = Yohobuy::param();
// 构建必传参数
$param = Yohobuy::param();
$param['email'] = $email;
$param['method'] = 'app.register.backpwdByEmail';
$param['email'] = $email;
$param['method'] = 'app.register.backpwdByEmail';
$param['client_secret'] = Sign::getSign($param);
return Yohobuy::get(Yohobuy::API_URL, $param);
}
... ... @@ -58,16 +60,14 @@ class BackData
*/
public static function modifyPasswordByEmail($pwd, $code)
{
$param['pwd'] = $pwd;
$param['re-input'] = $pwd;
$param['code'] = $code;
$param['pwd'] = $pwd;
$param['re-input'] = $pwd;
$param['code'] = $code;
// 默认返回的不是json类型数据,是html
return Yohobuy::get(Yohobuy::YOHOBUY_URL.'passport/back/update', $param, true);
return Yohobuy::get(Yohobuy::YOHOBUY_URL . 'passport/back/update', $param, true);
}
/**
* 通过手机找回密码
*
... ... @@ -77,14 +77,14 @@ class BackData
*/
public static function sendCodeToMobile($mobile, $area = 86)
{
// 构建必传参数
$param = Yohobuy::param();
// 构建必传参数
$param = Yohobuy::param();
$param['mobile'] = $mobile;
$param['area'] = $area;
$param['method'] = 'app.register.sendBackpwdCodeToMobile';
$param['mobile'] = $mobile;
$param['area'] = $area;
$param['method'] = 'app.register.sendBackpwdCodeToMobile';
$param['client_secret'] = Sign::getSign($param);
return Yohobuy::get(Yohobuy::API_URL, $param);
}
... ... @@ -98,15 +98,15 @@ class BackData
*/
public static function validateMobileCode($mobile, $code, $area = 86)
{
// 构建必传参数
$param = Yohobuy::param();
// 构建必传参数
$param = Yohobuy::param();
$param['mobile'] = $mobile;
$param['code'] = $code;
$param['area'] = $area;
$param['method'] = 'app.register.validBackpwdCode';
$param['mobile'] = $mobile;
$param['code'] = $code;
$param['area'] = $area;
$param['method'] = 'app.register.validBackpwdCode';
$param['client_secret'] = Sign::getSign($param);
return Yohobuy::get(Yohobuy::API_URL, $param);
}
... ... @@ -120,16 +120,17 @@ class BackData
*/
public static function modifyPasswordByMobile($mobile, $token, $newpwd, $area = 86)
{
// 构建必传参数
$param = Yohobuy::param();
$param['mobile'] = $mobile;
$param['token'] = $token;
$param['newpwd'] = $newpwd;
$param['area'] = $area;
$param['method'] = 'app.register.changepwdByMobileCode';
// 构建必传参数
$param = Yohobuy::param();
$param['mobile'] = $mobile;
$param['token'] = $token;
$param['newpwd'] = $newpwd;
$param['area'] = $area;
$param['method'] = 'app.register.changepwdByMobileCode';
$param['client_secret'] = Sign::getSign($param);
return Yohobuy::get(Yohobuy::API_URL, $param);
}
}
... ...
... ... @@ -90,12 +90,10 @@ class BindData
$param['open_id'] = $openId;
$param['source_type'] = $sourceType;
$param['area'] = $area;
if (!empty($nickname))
{
if (!empty($nickname)) {
$param['nickname'] = $nickname;
}
if (!empty($password))
{
if (!empty($password)) {
$param['password'] = $password;
}
$param['client_secret'] = Sign::getSign($param);
... ...
... ... @@ -79,7 +79,7 @@ class LoginData
if (!empty($shoppingKey)) {
$param['shopping_key'] = $shoppingKey;
}
$param['client_secret'] = Sign::getSign($param);
return Yohobuy::get(Yohobuy::API_URL, $param);
... ...
... ... @@ -165,7 +165,7 @@ class RegData
$param['password'] = $password;
$param['client_secret'] = Sign::getSign($param);
return Yohobuy::post(Yohobuy::API_URL, $param);
return Yohobuy::post(Yohobuy::API_URL, $param);
}
}
... ...
... ... @@ -57,7 +57,7 @@ class DetailData
$param['method'] = 'h5.product.intro';
$param['productskn'] = $productSkn;
$param['client_secret'] = Sign::getSign($param);
return Yohobuy::get(Yohobuy::API_URL, $param);
}
... ... @@ -77,7 +77,7 @@ class DetailData
$param['page'] = $pageNum;
$param['limit'] = $pageSize;
$param['client_secret'] = Sign::getSign($param);
return Yohobuy::get(Yohobuy::API_URL, $param);
}
... ... @@ -97,7 +97,7 @@ class DetailData
$param['page'] = $pageNum;
$param['limit'] = $pageSize;
$param['client_secret'] = Sign::getSign($param);
return Yohobuy::get(Yohobuy::API_URL, $param);
}
... ... @@ -135,7 +135,7 @@ class DetailData
$param['uid'] = $uid;
$param['client_secret'] = Sign::getSign($param);
return Yohobuy::post(Yohobuy::API_URL, $param);
return Yohobuy::post(Yohobuy::API_URL, $param);
}
}
... ...
... ... @@ -75,7 +75,6 @@ class RecomData
// $param['client_secret'] = Sign::getSign($param);
//
// return Yohobuy::get(Yohobuy::API_URL, $param);
// 人气单品
$param = array(
array(
... ... @@ -84,11 +83,10 @@ class RecomData
'order' => 's_n_desc',
'viewNum' => $limit,
'msort' => '10',
),
),
'N', false
);
$result['top'] = Yohobuy::yarClient(Yohobuy::SERVICE_URL . '/search/service/v1/product', 'search', $param, 3600); // 缓存1小时
// 新品到着
$param = array(
array('status' => 1, 'stocknumber' => 1, 'gender' => ''),
... ... @@ -98,11 +96,11 @@ class RecomData
array('misort' => 280, 'viewNum' => 10), //玩具娱乐
array('misort' => 101, 'viewNum' => 10), //办公文具
array('misort' => 259, 'viewNum' => 10), //美妆
),
),
false
);
$result['new'] = Yohobuy::yarClient(Yohobuy::SERVICE_URL . '/search/service/v1/product', 'searchBySortList', $param, 3600); // 缓存1小时
return $result;
}
... ...
... ... @@ -61,7 +61,7 @@ class Cache
public static function get($key, $node = 'master')
{
$result = array();
try {
// WINDOWS
if (DIRECTORY_SEPARATOR === '\\') {
... ... @@ -74,7 +74,7 @@ class Cache
} catch (Exception $e) {
$result = array();
}
return $result;
}
... ...
... ... @@ -269,8 +269,8 @@ class FloorProcess
foreach ($data as $key => &$value) {
if ($key == 'title') {
$urlParam = array('id' => 4);
isset(self::$channel[$type]) && $urlParam['gender'] = self::$channel[$type];
$urlParam = array('id' => 4);
isset(self::$channel[$type]) && $urlParam['gender'] = self::$channel[$type];
$value['more_url'] = Helpers::url('', $urlParam, 'guang');
}
if ($key == 'list') {
... ...
... ... @@ -62,7 +62,7 @@ class ListProcess
$filters = array('classify' => array());
// 返回数据中有没有gender时要添加gender
$data['gender'] = array('2,3'=>'GIRLS','1,3'=>'BOYS');
$data['gender'] = array('2,3' => 'GIRLS', '1,3' => 'BOYS');
$num = 1;
foreach ($data as $key => $val) {
... ... @@ -247,8 +247,8 @@ class ListProcess
private static function priceRange($data)
{
// 首先对价格进行排序
ksort($data, SORT_NUMERIC);
// 首先对价格进行排序
ksort($data, SORT_NUMERIC);
$result = array(
'title' => '价格',
... ...
... ... @@ -237,8 +237,8 @@ class Helpers
}
$result['is_soon_sold_out'] = ($productData['is_soon_sold_out'] === 'Y');
$result['url'] = self::url('/product/pro_' . $productData['product_id'] . '_'
. $productData['goods_list'][0]['goods_id']
. '/' . $productData['cn_alphabet'] . '.html');
. $productData['goods_list'][0]['goods_id']
. '/' . $productData['cn_alphabet'] . '.html');
// APP访问需要加附加的参数
// 备注:如果以后APP的接口太多,可以把这边参数提取出来,变成一个公共的方法来生成,便于以后管理维护
if ($isApp) {
... ... @@ -260,7 +260,7 @@ class Helpers
}
// 打折与其它组合则隐藏打折
elseif ($result['tags']['is_discount'] &&
($result['tags']['is_new'] || $result['tags']['is_limited'] || $result['tags']['is_yohood'] || $result['tags']['is_advance'])) {
($result['tags']['is_new'] || $result['tags']['is_limited'] || $result['tags']['is_yohood'] || $result['tags']['is_advance'])) {
$result['tags']['is_discount'] = false;
}
// YOHOOD和新品组合显示YOHOOD
... ... @@ -750,7 +750,7 @@ class Helpers
public static function syncUserSession($uid, $refer = '', $callback = 'call')
{
return 'http://mapi.yohobuy.com/Passport/session/index?callback=' . $callback
. '&sign=' . md5(md5($uid . 'Js8Yn0!EwPM45-ws')) . '&uid=' . $uid . '&go=' . $refer;
. '&sign=' . md5(md5($uid . 'Js8Yn0!EwPM45-ws')) . '&uid=' . $uid . '&go=' . $refer;
}
/**
... ... @@ -766,7 +766,7 @@ class Helpers
public static function logoutSession($token, $refer = '', $callback = 'call')
{
return 'http://mapi.yohobuy.com/Passport/session/logout?callback=' . $callback
. '&sign=' . md5(md5('Js8Yn0!EwPM45-ws')) . '&token=' . $token . '&go=' . $refer;
. '&sign=' . md5(md5('Js8Yn0!EwPM45-ws')) . '&token=' . $token . '&go=' . $refer;
}
}
... ...
... ... @@ -103,114 +103,98 @@ class Images
return $domain;
}
/**
* 图片上传
* @param string $name 文件表单name, 即用于$_FILES[$name]
*/
public static function saveImage($name)
{
if (empty($_FILES[$name])) {
return array();
}
$files = $_FILES[$name];
$images = array();
if (is_array($files['tmp_name'])) {
foreach ($files['tmp_name'] as $k => $tmp_name) {
if (!empty($tmp_name)) {
$images[$files['name'][$k]] = $tmp_name;
}
}
} else {
$images[$files['name']] = $files['tmp_name'];
}
return self::uploadStreamImage($images);
}
/**
* 图片上传
* @param string $name 文件表单name, 即用于$_FILES[$name]
*/
public static function saveImage($name)
{
if (empty($_FILES[$name]))
{
return array();
}
$files = $_FILES[$name];
$images = array();
if (is_array($files['tmp_name']))
{
foreach ($files['tmp_name'] as $k => $tmp_name)
{
if(!empty($tmp_name))
{
$images[$files['name'][$k]] = $tmp_name;
}
}
}
else
{
$images[$files['name']] = $files['tmp_name'];
}
return self::uploadStreamImage($images);
}
/**
* 上传图片[图片上传域名限制于http://test.service.api.yohobuy.com]
*
* @param string | array(filename => absolute file path) $file
* url:http://upload.static.yohobuy.com?project=sns&fileData=xxx
* @return mixed
*/
public static function uploadStreamImage($file)
{
$end ="\r\n";
$twoHyphens ="--";
$boundary = "*****";
$stream = '';
$files = is_array($file) ? $file : array($file);
foreach($files as $name => $filename)
{
if(!file_exists($filename))
{
continue;
}
$name = is_numeric($name) ? name.'.jpg' : $name;
$stream .= $twoHyphens.$boundary.$end;
$stream .="Content-Disposition: form-data; "."name=\"fileData\";filename=\"".$name ."\"".$end; // form file element name :fileData
$stream .= $end;
$stream .= file_get_contents($filename);
$stream .= $end;
}
if(empty($stream))
{
return false;
}
$stream .= $twoHyphens.$boundary.$end;
$stream .="Content-Disposition: form-data; "."name=\"project\"".$end;
$stream .= $end;
$stream .= "suggest";//project sns
$stream .= $end;
$stream .= $twoHyphens .$boundary .$twoHyphens .$end;
$opts = array(
'http' => array(
'method' => 'POST',
'header' => 'content-type:multipart/form-data;boundary='.$boundary,
'content' => $stream
)
);
$context = stream_context_create($opts);
$result = json_decode(file_get_contents('http://upload.static.yohobuy.com', false, $context), true);
if(!empty($result['data']['imagesList']))
{
$imgExtra = '?imageMogr2/thumbnail/130x130/extent/130x130/background/d2hpdGU=/position/center/quality/90';
$imgList = array('imgList'=>array());
if(count($file) == 1 || !is_array($file))
{
$imgRelUrl = current($result['data']['imagesList']);
$imgList['imgList'][] = array(
'imgUrl' => self::getSourceUrl($imgRelUrl, 'suggest') . $imgExtra,
'imgRelUrl' => $imgRelUrl
);
}
else
{
$img = array();
foreach ($result['data']['imagesList'] as $val) {
$img = array();
$img['imgUrl'] = self::getSourceUrl($val, 'suggest') . $imgExtra;
$img['imgRelUrl'] = $val;
$imgList['imgList'][] = $img;
}
}
return $imgList;
}
else
{
return false;
}
}
/**
* 上传图片[图片上传域名限制于http://test.service.api.yohobuy.com]
*
* @param string | array(filename => absolute file path) $file
* url:http://upload.static.yohobuy.com?project=sns&fileData=xxx
* @return mixed
*/
public static function uploadStreamImage($file)
{
$end = "\r\n";
$twoHyphens = "--";
$boundary = "*****";
$stream = '';
$files = is_array($file) ? $file : array($file);
foreach ($files as $name => $filename) {
if (!file_exists($filename)) {
continue;
}
$name = is_numeric($name) ? name . '.jpg' : $name;
$stream .= $twoHyphens . $boundary . $end;
$stream .="Content-Disposition: form-data; " . "name=\"fileData\";filename=\"" . $name . "\"" . $end; // form file element name :fileData
$stream .= $end;
$stream .= file_get_contents($filename);
$stream .= $end;
}
if (empty($stream)) {
return false;
}
$stream .= $twoHyphens . $boundary . $end;
$stream .="Content-Disposition: form-data; " . "name=\"project\"" . $end;
$stream .= $end;
$stream .= "suggest"; //project sns
$stream .= $end;
$stream .= $twoHyphens . $boundary . $twoHyphens . $end;
$opts = array(
'http' => array(
'method' => 'POST',
'header' => 'content-type:multipart/form-data;boundary=' . $boundary,
'content' => $stream
)
);
$context = stream_context_create($opts);
$result = json_decode(file_get_contents('http://upload.static.yohobuy.com', false, $context), true);
if (!empty($result['data']['imagesList'])) {
$imgExtra = '?imageMogr2/thumbnail/130x130/extent/130x130/background/d2hpdGU=/position/center/quality/90';
$imgList = array('imgList' => array());
if (count($file) == 1 || !is_array($file)) {
$imgRelUrl = current($result['data']['imagesList']);
$imgList['imgList'][] = array(
'imgUrl' => self::getSourceUrl($imgRelUrl, 'suggest') . $imgExtra,
'imgRelUrl' => $imgRelUrl
);
} else {
$img = array();
foreach ($result['data']['imagesList'] as $val) {
$img = array();
$img['imgUrl'] = self::getSourceUrl($val, 'suggest') . $imgExtra;
$img['imgRelUrl'] = $val;
$imgList['imgList'][] = $img;
}
}
return $imgList;
} else {
return false;
}
}
/**
* 获取模板的图片地址
... ...
<?php
<?php
namespace Plugin;
/**
* LightnCandy static class for compiled template runtime methods.
*/
class LCRun3 {
class LCRun3
{
const DEBUG_ERROR_LOG = 1;
const DEBUG_ERROR_EXCEPTION = 2;
const DEBUG_TAGS = 4;
... ... @@ -20,7 +24,8 @@ class LCRun3 {
* @expect '{{123}}' when input '123', 'miss', array('flags' => array('debug' => LCRun3::DEBUG_TAGS), 'lcrun' => 'LCRun3'), ''
* @expect '<!--MISSED((-->{{#123}}<!--))--><!--SKIPPED--><!--MISSED((-->{{/123}}<!--))-->' when input '123', 'wi', array('flags' => array('debug' => LCRun3::DEBUG_TAGS_HTML), 'lcrun' => 'LCRun3'), false, false, function () {return 'A';}
*/
public static function debug($v, $f, $cx) {
public static function debug($v, $f, $cx)
{
$params = array_slice(func_get_args(), 2);
$r = call_user_func_array((isset($cx['funcs'][$f]) ? $cx['funcs'][$f] : "{$cx['lcrun']}::$f"), $params);
... ... @@ -28,9 +33,9 @@ class LCRun3 {
$ansi = $cx['flags']['debug'] & (self::DEBUG_TAGS_ANSI - self::DEBUG_TAGS);
$html = $cx['flags']['debug'] & (self::DEBUG_TAGS_HTML - self::DEBUG_TAGS);
$cs = ($html ? (($r !== '') ? '<!!--OK((-->' : '<!--MISSED((-->') : '')
. ($ansi ? (($r !== '') ? "\033[0;32m" : "\033[0;31m") : '');
. ($ansi ? (($r !== '') ? "\033[0;32m" : "\033[0;31m") : '');
$ce = ($html ? '<!--))-->' : '')
. ($ansi ? "\033[0m" : '');
. ($ansi ? "\033[0m" : '');
switch ($f) {
case 'sec':
case 'ifv':
... ... @@ -59,7 +64,8 @@ class LCRun3 {
* @param array<string,array|string|integer> $cx render time context
* @param string $v expression
*/
public static function miss($cx, $v) {
public static function miss($cx, $v)
{
$e = "LCRun3: $v is not exist";
if ($cx['flags']['debug'] & self::DEBUG_ERROR_LOG) {
error_log($e);
... ... @@ -84,7 +90,8 @@ class LCRun3 {
* @expect null when input array('scopes' => array(), 'flags' => array('prop' => 0, 'method' => 0, 'mustlok' => 0)), (Object) array('a' => array('b' => 3)), array('a', 'b')
* @expect 3 when input array('scopes' => array(), 'flags' => array('prop' => 1, 'method' => 0, 'mustlok' => 0)), (Object) array('a' => array('b' => 3)), array('a', 'b')
*/
public static function v($cx, $base, $path) {
public static function v($cx, $base, $path)
{
$count = count($cx['scopes']);
while ($base) {
$v = $base;
... ... @@ -143,7 +150,8 @@ class LCRun3 {
* @expect true when input array(), array('')
* @expect true when input array(), array(0)
*/
public static function ifvar($cx, $v) {
public static function ifvar($cx, $v)
{
return !is_null($v) && ($v !== false) && ($v !== 0) && ($v !== 0.0) && ($v !== '') && (is_array($v) ? (count($v) > 0) : true);
}
... ... @@ -163,7 +171,8 @@ class LCRun3 {
* @expect 'Y' when input array('scopes' => array()), 1, array(), function () {return 'Y';}
* @expect 'N' when input array('scopes' => array()), null, array(), function () {return 'Y';}, function () {return 'N';}
*/
public static function ifv($cx, $v, $in, $truecb, $falsecb = null) {
public static function ifv($cx, $v, $in, $truecb, $falsecb = null)
{
$ret = '';
if (self::ifvar($cx, $v)) {
if ($truecb) {
... ... @@ -198,7 +207,8 @@ class LCRun3 {
* @expect 'Y' when input array('scopes' => array()), null, array(), function () {return 'Y';}, function () {return 'N';}
* @expect 'N' when input array('scopes' => array()), true, array(), function () {return 'Y';}, function () {return 'N';}
*/
public static function unl($cx, $var, $in, $truecb, $falsecb = null) {
public static function unl($cx, $var, $in, $truecb, $falsecb = null)
{
return self::ifv($cx, $var, $in, $falsecb, $truecb);
}
... ... @@ -217,7 +227,8 @@ class LCRun3 {
* @expect true when input array(), array()
* @expect false when input array(), array('1')
*/
public static function isec($cx, $v) {
public static function isec($cx, $v)
{
return is_null($v) || ($v === false) || (is_array($v) && (count($v) === 0));
}
... ... @@ -243,7 +254,8 @@ class LCRun3 {
* @expect 'a,' when input array('flags' => array('jstrue' => 0, 'jsobj' => 1)), array('a',false)
* @expect 'a,false' when input array('flags' => array('jstrue' => 1, 'jsobj' => 1)), array('a',false)
*/
public static function raw($cx, $v) {
public static function raw($cx, $v)
{
if ($v === true) {
if ($cx['flags']['jstrue']) {
return 'true';
... ... @@ -287,7 +299,8 @@ class LCRun3 {
* @expect 'a&amp;b' when input array(), 'a&b'
* @expect 'a&#039;b' when input array(), 'a\'b'
*/
public static function enc($cx, $var) {
public static function enc($cx, $var)
{
return htmlentities(self::raw($cx, $var), ENT_QUOTES, 'UTF-8');
}
... ... @@ -304,7 +317,8 @@ class LCRun3 {
* @expect 'a&#x27;b' when input array(), 'a\'b'
* @expect '&#x60;a&#x27;b' when input array(), '`a\'b'
*/
public static function encq($cx, $var) {
public static function encq($cx, $var)
{
return preg_replace('/`/', '&#x60;', preg_replace('/&#039;/', '&#x27;', htmlentities(self::raw($cx, $var), ENT_QUOTES, 'UTF-8')));
}
... ... @@ -345,7 +359,8 @@ class LCRun3 {
* @expect '268' when input array('flags' => array('spvar' => 1), 'sp_vars'=>array('root' => 0)), array(1,3,4), 0, false, function ($c, $i) {return $i * 2;}
* @expect '038' when input array('flags' => array('spvar' => 1), 'sp_vars'=>array('root' => 0)), array(1,3,'a'=>4), 0, true, function ($c, $i) {return $i * $c['sp_vars']['index'];}
*/
public static function sec($cx, $v, $in, $each, $cb, $else = null) {
public static function sec($cx, $v, $in, $each, $cb, $else = null)
{
$isAry = is_array($v) || ($v instanceof ArrayObject);
$isTrav = $v instanceof Traversable;
$loop = $each;
... ... @@ -461,7 +476,8 @@ class LCRun3 {
* @expect '{"a":"b"}' when input array(), array('a'=>'b'), array('a'=>'c'), function ($c, $i) {return json_encode($i);}
* @expect '-b=' when input array(), 'b', array('a'=>'b'), function ($c, $i) {return "-$i=";}
*/
public static function wi($cx, $v, $in, $cb, $else = null) {
public static function wi($cx, $v, $in, $cb, $else = null)
{
if (($v === false) || ($v === null)) {
return $else ? $else($cx, $in) : '';
}
... ... @@ -481,7 +497,8 @@ class LCRun3 {
* @return string The rendered string of the partial
*
*/
public static function p($cx, $p, $v, $sp = '') {
public static function p($cx, $p, $v, $sp = '')
{
$param = $v[0][0];
if (is_array($v[1])) {
... ... @@ -512,7 +529,8 @@ class LCRun3 {
* @expect '=&#x27;=' when input array('helpers' => array('a' => function ($i) {return "=$i[0]=";})), 'a', array(array('\''),array()), 'encq'
* @expect '=b=' when input array('helpers' => array('a' => function ($i,$j) {return "={$j['a']}=";})), 'a', array(array(),array('a' => 'b')), 'raw'
*/
public static function ch($cx, $ch, $vars, $op) {
public static function ch($cx, $ch, $vars, $op)
{
return self::chret(call_user_func_array($cx['helpers'][$ch], $vars), $op);
}
... ... @@ -534,7 +552,8 @@ class LCRun3 {
* @expect '=&=' when input array('=&=', 'raw'), 'enc'
* @expect '=&amp;&#x27;=' when input array('=&\'=', 'encq'), 'raw'
*/
public static function chret($ret, $op) {
public static function chret($ret, $op)
{
if (is_array($ret)) {
if (isset($ret[1]) && $ret[1]) {
$op = $ret[1];
... ... @@ -564,7 +583,8 @@ class LCRun3 {
*
* @return string The rendered string of the token
*/
public static function hbch($cx, $ch, $vars, $op, $inverted, $cb = null, $else = null) {
public static function hbch($cx, $ch, $vars, $op, $inverted, $cb = null, $else = null)
{
$isBlock = (is_object($cb) && ($cb instanceof Closure));
$args = $vars[0];
$options = array(
... ... @@ -628,7 +648,7 @@ class LCRun3 {
$e = "LCRun3: call custom helper '$ch' error: " . $E->getMessage();
}
if($e !== null) {
if ($e !== null) {
if ($cx['flags']['debug'] & self::DEBUG_ERROR_LOG) {
error_log($e);
}
... ... @@ -657,7 +677,8 @@ class LCRun3 {
* @expect '2.6.5' when input array('blockhelpers' => array('a' => function ($cx,$in) {return array($cx,$in[0],5);})), 'a', array('6', 0), 2, false, function($cx, $i) {return implode('.', $i);}
* @expect '' when input array('blockhelpers' => array('a' => function ($cx,$in) {})), 'a', array('6', 0), 2, false, function($cx, $i) {return implode('.', $i);}
*/
public static function bch($cx, $ch, $vars, $in, $inverted, $cb, $else = null) {
public static function bch($cx, $ch, $vars, $in, $inverted, $cb, $else = null)
{
$r = call_user_func($cx['blockhelpers'][$ch], $in, $vars[0], $vars[1]);
// $invert the logic
... ... @@ -684,4 +705,5 @@ class LCRun3 {
return $ret;
}
}
\ No newline at end of file
}
... ...
... ... @@ -6,26 +6,23 @@
* Date: 14-1-12
* Time: 16:32
*/
namespace Plugin;
use Yaf\View_Interface;
use Yaf\View;
use Yaf\Application;
class Layout implements View_Interface
{
public $breadcrumb = array();
public $breadcrumb = array();
public $engine;
protected $options = array();
protected $layout_path;
protected $layout;
protected $content;
protected $tpl_vars = array();
protected $tpl_dir;
public function __construct($path, $options = array())
... ... @@ -36,9 +33,8 @@ class Layout implements View_Interface
protected function engine()
{
$this->engine = $this->engine ?: new View\Simple(
$this->tpl_dir,
$this->options
$this->engine = $this->engine ? : new View\Simple(
$this->tpl_dir, $this->options
);
return $this->engine;
}
... ... @@ -129,8 +125,7 @@ class Layout implements View_Interface
$tpl_vars['content'] = $this->content;
$this->engine()->assign('breadcrumb', $this->breadcrumb);
return $this->engine()->render(
$this->getLayoutPath(),
$tpl_vars
$this->getLayoutPath(), $tpl_vars
);
}
... ... @@ -138,4 +133,5 @@ class Layout implements View_Interface
{
echo $this->render($tpl, $tpl_vars);
}
}
... ...
<?php
/*
Copyrights for code authored by Yahoo! Inc. is licensed under the following terms:
MIT License
Copyright (c) 2013-2015 Yahoo! Inc. All Rights Reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Copyrights for code authored by Yahoo! Inc. is licensed under the following terms:
MIT License
Copyright (c) 2013-2015 Yahoo! Inc. All Rights Reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Origin: https://github.com/zordius/lightncandy
*/
Origin: https://github.com/zordius/lightncandy
*/
/**
* This is abstract engine which defines must-have methods.
... ... @@ -17,27 +18,26 @@ Origin: https://github.com/zordius/lightncandy
* @package LightnCandy
* @author Zordius <zordius@yahoo-inc.com>
*/
/**
* LightnCandy static core class.
*/
namespace Plugin;
class LightnCandy {
class LightnCandy
{
// Compile time error handling flags
const FLAG_ERROR_LOG = 1;
const FLAG_ERROR_EXCEPTION = 2;
const FLAG_ERROR_SKIPPARTIAL = 4194304;
// Compile the template as standalone PHP code which can execute without including LightnCandy
const FLAG_STANDALONE = 4;
const FLAG_BARE = 33554432;
const FLAG_NOESCAPE = 67108864;
// JavaScript compatibility
const FLAG_JSTRUE = 8;
const FLAG_JSOBJECT = 16;
// Handlebars.js compatibility
const FLAG_THIS = 32;
const FLAG_WITH = 64;
... ... @@ -49,22 +49,18 @@ class LightnCandy {
const FLAG_SPVARS = 4096;
const FLAG_SLASH = 8388608;
const FLAG_ELSE = 16777216;
// PHP behavior flags
const FLAG_EXTHELPER = 8192;
const FLAG_ECHO = 16384;
const FLAG_PROPERTY = 32768;
const FLAG_METHOD = 65536;
const FLAG_RUNTIMEPARTIAL = 1048576;
// Mustache compatibility
const FLAG_MUSTACHESP = 131072;
const FLAG_MUSTACHELOOKUP = 262144;
const FLAG_MUSTACHEPAIN = 2097152;
// Template rendering time debug flags
const FLAG_RENDER_DEBUG = 524288;
// alias flags
const FLAG_BESTPERFORMANCE = 16384; // FLAG_ECHO
const FLAG_JS = 24; // FLAG_JSTRUE + FLAG_JSOBJECT
... ... @@ -72,12 +68,10 @@ class LightnCandy {
const FLAG_HANDLEBARS = 27402208; // FLAG_THIS + FLAG_WITH + FLAG_PARENT + FLAG_JSQUOTE + FLAG_ADVARNAME + FLAG_SPACECTL + FLAG_NAMEDARG + FLAG_SPVARS + FLAG_SLASH + FLAG_ELSE + FLAG_MUSTACHESP + FLAG_MUSTACHEPAIN
const FLAG_HANDLEBARSJS = 27402232; // FLAG_JS + FLAG_HANDLEBARS
const FLAG_INSTANCE = 98304; // FLAG_PROPERTY + FLAG_METHOD
// RegExps
const VARNAME_SEARCH = '/(\\[[^\\]]+\\]|[^\\[\\]\\.]+)/';
const EXTENDED_COMMENT_SEARCH = '/{{!--.*?--}}/s';
const IS_SUBEXP_SEARCH = '/^\(.+\)$/s';
// Positions of matched token
const POS_LOTHER = 1;
const POS_LSPACE = 2;
... ... @@ -101,7 +95,8 @@ class LightnCandy {
*
* @return string|false Compiled PHP code when successed. If error happened and compile failed, return false.
*/
public static function compile($template, $options = array('flags' => self::FLAG_BESTPERFORMANCE)) {
public static function compile($template, $options = array('flags' => self::FLAG_BESTPERFORMANCE))
{
$context = static::buildContext($options);
if (static::handleError($context)) {
... ... @@ -141,7 +136,8 @@ class LightnCandy {
/**
* Include all partials when using dynamic partials
*/
protected static function handleDynamicPartial(&$context) {
protected static function handleDynamicPartial(&$context)
{
if ($context['usedFeature']['dynpartial'] == 0) {
return;
}
... ... @@ -162,7 +158,8 @@ class LightnCandy {
* @expect 'a\\\\bc' when input 'a\bc'
* @expect 'a\\\'bc' when input 'a\'bc'
*/
protected static function escapeTemplate($template) {
protected static function escapeTemplate($template)
{
return addcslashes(addcslashes($template, '\\'), "'");
}
... ... @@ -173,7 +170,8 @@ class LightnCandy {
* @param string $left left string of a token
* @param string $right right string of a token
*/
protected static function setupToken(&$context, $left = '{{', $right = '}}') {
protected static function setupToken(&$context, $left = '{{', $right = '}}')
{
if (preg_match('/=/', "$left$right")) {
$context['error'][] = "Can not set delimiter contains '=' , you try to set delimiter as '$left' and '$right'.";
return;
... ... @@ -200,9 +198,10 @@ class LightnCandy {
* @param array<string,array|string|integer> $context Current context
* @param string $template handlebars template
*/
protected static function verifyTemplate(&$context, $template) {
protected static function verifyTemplate(&$context, $template)
{
while (preg_match($context['tokens']['search'], $template, $matches)) {
$context['tokens']['count']++;
$context['tokens']['count'] ++;
static::scanFeatures($matches, $context);
$template = $matches[self::POS_ROTHER];
}
... ... @@ -217,7 +216,8 @@ class LightnCandy {
*
* @return string generated PHP code
*/
protected static function compileTemplate(&$context, $template, $partial = '') {
protected static function compileTemplate(&$context, $template, $partial = '')
{
// Check for recursive partial
if ($partial && !$context['flags']['runpart']) {
$context['partialStack'][] = $partial;
... ... @@ -245,7 +245,7 @@ class LightnCandy {
}
}
$context['tokens']['current']++;
$context['tokens']['current'] ++;
$tmpl = static::compileToken($matches, $context);
if ($tmpl == $context['ops']['seperator']) {
$tmpl = '';
... ... @@ -271,7 +271,8 @@ class LightnCandy {
*
* @return string Composed PHP code
*/
protected static function composePHPRender($context, $code) {
protected static function composePHPRender($context, $code)
{
$flagJStrue = static::getBoolStr($context['flags']['jstrue']);
$flagJSObj = static::getBoolStr($context['flags']['jsobj']);
$flagSPVar = static::getBoolStr($context['flags']['spvar']);
... ... @@ -324,7 +325,8 @@ $libstr
*
* @return array<string,array|string|integer> Context from options
*/
protected static function buildContext($options) {
protected static function buildContext($options)
{
if (!is_array($options)) {
$options = array();
}
... ... @@ -423,7 +425,7 @@ $libstr
'cnd_then' => '{echo ',
'cnd_else' => ';}else{echo ',
'cnd_end' => ';}echo ',
) : array(
) : array(
'seperator' => '.',
'f_start' => 'return ',
'f_end' => ';',
... ... @@ -458,7 +460,8 @@ $libstr
* @expect array('flags' => array('exhlp' => 1), 'helpers' => array('LCRun3::raw' => 'LCRun3::raw')) when input array('flags' => array('exhlp' => 1), 'helpers' => array()), array('helpers' => array('LCRun3::raw'))
* @expect array('flags' => array('exhlp' => 1), 'helpers' => array('test' => 'LCRun3::raw')) when input array('flags' => array('exhlp' => 1), 'helpers' => array()), array('helpers' => array('test' => 'LCRun3::raw'))
*/
protected static function buildHelperTable($context, $options, $tname = 'helpers') {
protected static function buildHelperTable($context, $options, $tname = 'helpers')
{
if (isset($options[$tname]) && is_array($options[$tname])) {
foreach ($options[$tname] as $name => $func) {
if (is_callable($func)) {
... ... @@ -483,8 +486,9 @@ $libstr
* @param string $name partial name
* @param array<string,array|string|integer> $context Current context of compiler progress.
*/
protected static function readPartial($name, &$context) {
$context['usedFeature']['partial']++;
protected static function readPartial($name, &$context)
{
$context['usedFeature']['partial'] ++;
if (isset($context['usedPartial'][$name])) {
return;
... ... @@ -498,7 +502,7 @@ $libstr
if (preg_match(static::IS_SUBEXP_SEARCH, $name)) {
if ($context['flags']['runpart']) {
$context['usedFeature']['dynpartial']++;
$context['usedFeature']['dynpartial'] ++;
return;
} else {
$context['error'][] = "You use dynamic partial name as '$name', this only works with option FLAG_RUNTIMEPARTIAL enabled";
... ... @@ -519,7 +523,8 @@ $libstr
*
* @return string|null $content partial content
*/
protected static function resolvePartial(&$name, &$context) {
protected static function resolvePartial(&$name, &$context)
{
if (isset($context['partials'][$name])) {
return $context['partials'][$name];
}
... ... @@ -542,7 +547,8 @@ $libstr
* @param array<string,array|string|integer> $context Current context of compiler progress.
* @param string $content partial content
*/
protected static function compilePartial(&$name, &$context, $content) {
protected static function compilePartial(&$name, &$context, $content)
{
$context['usedPartial'][$name] = static::escapeTemplate($content);
$originalAhead = $context['tokens']['ahead'];
... ... @@ -582,7 +588,8 @@ $libstr
* @expect array('test1') when input array('fileext' => array('test1'))
* @expect array('test2', 'test3') when input array('fileext' => array('test2', 'test3'))
*/
protected static function buildCXFileext($options) {
protected static function buildCXFileext($options)
{
$exts = isset($options['fileext']) ? $options['fileext'] : '.tmpl';
return is_array($exts) ? $exts : array($exts);
}
... ... @@ -600,7 +607,8 @@ $libstr
* @expect array('src') when input array('basedir' => array('src', 'dir_not_found'))
* @expect array('src', 'tests') when input array('basedir' => array('src', 'tests'))
*/
protected static function buildCXBasedir($options) {
protected static function buildCXBasedir($options)
{
$dirs = isset($options['basedir']) ? $options['basedir'] : 0;
$dirs = is_array($dirs) ? $dirs : array($dirs);
$ret = array();
... ... @@ -624,7 +632,8 @@ $libstr
* @expect 'function($a) {return;}' when input function ($a) {return;}
* @expect 'function($a) {return;}' when input function ($a) {return;}
*/
protected static function getPHPCode($closure) {
protected static function getPHPCode($closure)
{
if (is_string($closure) && preg_match('/(.+)::(.+)/', $closure, $matched)) {
$ref = new ReflectionMethod($matched[1], $matched[2]);
} else {
... ... @@ -650,7 +659,8 @@ $libstr
*
* @return string
*/
protected static function exportHelper($context, $tname = 'helpers') {
protected static function exportHelper($context, $tname = 'helpers')
{
$ret = '';
foreach ($context[$tname] as $name => $func) {
if (!isset($context['usedCount'][$tname][$name])) {
... ... @@ -673,7 +683,8 @@ $libstr
*
* @return string
*/
protected static function exportLCRun($context) {
protected static function exportLCRun($context)
{
if ($context['flags']['standalone'] == 0) {
return '';
}
... ... @@ -699,15 +710,15 @@ $libstr
while (true) {
if (array_sum(array_map(function ($name) use (&$exports, $methods) {
$n = 0;
foreach ($methods[$name][1] as $child => $count) {
if (!in_array($child, $exports)) {
$exports[] = $child;
$n++;
}
}
return $n;
}, $exports)) == 0) {
$n = 0;
foreach ($methods[$name][1] as $child => $count) {
if (!in_array($child, $exports)) {
$exports[] = $child;
$n++;
}
}
return $n;
}, $exports)) == 0) {
break;
}
}
... ... @@ -726,7 +737,8 @@ $libstr
*
* @return string
*/
protected static function exportLCRunConstant($context) {
protected static function exportLCRunConstant($context)
{
if ($context['flags']['standalone'] == 0) {
return 'array()';
}
... ... @@ -734,8 +746,8 @@ $libstr
$class = new ReflectionClass($context['lcrun']);
$constants = $class->getConstants();
$ret = " array(\n";
foreach($constants as $name => $value) {
$ret .= " '$name' => ". (is_string($value) ? "'$value'" : $value ) . ",\n";
foreach ($constants as $name => $value) {
$ret .= " '$name' => " . (is_string($value) ? "'$value'" : $value ) . ",\n";
}
$ret .= " )";
return $ret;
... ... @@ -749,14 +761,15 @@ $libstr
*
* @return array<string|array> list of converted code and children array
*/
protected static function scanLCRunDependency($context, $code) {
protected static function scanLCRunDependency($context, $code)
{
$child = array();
$code = preg_replace_callback('/self::(\w+?)\s*\(/', function ($matches) use ($context, &$child) {
if (!isset($child[$matches[1]])) {
$child[$matches[1]] = 0;
}
$child[$matches[1]]++;
$child[$matches[1]] ++;
return "\$cx['funcs']['{$matches[1]}'](";
}, $code);
... ... @@ -778,7 +791,8 @@ $libstr
* @expect false when input array('level' => 0, 'error' => array())
* @expect true when input array('level' => 0, 'error' => array('some error'), 'flags' => array('errorlog' => 0, 'exception' => 0))
*/
protected static function handleError(&$context) {
protected static function handleError(&$context)
{
if ($context['level'] > 0) {
$token = array_pop($context['stack']);
$context['error'][] = "Unclosed token {{{#$token}}} !!";
... ... @@ -810,7 +824,8 @@ $libstr
* @expect 'false' when input 0
* @expect 'false' when input -1
*/
protected static function getBoolStr($v) {
protected static function getBoolStr($v)
{
return ($v > 0) ? 'true' : 'false';
}
... ... @@ -819,7 +834,8 @@ $libstr
*
* @return array<string,array|string|integer> Context data
*/
public static function getContext() {
public static function getContext()
{
return static::$lastContext;
}
... ... @@ -834,7 +850,8 @@ $libstr
*
* @deprecated
*/
public static function prepare($php, $tmpDir = null, $delete = true) {
public static function prepare($php, $tmpDir = null, $delete = true)
{
if (!ini_get('allow_url_include') || !ini_get('allow_url_fopen')) {
if (!is_string($tmpDir) || !is_dir($tmpDir)) {
$tmpDir = sys_get_temp_dir();
... ... @@ -878,7 +895,8 @@ $libstr
* @expect "\$cx['funcs']['test3'](" when input array('flags' => array('standalone' => 1, 'debug' => 0), 'lcrun' => 'LCRun3'), 'test3', ''
* @expect 'LCRun3::debug(\'abc\', \'test\', ' when input array('flags' => array('standalone' => 0, 'debug' => 1), 'lcrun' => 'LCRun3'), 'test', 'abc'
*/
protected static function getFuncName(&$context, $name, $tag) {
protected static function getFuncName(&$context, $name, $tag)
{
static::addUsageCount($context, 'lcrun', $name);
if ($context['flags']['debug'] && ($name != 'miss')) {
... ... @@ -903,7 +921,8 @@ $libstr
* @expect '[a]' when input array('a')
* @expect '[a][b][c]' when input array('a', 'b', 'c')
*/
protected static function getArrayStr($scopes) {
protected static function getArrayStr($scopes)
{
return count($scopes) ? '[' . implode('][', $scopes) . ']' : '';
}
... ... @@ -918,10 +937,11 @@ $libstr
* @expect "['a']" when input array('a')
* @expect "['a']['b']['c']" when input array('a', 'b', 'c')
*/
protected static function getArrayCode($list) {
protected static function getArrayCode($list)
{
return static::getArrayStr(array_map(function ($v) {
return "'$v'";
}, $list));
return "'$v'";
}, $list));
}
/**
... ... @@ -936,7 +956,8 @@ $libstr
* @expect array('array(array($in,$in),array())', array('this', 'this')) when input array(null, null), array('flags'=>array('spvar'=>true))
* @expect array('array(array(),array(\'a\'=>$in))', array('this')) when input array('a' => null), array('flags'=>array('spvar'=>true))
*/
protected static function getVariableNames($vn, &$context) {
protected static function getVariableNames($vn, &$context)
{
$vars = array(array(), array());
$exps = array();
foreach ($vn as $i => $v) {
... ... @@ -960,7 +981,8 @@ $libstr
*
* @return array<string> code representing passed expression
*/
protected static function compileSubExpression($subExpression, &$context, $keepCount = false) {
protected static function compileSubExpression($subExpression, &$context, $keepCount = false)
{
// mock up a token for this expression
$token = array_fill(self::POS_LOTHER, self::POS_ROTHER, '');
... ... @@ -979,14 +1001,14 @@ $libstr
if ($keepCount) {
$context['usedFeature'] = $oldCount;
} else {
$context['usedFeature']['subexp']++;
$context['usedFeature']['subexp'] ++;
// detect handlebars custom helpers.
if (isset($context['hbhelpers'][$vars[0][0]])) {
$context['usedFeature']['hbhelper']++;
$context['usedFeature']['hbhelper'] ++;
} else {
// detect custom helpers.
if (isset($context['helpers'][$vars[0][0]])) {
$context['usedFeature']['helper']++;
$context['usedFeature']['helper'] ++;
}
}
}
... ... @@ -1002,7 +1024,8 @@ $libstr
*
* @return array<string> variable names
*/
protected static function getVariableNameOrSubExpression($var, &$context) {
protected static function getVariableNameOrSubExpression($var, &$context)
{
if (isset($var[0]) && preg_match(static::IS_SUBEXP_SEARCH, $var[0])) {
return static::compileSubExpression($var[0], $context, true);
}
... ... @@ -1037,7 +1060,8 @@ $libstr
* @expect array('((isset($in[\'id\']) && is_array($in)) ? $in[\'id\'] : null)', 'this.[id]') when input array(null, 'id'), array('flags'=>array('spvar'=>true,'debug'=>0,'prop'=>0,'method'=>0,'mustlok'=>0))
* @expect array('LCRun3::v($cx, $in, array(\'id\'))', 'this.[id]') when input array(null, 'id'), array('flags'=>array('prop'=>true,'spvar'=>true,'debug'=>0,'method'=>0,'mustlok'=>0,'standalone'=>0), 'lcrun' => 'LCRun3')
*/
protected static function getVariableName($var, &$context) {
protected static function getVariableName($var, &$context)
{
if (isset($var[0]) && ($var[0] === 0)) {
return array($var[1], preg_replace('/\'(.*)\'/', '$1', $var[1]));
}
... ... @@ -1089,8 +1113,8 @@ $libstr
// the only way is using slower rendering time variable resolver.
if ($context['flags']['prop'] || $context['flags']['method'] || $context['flags']['mustlok']) {
return array(static::getFuncName($context, 'v', $exp) . "\$cx, $base, array(" . implode(',', array_map(function ($V) {
return "'$V'";
}, $var)) . '))', $exp);
return "'$V'";
}, $var)) . '))', $exp);
}
$n = static::getArrayCode($var);
... ... @@ -1117,10 +1141,11 @@ $libstr
* @expect '../../[a].[b]' when input 2, false, array('a', 'b')
* @expect '../[a\'b]' when input 1, false, array('a\'b')
*/
protected static function getExpression($levels, $spvar, $var) {
protected static function getExpression($levels, $spvar, $var)
{
return ($spvar ? '@' : '') . str_repeat('../', $levels) . ((is_array($var) && count($var)) ? implode('.', array_map(function($v) {
return is_null($v) ? 'this' : "[$v]";
}, $var)) : 'this');
return is_null($v) ? 'this' : "[$v]";
}, $var)) : 'this');
}
/**
... ... @@ -1145,7 +1170,8 @@ $libstr
* @expect array(0, '123') when input '123', array('flags' => array('advar' => 1, 'this' => 0, 'parent' => 1), 'usedFeature' => array('parent' => 0))
* @expect array(0, 'null') when input 'null', array('flags' => array('advar' => 1, 'this' => 0, 'parent' => 1), 'usedFeature' => array('parent' => 0))
*/
protected static function fixVariable($v, &$context) {
protected static function fixVariable($v, &$context)
{
// handle number
if (is_numeric($v)) {
// convert 0x00 or 0b00 numbers to decimal
... ... @@ -1240,7 +1266,8 @@ $libstr
* @expect array(false, array(array('a'), 'q' => array(0, "' d e'"))) when input array(0,0,0,0,0,0,"a q=\' d e\'"), array('flags' => array('advar' => 1, 'this' => 1, 'namev' => 1, 'noesc' => 0), 'scan' => false)
* @expect array(false, array('q' => array('( foo bar)'))) when input array(0,0,0,0,0,0,'q=( foo bar)'), array('flags' => array('advar' => 1, 'this' => 1, 'namev' => 1, 'noesc' => 0, 'exhlp' => 0), 'scan' => false, 'usedFeature' => array(), 'ops' => array('seperator' => 0))
*/
protected static function parseTokenArgs(&$token, &$context) {
protected static function parseTokenArgs(&$token, &$context)
{
trim($token[self::POS_INNERTAG]);
// Handle delimiter change
... ... @@ -1360,7 +1387,7 @@ $libstr
$esc = $context['scan'] ? '' : '\\\\';
if ($context['flags']['advar'] && !preg_match("/^(\"|$esc')(.*)(\"|$esc')$/", $var)) {
// foo] Rule 1: no starting [ or [ not start from head
// foo] Rule 1: no starting [ or [ not start from head
if (preg_match('/^[^\\[\\.]+[\\]\\[]/', $var)
// [bar Rule 2: no ending ] or ] not in the end
|| preg_match('/[\\[\\]][^\\]\\.]+$/', $var)
... ... @@ -1412,7 +1439,8 @@ $libstr
* @expect 'b' when input array(0, 'a', 'b', 'c'), 1
* @expect 'c' when input array(0, 'a', 'b', 'c', 'd', 'e')
*/
protected static function tokenString($token, $remove = 2) {
protected static function tokenString($token, $remove = 2)
{
return implode('', array_slice($token, 1 + $remove, -$remove));
}
... ... @@ -1428,7 +1456,8 @@ $libstr
* @expect null when input array_fill(0, 9, '}}'), array()
* @expect true when input array_fill(0, 9, '{{{'), array()
*/
protected static function validateStartEnd($token, &$context) {
protected static function validateStartEnd($token, &$context)
{
// {{ }}} or {{{ }} are invalid
if (strlen($token[self::POS_BEGINTAG]) !== strlen($token[self::POS_ENDTAG])) {
$context['error'][] = 'Bad token ' . static::tokenString($token) . ' ! Do you mean {{' . static::tokenString($token, 4) . '}} or {{{' . static::tokenString($token, 4) . '}}}?';
... ... @@ -1464,7 +1493,8 @@ $libstr
* @expect 11 when input array(0, 0, 0, 0, 0, '#', '...'), array('hbhelpers' => array('abc' => ''), 'usedFeature' => array('hbhelper' => 10), 'level' => 0), array(array('abc'))
* @expect true when input array(0, 0, 0, 0, 0, '>', '...'), array('basedir' => array('.'), 'fileext' => array('.tmpl'), 'usedFeature' => array('unless' => 7, 'partial' => 7), 'level' => 0, 'flags' => array('skippartial' => 0)), array('test')
*/
protected static function validateOperations($token, &$context, $vars) {
protected static function validateOperations($token, &$context, $vars)
{
switch ($token[self::POS_OP]) {
case '>':
static::readPartial($vars[0][0], $context);
... ... @@ -1476,7 +1506,7 @@ $libstr
case '^':
if (isset($vars[0][0])) {
$context['stack'][] = $token[self::POS_INNERTAG];
$context['level']++;
$context['level'] ++;
return ++$context['usedFeature']['isec'];
}
... ... @@ -1487,7 +1517,7 @@ $libstr
case '/':
array_pop($context['stack']);
$context['level']--;
$context['level'] --;
return true;
case '!':
... ... @@ -1495,7 +1525,7 @@ $libstr
case '#':
$context['stack'][] = $token[self::POS_INNERTAG];
$context['level']++;
$context['level'] ++;
if (!isset($vars[0][0])) {
return;
... ... @@ -1524,7 +1554,7 @@ $libstr
$context['error'][] = 'Do not support {{#with var}}, you should do compile with LightnCandy::FLAG_WITH flag';
}
}
// Continue to add usage...
// Continue to add usage...
case 'each':
case 'unless':
case 'if':
... ... @@ -1542,7 +1572,8 @@ $libstr
* @param string[] $token detected handlebars {{ }} token
* @param array<string,array|string|integer> $context current compile context
*/
protected static function scanFeatures($token, &$context) {
protected static function scanFeatures($token, &$context)
{
list($raw, $vars) = static::parseTokenArgs($token, $context);
if (static::validateStartEnd($token, $context)) {
... ... @@ -1554,7 +1585,7 @@ $libstr
}
if (($token[self::POS_OP] === '^') && ($context['flags']['else'])) {
return $context['usedFeature']['else']++;
return $context['usedFeature']['else'] ++;
}
if (count($vars) == 0) {
... ... @@ -1566,15 +1597,15 @@ $libstr
}
if ($vars[0] !== 'else') {
$context['usedFeature'][$raw ? 'raw' : 'enc']++;
$context['usedFeature'][$raw ? 'raw' : 'enc'] ++;
}
foreach ($vars as $var) {
if (!isset($var[0])) {
if ($context['level'] == 0) {
$context['usedFeature']['rootthis']++;
$context['usedFeature']['rootthis'] ++;
}
$context['usedFeature']['this']++;
$context['usedFeature']['this'] ++;
}
}
... ... @@ -1584,18 +1615,18 @@ $libstr
if ($vars[0][0] === 'else') {
if ($context['flags']['else']) {
return $context['usedFeature']['else']++;
return $context['usedFeature']['else'] ++;
}
}
// detect handlebars custom helpers.
if (isset($context['hbhelpers'][$vars[0][0]])) {
return $context['usedFeature']['hbhelper']++;
return $context['usedFeature']['hbhelper'] ++;
}
// detect custom helpers.
if (isset($context['helpers'][$vars[0][0]])) {
return $context['usedFeature']['helper']++;
return $context['usedFeature']['helper'] ++;
}
}
... ... @@ -1607,7 +1638,8 @@ $libstr
* @param boolean $named is named arguments
* @param string $suggest extended hint for this no named argument error
*/
public static function noNamedArguments($token, &$context, $named, $suggest = '!') {
public static function noNamedArguments($token, &$context, $named, $suggest = '!')
{
if ($named) {
$context['error'][] = 'Do not support name=value in ' . static::tokenString($token) . $suggest;
}
... ... @@ -1622,7 +1654,8 @@ $libstr
*
* @return string|null Return compiled code segment for the token
*/
public static function handleMustacheSpacing(&$token, $vars, &$context) {
public static function handleMustacheSpacing(&$token, $vars, &$context)
{
if (!$context['flags']['mustsp'] && !$context['flags']['mustpi']) {
return;
}
... ... @@ -1667,7 +1700,7 @@ $libstr
if ($st && (($lsp && $rsp) // both side cr
|| ($rsp && !$token[self::POS_LOTHER]) // first line without left
|| ($lsp && ($context['tokens']['current'] == $context['tokens']['count']) && !$token[self::POS_ROTHER]) // final line
)) {
)) {
// handle partial
if ($context['flags']['mustpi'] && ($token[self::POS_OP] === '>')) {
$context['tokens']['partialind'] = $ind;
... ... @@ -1687,7 +1720,8 @@ $libstr
*
* @return string Return compiled code segment for the token
*/
public static function compileToken(&$token, &$context) {
public static function compileToken(&$token, &$context)
{
list($raw, $vars) = static::parseTokenArgs($token, $context);
$named = count(array_diff_key($vars, array_keys(array_keys($vars)))) > 0;
... ... @@ -1731,7 +1765,8 @@ $libstr
*
* @return string|null Return compiled code segment for the token when the token is section
*/
protected static function compileSection(&$token, &$context, &$vars, $named) {
protected static function compileSection(&$token, &$context, &$vars, $named)
{
switch ($token[self::POS_OP]) {
case '>':
// mustache spec: ignore missing partial
... ... @@ -1743,7 +1778,7 @@ $libstr
$vars[0] = array();
}
$v = static::getVariableNames($vars, $context);
$tag = ">$p[0] " .implode(' ', $v[1]);
$tag = ">$p[0] " . implode(' ', $v[1]);
if ($context['flags']['runpart']) {
if (preg_match(static::IS_SUBEXP_SEARCH, $p[0])) {
list($p) = static::compileSubExpression($p[0], $context);
... ... @@ -1803,7 +1838,8 @@ $libstr
*
* @return string|null Return compiled code segment for the token
*/
protected static function compileBlockCustomHelper(&$context, $vars, $inverted = false) {
protected static function compileBlockCustomHelper(&$context, $vars, $inverted = false)
{
if (!isset($vars[0][0])) {
return;
}
... ... @@ -1833,7 +1869,8 @@ $libstr
*
* @return string Return compiled code segment for the token
*/
protected static function compileBlockEnd(&$token, &$context, $vars) {
protected static function compileBlockEnd(&$token, &$context, $vars)
{
$each = false;
$pop = array_pop($context['stack']);
switch ($token[self::POS_INNERTAG]) {
... ... @@ -1857,7 +1894,7 @@ $libstr
$each = true;
}
switch($pop) {
switch ($pop) {
case '#':
case '^':
$pop2 = array_pop($context['stack']);
... ... @@ -1884,20 +1921,17 @@ $libstr
*
* @return string Return compiled code segment for the token
*/
protected static function compileBlockBegin(&$context, $vars) {
protected static function compileBlockBegin(&$context, $vars)
{
$each = 'false';
$v = isset($vars[1]) ? static::getVariableNameOrSubExpression($vars[1], $context) : array(null, array());
switch (isset($vars[0][0]) ? $vars[0][0] : null) {
case 'if':
$context['stack'][] = 'if';
return $context['usedFeature']['parent']
? $context['ops']['seperator'] . static::getFuncName($context, 'ifv', 'if ' . $v[1]) . "\$cx, {$v[0]}, \$in, function(\$cx, \$in) {{$context['ops']['f_start']}"
: "{$context['ops']['cnd_start']}(" . static::getFuncName($context, 'ifvar', $v[1]) . "\$cx, {$v[0]})){$context['ops']['cnd_then']}";
return $context['usedFeature']['parent'] ? $context['ops']['seperator'] . static::getFuncName($context, 'ifv', 'if ' . $v[1]) . "\$cx, {$v[0]}, \$in, function(\$cx, \$in) {{$context['ops']['f_start']}" : "{$context['ops']['cnd_start']}(" . static::getFuncName($context, 'ifvar', $v[1]) . "\$cx, {$v[0]})){$context['ops']['cnd_then']}";
case 'unless':
$context['stack'][] = 'unless';
return $context['usedFeature']['parent']
? $context['ops']['seperator'] . static::getFuncName($context, 'unl', 'unless ' . $v[1]) . "\$cx, {$v[0]}, \$in, function(\$cx, \$in) {{$context['ops']['f_start']}"
: "{$context['ops']['cnd_start']}(!" . static::getFuncName($context, 'ifvar', $v[1]) . "\$cx, {$v[0]})){$context['ops']['cnd_then']}";
return $context['usedFeature']['parent'] ? $context['ops']['seperator'] . static::getFuncName($context, 'unl', 'unless ' . $v[1]) . "\$cx, {$v[0]}, \$in, function(\$cx, \$in) {{$context['ops']['f_start']}" : "{$context['ops']['cnd_start']}(!" . static::getFuncName($context, 'ifvar', $v[1]) . "\$cx, {$v[0]})){$context['ops']['cnd_then']}";
case 'each':
$each = 'true';
array_shift($vars);
... ... @@ -1928,7 +1962,8 @@ $libstr
*
* @return string|null Return compiled code segment for the token when the token is custom helper
*/
protected static function compileCustomHelper(&$context, $vars, $raw, $err = false) {
protected static function compileCustomHelper(&$context, $vars, $raw, $err = false)
{
$notHH = !isset($context['hbhelpers'][$vars[0][0]]);
if (!isset($context['helpers'][$vars[0][0]]) && $notHH) {
if ($err) {
... ... @@ -1954,7 +1989,8 @@ $libstr
*
* @return string|null Return compiled code segment for the token when the token is else
*/
protected static function compileElse(&$context, &$vars) {
protected static function compileElse(&$context, &$vars)
{
if ($vars[0][0] === 'else') {
$c = count($context['stack']) - 1;
if ($c >= 0) {
... ... @@ -1983,7 +2019,8 @@ $libstr
*
* @return string Return compiled code segment for the token
*/
protected static function compileVariable(&$context, &$vars, $raw) {
protected static function compileVariable(&$context, &$vars, $raw)
{
$v = static::getVariableName($vars[0], $context);
if ($context['flags']['jsobj'] || $context['flags']['jstrue'] || $context['flags']['debug']) {
return $context['ops']['seperator'] . static::getFuncName($context, $raw ? 'raw' : $context['ops']['enc'], $v[1]) . "\$cx, {$v[0]}){$context['ops']['seperator']}";
... ... @@ -2004,18 +2041,22 @@ $libstr
* @expect 3 when input array('usedCount' => array('test' => array('testname' => 2))), 'test', 'testname'
* @expect 5 when input array('usedCount' => array('test' => array('testname' => 2))), 'test', 'testname', 3
*/
protected static function addUsageCount(&$context, $category, $name, $count = 1) {
protected static function addUsageCount(&$context, $category, $name, $count = 1)
{
if (!isset($context['usedCount'][$category][$name])) {
$context['usedCount'][$category][$name] = 0;
}
return ($context['usedCount'][$category][$name] += $count);
}
}
/**
* LightnCandy static class for compiled template runtime methods.
*/
class LCRun3 {
class LCRun3
{
const DEBUG_ERROR_LOG = 1;
const DEBUG_ERROR_EXCEPTION = 2;
const DEBUG_TAGS = 4;
... ... @@ -2032,7 +2073,8 @@ class LCRun3 {
* @expect '{{123}}' when input '123', 'miss', array('flags' => array('debug' => LCRun3::DEBUG_TAGS), 'lcrun' => 'LCRun3'), ''
* @expect '<!--MISSED((-->{{#123}}<!--))--><!--SKIPPED--><!--MISSED((-->{{/123}}<!--))-->' when input '123', 'wi', array('flags' => array('debug' => LCRun3::DEBUG_TAGS_HTML), 'lcrun' => 'LCRun3'), false, false, function () {return 'A';}
*/
public static function debug($v, $f, $cx) {
public static function debug($v, $f, $cx)
{
$params = array_slice(func_get_args(), 2);
$r = call_user_func_array((isset($cx['funcs'][$f]) ? $cx['funcs'][$f] : "{$cx['lcrun']}::$f"), $params);
... ... @@ -2040,9 +2082,9 @@ class LCRun3 {
$ansi = $cx['flags']['debug'] & (self::DEBUG_TAGS_ANSI - self::DEBUG_TAGS);
$html = $cx['flags']['debug'] & (self::DEBUG_TAGS_HTML - self::DEBUG_TAGS);
$cs = ($html ? (($r !== '') ? '<!!--OK((-->' : '<!--MISSED((-->') : '')
. ($ansi ? (($r !== '') ? "\033[0;32m" : "\033[0;31m") : '');
. ($ansi ? (($r !== '') ? "\033[0;32m" : "\033[0;31m") : '');
$ce = ($html ? '<!--))-->' : '')
. ($ansi ? "\033[0m" : '');
. ($ansi ? "\033[0m" : '');
switch ($f) {
case 'sec':
case 'ifv':
... ... @@ -2071,7 +2113,8 @@ class LCRun3 {
* @param array<string,array|string|integer> $cx render time context
* @param string $v expression
*/
public static function miss($cx, $v) {
public static function miss($cx, $v)
{
$e = "LCRun3: $v is not exist";
if ($cx['flags']['debug'] & self::DEBUG_ERROR_LOG) {
error_log($e);
... ... @@ -2096,7 +2139,8 @@ class LCRun3 {
* @expect null when input array('scopes' => array(), 'flags' => array('prop' => 0, 'method' => 0, 'mustlok' => 0)), (Object) array('a' => array('b' => 3)), array('a', 'b')
* @expect 3 when input array('scopes' => array(), 'flags' => array('prop' => 1, 'method' => 0, 'mustlok' => 0)), (Object) array('a' => array('b' => 3)), array('a', 'b')
*/
public static function v($cx, $base, $path) {
public static function v($cx, $base, $path)
{
$count = count($cx['scopes']);
while ($base) {
$v = $base;
... ... @@ -2155,7 +2199,8 @@ class LCRun3 {
* @expect true when input array(), array('')
* @expect true when input array(), array(0)
*/
public static function ifvar($cx, $v) {
public static function ifvar($cx, $v)
{
return !is_null($v) && ($v !== false) && ($v !== 0) && ($v !== 0.0) && ($v !== '') && (is_array($v) ? (count($v) > 0) : true);
}
... ... @@ -2175,7 +2220,8 @@ class LCRun3 {
* @expect 'Y' when input array('scopes' => array()), 1, array(), function () {return 'Y';}
* @expect 'N' when input array('scopes' => array()), null, array(), function () {return 'Y';}, function () {return 'N';}
*/
public static function ifv($cx, $v, $in, $truecb, $falsecb = null) {
public static function ifv($cx, $v, $in, $truecb, $falsecb = null)
{
$ret = '';
if (self::ifvar($cx, $v)) {
if ($truecb) {
... ... @@ -2210,7 +2256,8 @@ class LCRun3 {
* @expect 'Y' when input array('scopes' => array()), null, array(), function () {return 'Y';}, function () {return 'N';}
* @expect 'N' when input array('scopes' => array()), true, array(), function () {return 'Y';}, function () {return 'N';}
*/
public static function unl($cx, $var, $in, $truecb, $falsecb = null) {
public static function unl($cx, $var, $in, $truecb, $falsecb = null)
{
return self::ifv($cx, $var, $in, $falsecb, $truecb);
}
... ... @@ -2229,7 +2276,8 @@ class LCRun3 {
* @expect true when input array(), array()
* @expect false when input array(), array('1')
*/
public static function isec($cx, $v) {
public static function isec($cx, $v)
{
return is_null($v) || ($v === false) || (is_array($v) && (count($v) === 0));
}
... ... @@ -2255,7 +2303,8 @@ class LCRun3 {
* @expect 'a,' when input array('flags' => array('jstrue' => 0, 'jsobj' => 1)), array('a',false)
* @expect 'a,false' when input array('flags' => array('jstrue' => 1, 'jsobj' => 1)), array('a',false)
*/
public static function raw($cx, $v) {
public static function raw($cx, $v)
{
if ($v === true) {
if ($cx['flags']['jstrue']) {
return 'true';
... ... @@ -2299,7 +2348,8 @@ class LCRun3 {
* @expect 'a&amp;b' when input array(), 'a&b'
* @expect 'a&#039;b' when input array(), 'a\'b'
*/
public static function enc($cx, $var) {
public static function enc($cx, $var)
{
return htmlentities(self::raw($cx, $var), ENT_QUOTES, 'UTF-8');
}
... ... @@ -2316,7 +2366,8 @@ class LCRun3 {
* @expect 'a&#x27;b' when input array(), 'a\'b'
* @expect '&#x60;a&#x27;b' when input array(), '`a\'b'
*/
public static function encq($cx, $var) {
public static function encq($cx, $var)
{
return preg_replace('/`/', '&#x60;', preg_replace('/&#039;/', '&#x27;', htmlentities(self::raw($cx, $var), ENT_QUOTES, 'UTF-8')));
}
... ... @@ -2357,7 +2408,8 @@ class LCRun3 {
* @expect '268' when input array('flags' => array('spvar' => 1), 'sp_vars'=>array('root' => 0)), array(1,3,4), 0, false, function ($c, $i) {return $i * 2;}
* @expect '038' when input array('flags' => array('spvar' => 1), 'sp_vars'=>array('root' => 0)), array(1,3,'a'=>4), 0, true, function ($c, $i) {return $i * $c['sp_vars']['index'];}
*/
public static function sec($cx, $v, $in, $each, $cb, $else = null) {
public static function sec($cx, $v, $in, $each, $cb, $else = null)
{
$isAry = is_array($v) || ($v instanceof ArrayObject);
$isTrav = $v instanceof Traversable;
$loop = $each;
... ... @@ -2473,7 +2525,8 @@ class LCRun3 {
* @expect '{"a":"b"}' when input array(), array('a'=>'b'), array('a'=>'c'), function ($c, $i) {return json_encode($i);}
* @expect '-b=' when input array(), 'b', array('a'=>'b'), function ($c, $i) {return "-$i=";}
*/
public static function wi($cx, $v, $in, $cb, $else = null) {
public static function wi($cx, $v, $in, $cb, $else = null)
{
if (($v === false) || ($v === null)) {
return $else ? $else($cx, $in) : '';
}
... ... @@ -2493,7 +2546,8 @@ class LCRun3 {
* @return string The rendered string of the partial
*
*/
public static function p($cx, $p, $v, $sp = '') {
public static function p($cx, $p, $v, $sp = '')
{
$param = $v[0][0];
if (is_array($v[1])) {
... ... @@ -2524,7 +2578,8 @@ class LCRun3 {
* @expect '=&#x27;=' when input array('helpers' => array('a' => function ($i) {return "=$i[0]=";})), 'a', array(array('\''),array()), 'encq'
* @expect '=b=' when input array('helpers' => array('a' => function ($i,$j) {return "={$j['a']}=";})), 'a', array(array(),array('a' => 'b')), 'raw'
*/
public static function ch($cx, $ch, $vars, $op) {
public static function ch($cx, $ch, $vars, $op)
{
return self::chret(call_user_func_array($cx['helpers'][$ch], $vars), $op);
}
... ... @@ -2546,7 +2601,8 @@ class LCRun3 {
* @expect '=&=' when input array('=&=', 'raw'), 'enc'
* @expect '=&amp;&#x27;=' when input array('=&\'=', 'encq'), 'raw'
*/
public static function chret($ret, $op) {
public static function chret($ret, $op)
{
if (is_array($ret)) {
if (isset($ret[1]) && $ret[1]) {
$op = $ret[1];
... ... @@ -2576,7 +2632,8 @@ class LCRun3 {
*
* @return string The rendered string of the token
*/
public static function hbch($cx, $ch, $vars, $op, $inverted, $cb = null, $else = null) {
public static function hbch($cx, $ch, $vars, $op, $inverted, $cb = null, $else = null)
{
$isBlock = (is_object($cb) && ($cb instanceof Closure));
$args = $vars[0];
$options = array(
... ... @@ -2640,7 +2697,7 @@ class LCRun3 {
$e = "LCRun3: call custom helper '$ch' error: " . $E->getMessage();
}
if($e !== null) {
if ($e !== null) {
if ($cx['flags']['debug'] & self::DEBUG_ERROR_LOG) {
error_log($e);
}
... ... @@ -2669,7 +2726,8 @@ class LCRun3 {
* @expect '2.6.5' when input array('blockhelpers' => array('a' => function ($cx,$in) {return array($cx,$in[0],5);})), 'a', array('6', 0), 2, false, function($cx, $i) {return implode('.', $i);}
* @expect '' when input array('blockhelpers' => array('a' => function ($cx,$in) {})), 'a', array('6', 0), 2, false, function($cx, $i) {return implode('.', $i);}
*/
public static function bch($cx, $ch, $vars, $in, $inverted, $cb, $else = null) {
public static function bch($cx, $ch, $vars, $in, $inverted, $cb, $else = null)
{
$r = call_user_func($cx['blockhelpers'][$ch], $in, $vars[0], $vars[1]);
// $invert the logic
... ... @@ -2696,4 +2754,5 @@ class LCRun3 {
return $ret;
}
}
... ...
... ... @@ -16,25 +16,28 @@ defined('DS') || define('DS', '/');
*/
abstract class Factory
{
/**
* 接口名称
*
* @var string
*/
protected $apiName = '';
/**
* 接口配置
*
* @var array
*/
protected $apiConfig = array();
/**
/**
* 接口对象
*
* @var array
*/
protected static $apiObjs = array();
/**
* 单例模式: 实例化需要调用的接口对象
*
... ... @@ -44,23 +47,21 @@ abstract class Factory
public static function create($apiName)
{
$apiName = strtolower($apiName);
if (!isset(self::$apiObjs[$apiName]))
{
if (!isset(self::$apiObjs[$apiName])) {
// require dirname(__FILE__) . DS . $apiName . DS . 'Call.class.php';
//$apiNameCase = ucfirst($apiName);
$apiClass = "Plugin\Partner\\{$apiName}\Call";
self::$apiObjs[$apiName] = new $apiClass();
self::$apiObjs[$apiName]->apiName = $apiName;
self::$apiObjs[$apiName]->configure();
self::$apiObjs[$apiName]->init();
}
return self::$apiObjs[$apiName];
}
/**
* 应用的配置
*
... ... @@ -70,16 +71,22 @@ abstract class Factory
{
$this->apiConfig = require(dirname(__FILE__) . DS . $this->apiName . DS . 'Config.inc.php');
}
/**初始化*/
/* * 初始化 */
abstract protected function init();
/**获取接口*/
/* * 获取接口 */
abstract public function getAuthorizeUrl();
abstract public function getAccessToken();
abstract public function getUserInfo($token);
abstract public function getFriends($token, $params);
/**同步分享*/
/* * 同步分享 */
abstract public function syncShare($token, $content, $image, $link);
}
\ No newline at end of file
}
... ...
... ... @@ -4,7 +4,7 @@ namespace Plugin\Partner\alipay;
use Plugin\Partner\Factory;
define('TB_CLASS_PATH', dirname(__FILE__).'/class');
define('TB_CLASS_PATH', dirname(__FILE__) . '/class');
require TB_CLASS_PATH . '/lib/alipay.function.php';
require TB_CLASS_PATH . '/AlipaySubmit.class.php';
require TB_CLASS_PATH . '/AlipayNotify.class.php';
... ... @@ -20,9 +20,10 @@ require TB_CLASS_PATH . '/AlipayNotify.class.php';
*/
class Call extends Factory
{
protected $alipaySubmit;
protected $alipayNotify;
/**
* 初始化
*/
... ... @@ -31,7 +32,7 @@ class Call extends Factory
$this->alipaySubmit = new \AlipaySubmit($this->apiConfig);
$this->alipayNotify = new \AlipayNotify($this->apiConfig);
}
/**
* 获取授权URL
*
... ... @@ -44,17 +45,17 @@ class Call extends Factory
'partner' => $this->apiConfig['partner'],
'target_service' => 'user.auth.quick.login',
'return_url' => $this->apiConfig['return_url'],
'anti_phishing_key' => $this->alipaySubmit->query_timestamp(),
'anti_phishing_key' => $this->alipaySubmit->query_timestamp(),
'exter_invoke_ip' => '',
'_input_charset' => $this->apiConfig['input_charset']
);
echo '<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>支付宝快捷登录</title></head><body>',
$this->alipaySubmit->buildRequestForm($parameter, 'get'),
'</body></html>';
$this->alipaySubmit->buildRequestForm($parameter, 'get'),
'</body></html>';
exit();
}
/**
* 获取授权的TOKEN
*
... ... @@ -63,17 +64,16 @@ class Call extends Factory
public function getAccessToken()
{
$token = array();
$verify = $this->alipayNotify->verifyReturn();
if ($verify)
{
if ($verify) {
$token['access_token'] = isset($_GET['token']) ? $_GET['token'] : null;
$token['user_id'] = isset($_GET['user_id']) ? $_GET['user_id'] : null;
}
return $token;
}
/**
* 获取当前用户的基本资料
*
... ... @@ -93,7 +93,7 @@ class Call extends Factory
return $result;
}
/**
* 获取当前用户的偶像(关注)列表
*
... ... @@ -107,7 +107,7 @@ class Call extends Factory
{
return array();
}
/**
* 同步分享
*
... ... @@ -123,5 +123,5 @@ class Call extends Factory
{
return true;
}
}
\ No newline at end of file
}
... ...
<?php
<?php
defined('SITE_MAIN') || define('SITE_MAIN', $_SERVER['HTTP_HOST']);
return array(
... ... @@ -11,7 +12,7 @@ return array(
// 字符编码格式 目前支持 gbk 或 utf-8
'input_charset' => 'utf-8',
// ca证书路径地址,用于curl中ssl校验 (请保证cacert.pem文件在当前文件夹目录中)
'cacert' => dirname(__FILE__) .'/cacert.pem',
'cacert' => dirname(__FILE__) . '/cacert.pem',
// 访问模式,根据自己的服务器是否支持ssl访问,若支持请选择https;若不支持请选择http
'transport' => 'http',
// 页面跳转同步通知页面路径 (需http://格式的完整路径,不允许加?id=123这类自定义参数)
... ...
<?php
/**
* 支付宝通知处理类
*
... ... @@ -10,129 +11,138 @@
* @version 5.0 (2014-03-06 16:41:20)
* @author fei.hong <fei.hong@yoho.cn>
*/
class AlipayNotify {
class AlipayNotify
{
/**
* HTTPS形式消息验证地址
*/
var $https_verify_url = 'https://mapi.alipay.com/gateway.do?service=notify_verify&';
/**
var $https_verify_url = 'https://mapi.alipay.com/gateway.do?service=notify_verify&';
/**
* HTTP形式消息验证地址
*/
var $http_verify_url = 'http://notify.alipay.com/trade/notify_query.do?';
/**
* 支付宝配置
*/
var $alipay_config = array();
function __construct($alipay_config){
$this->alipay_config = $alipay_config;
}
function AlipayNotify($alipay_config) {
$this->__construct($alipay_config);
var $http_verify_url = 'http://notify.alipay.com/trade/notify_query.do?';
/**
* 支付宝配置
*/
var $alipay_config = array();
function __construct($alipay_config)
{
$this->alipay_config = $alipay_config;
}
function AlipayNotify($alipay_config)
{
$this->__construct($alipay_config);
}
/**
* 针对notify_url验证消息是否是支付宝发出的合法消息
* @return 验证结果
*/
function verifyNotify(){
if (empty($_POST)) { //判断POST来的数组是否为空
return false;
} else {
//生成签名结果
$isSign = $this->getSignVeryfy($_POST, $_POST["sign"]);
//获取支付宝远程服务器ATN结果(验证是否是支付宝发来的消息)
$responseTxt = 'true';
if (! empty($_POST["notify_id"])) {$responseTxt = $this->getResponse($_POST["notify_id"]);}
//写日志记录
//if ($isSign) {
// $isSignStr = 'true';
//}
//else {
// $isSignStr = 'false';
//}
//$log_text = "responseTxt=".$responseTxt."\n notify_url_log:isSign=".$isSignStr.",";
//$log_text = $log_text.createLinkString($_POST);
//logResult($log_text);
//验证
//$responsetTxt的结果不是true,与服务器设置问题、合作身份者ID、notify_id一分钟失效有关
//isSign的结果不是true,与安全校验码、请求时的参数格式(如:带自定义参数等)、编码格式有关
if (preg_match("/true$/i",$responseTxt) && $isSign) {
return true;
} else {
return false;
}
}
}
function verifyNotify()
{
if (empty($_POST)) { //判断POST来的数组是否为空
return false;
} else {
//生成签名结果
$isSign = $this->getSignVeryfy($_POST, $_POST["sign"]);
//获取支付宝远程服务器ATN结果(验证是否是支付宝发来的消息)
$responseTxt = 'true';
if (!empty($_POST["notify_id"])) {
$responseTxt = $this->getResponse($_POST["notify_id"]);
}
//写日志记录
//if ($isSign) {
// $isSignStr = 'true';
//}
//else {
// $isSignStr = 'false';
//}
//$log_text = "responseTxt=".$responseTxt."\n notify_url_log:isSign=".$isSignStr.",";
//$log_text = $log_text.createLinkString($_POST);
//logResult($log_text);
//验证
//$responsetTxt的结果不是true,与服务器设置问题、合作身份者ID、notify_id一分钟失效有关
//isSign的结果不是true,与安全校验码、请求时的参数格式(如:带自定义参数等)、编码格式有关
if (preg_match("/true$/i", $responseTxt) && $isSign) {
return true;
} else {
return false;
}
}
}
/**
* 针对return_url验证消息是否是支付宝发出的合法消息
* @return 验证结果
*/
function verifyReturn(){
if(empty($_GET)) {//判断POST来的数组是否为空
return false;
}
else {
//生成签名结果
$isSign = $this->getSignVeryfy($_GET, $_GET["sign"]);
//获取支付宝远程服务器ATN结果(验证是否是支付宝发来的消息)
$responseTxt = 'true';
if (! empty($_GET["notify_id"])) {$responseTxt = $this->getResponse($_GET["notify_id"]);}
//写日志记录
//if ($isSign) {
// $isSignStr = 'true';
//}
//else {
// $isSignStr = 'false';
//}
//$log_text = "responseTxt=".$responseTxt."\n return_url_log:isSign=".$isSignStr.",";
//$log_text = $log_text.createLinkString($_GET);
//logResult($log_text);
//验证
//$responsetTxt的结果不是true,与服务器设置问题、合作身份者ID、notify_id一分钟失效有关
//isSign的结果不是true,与安全校验码、请求时的参数格式(如:带自定义参数等)、编码格式有关
if (preg_match("/true$/i",$responseTxt) && $isSign) {
return true;
} else {
return false;
}
}
}
function verifyReturn()
{
if (empty($_GET)) {//判断POST来的数组是否为空
return false;
} else {
//生成签名结果
$isSign = $this->getSignVeryfy($_GET, $_GET["sign"]);
//获取支付宝远程服务器ATN结果(验证是否是支付宝发来的消息)
$responseTxt = 'true';
if (!empty($_GET["notify_id"])) {
$responseTxt = $this->getResponse($_GET["notify_id"]);
}
//写日志记录
//if ($isSign) {
// $isSignStr = 'true';
//}
//else {
// $isSignStr = 'false';
//}
//$log_text = "responseTxt=".$responseTxt."\n return_url_log:isSign=".$isSignStr.",";
//$log_text = $log_text.createLinkString($_GET);
//logResult($log_text);
//验证
//$responsetTxt的结果不是true,与服务器设置问题、合作身份者ID、notify_id一分钟失效有关
//isSign的结果不是true,与安全校验码、请求时的参数格式(如:带自定义参数等)、编码格式有关
if (preg_match("/true$/i", $responseTxt) && $isSign) {
return true;
} else {
return false;
}
}
}
/**
* 获取返回时的签名验证结果
* @param $para_temp 通知返回来的参数数组
* @param $sign 返回的签名结果
* @return 签名验证结果
*/
function getSignVeryfy($para_temp, $sign) {
//除去待签名参数数组中的空值和签名参数
$para_filter = paraFilter($para_temp);
//对待签名参数数组排序
$para_sort = argSort($para_filter);
//把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串
$prestr = createLinkstring($para_sort);
$isSgin = false;
switch ($this->alipay_config['sign_type']) {
case "MD5" :
$isSgin = md5Verify($prestr, $sign, $this->alipay_config['key']);
break;
default :
$isSgin = false;
}
return $isSgin;
}
function getSignVeryfy($para_temp, $sign)
{
//除去待签名参数数组中的空值和签名参数
$para_filter = paraFilter($para_temp);
//对待签名参数数组排序
$para_sort = argSort($para_filter);
//把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串
$prestr = createLinkstring($para_sort);
$isSgin = false;
switch ($this->alipay_config['sign_type']) {
case "MD5" :
$isSgin = md5Verify($prestr, $sign, $this->alipay_config['key']);
break;
default :
$isSgin = false;
}
return $isSgin;
}
/**
* 获取远程服务器ATN结果,验证返回URL
... ... @@ -143,21 +153,22 @@ class AlipayNotify {
* true 返回正确信息
* false 请检查防火墙或者是服务器阻止端口问题以及验证时间是否超过一分钟
*/
function getResponse($notify_id) {
$transport = $this->alipay_config['transport'];
$partner = $this->alipay_config['partner'];
$veryfy_url = '';
if($transport == 'https') {
$veryfy_url = $this->https_verify_url;
}
else {
$veryfy_url = $this->http_verify_url;
}
$veryfy_url = $veryfy_url."partner=" . $partner . "&notify_id=" . $notify_id;
$responseTxt = getHttpResponseGET($veryfy_url, $this->alipay_config['cacert']);
return $responseTxt;
}
function getResponse($notify_id)
{
$transport = $this->alipay_config['transport'];
$partner = $this->alipay_config['partner'];
$veryfy_url = '';
if ($transport == 'https') {
$veryfy_url = $this->https_verify_url;
} else {
$veryfy_url = $this->http_verify_url;
}
$veryfy_url = $veryfy_url . "partner=" . $partner . "&notify_id=" . $notify_id;
$responseTxt = getHttpResponseGET($veryfy_url, $this->alipay_config['cacert']);
return $responseTxt;
}
}
?>
... ...
<?php
/**
* 支付宝各接口请求提交类
*
... ... @@ -8,22 +9,26 @@
* @version 5.0 (2014-03-06 16:23:47)
* @author fei.hong <fei.hong@yoho.cn>
*/
class AlipaySubmit {
class AlipaySubmit
{
/**
* 支付宝配置
*/
var $alipay_config = array();
/**
* 支付宝网关地址(新)
*/
var $alipay_gateway_new = 'https://mapi.alipay.com/gateway.do?';
function __construct($alipay_config){
function __construct($alipay_config)
{
$this->alipay_config = $alipay_config;
}
function AlipaySubmit($alipay_config) {
function AlipaySubmit($alipay_config)
{
$this->__construct($alipay_config);
}
... ... @@ -32,7 +37,8 @@ class AlipaySubmit {
* @param $para_sort 已排序要签名的数组
* return 签名结果字符串
*/
function buildRequestMysign($para_sort) {
function buildRequestMysign($para_sort)
{
//把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串
$prestr = createLinkstring($para_sort);
... ... @@ -53,7 +59,8 @@ class AlipaySubmit {
* @param $para_temp 请求前的参数数组
* @return 要请求的参数数组
*/
function buildRequestPara($para_temp) {
function buildRequestPara($para_temp)
{
//除去待签名参数数组中的空值和签名参数
$para_filter = paraFilter($para_temp);
... ... @@ -75,7 +82,8 @@ class AlipaySubmit {
* @param $para_temp 请求前的参数数组
* @return 要请求的参数数组字符串
*/
function buildRequestParaToString($para_temp) {
function buildRequestParaToString($para_temp)
{
//待请求参数数组
$para = $this->buildRequestPara($para_temp);
... ... @@ -92,16 +100,17 @@ class AlipaySubmit {
* @param $button_name 确认按钮显示文字
* @return 提交表单HTML文本
*/
function buildRequestForm($para_temp, $method) {
function buildRequestForm($para_temp, $method)
{
//待请求参数数组
$para = $this->buildRequestPara($para_temp);
$sHtml = "<form id='alipaysubmit' name='alipaysubmit' action='".$this->alipay_gateway_new."_input_charset=".$this->alipay_config['input_charset']."' method='".$method."'>";
while (list ($key, $val) = each ($para)) {
$sHtml.= "<input type='hidden' name='".$key."' value='".$val."'/>";
$sHtml = "<form id='alipaysubmit' name='alipaysubmit' action='" . $this->alipay_gateway_new . "_input_charset=" . $this->alipay_config['input_charset'] . "' method='" . $method . "'>";
while (list ($key, $val) = each($para)) {
$sHtml.= "<input type='hidden' name='" . $key . "' value='" . $val . "'/>";
}
$sHtml = $sHtml."<script>document.forms['alipaysubmit'].submit();</script>";
$sHtml = $sHtml . "<script>document.forms['alipaysubmit'].submit();</script>";
return $sHtml;
}
... ... @@ -111,14 +120,15 @@ class AlipaySubmit {
* @param $para_temp 请求参数数组
* @return 支付宝处理结果
*/
function buildRequestHttp($para_temp) {
function buildRequestHttp($para_temp)
{
$sResult = '';
//待请求参数数组字符串
$request_data = $this->buildRequestPara($para_temp);
//远程获取数据
$sResult = getHttpResponsePOST($this->alipay_gateway_new, $this->alipay_config['cacert'],$request_data,$this->alipay_config['input_charset']);
$sResult = getHttpResponsePOST($this->alipay_gateway_new, $this->alipay_config['cacert'], $request_data, $this->alipay_config['input_charset']);
return $sResult;
}
... ... @@ -130,14 +140,15 @@ class AlipaySubmit {
* @param $file_name 文件完整绝对路径
* @return 支付宝返回处理结果
*/
function buildRequestHttpInFile($para_temp, $file_para_name, $file_name) {
function buildRequestHttpInFile($para_temp, $file_para_name, $file_name)
{
//待请求参数数组
$para = $this->buildRequestPara($para_temp);
$para[$file_para_name] = "@".$file_name;
$para[$file_para_name] = "@" . $file_name;
//远程获取数据
$sResult = getHttpResponsePOST($this->alipay_gateway_new, $this->alipay_config['cacert'],$para,$this->alipay_config['input_charset']);
$sResult = getHttpResponsePOST($this->alipay_gateway_new, $this->alipay_config['cacert'], $para, $this->alipay_config['input_charset']);
return $sResult;
}
... ... @@ -147,18 +158,19 @@ class AlipaySubmit {
* 注意:该功能PHP5环境及以上支持,因此必须服务器、本地电脑中装有支持DOMDocument、SSL的PHP配置环境。建议本地调试时使用PHP开发软件
* return 时间戳字符串
*/
function query_timestamp() {
$url = $this->alipay_gateway_new."service=query_timestamp&partner=".$this->alipay_config['partner']."&_input_charset=".$this->alipay_config['input_charset'];
function query_timestamp()
{
$url = $this->alipay_gateway_new . "service=query_timestamp&partner=" . $this->alipay_config['partner'] . "&_input_charset=" . $this->alipay_config['input_charset'];
$encrypt_key = "";
$doc = new DOMDocument();
$doc->load($url);
$itemEncrypt_key = $doc->getElementsByTagName( "encrypt_key" );
$itemEncrypt_key = $doc->getElementsByTagName("encrypt_key");
$encrypt_key = $itemEncrypt_key->item(0)->nodeValue;
return $encrypt_key;
}
/**
* 通过token获取用户信息
*
... ... @@ -166,12 +178,13 @@ class AlipaySubmit {
* @return array
* @since 1.0.3
*/
function getUserInfoByToken($parameter) {
function getUserInfoByToken($parameter)
{
$parameter = $this->buildRequestPara($parameter);
// 系统参数放入GET请求串
$requestUrl = $this->alipay_gateway_new . http_build_query($parameter, null, '&');
// 发起HTTP请求
$result = array();
try {
... ... @@ -186,4 +199,5 @@ class AlipaySubmit {
}
}
?>
\ No newline at end of file
... ...
<?php
/* *
* 支付宝接口公用函数
* 详细:该类是请求、通知返回两个文件所调用的公用函数核心处理文件
... ... @@ -14,71 +15,86 @@
* @param $para 需要拼接的数组
* return 拼接完成以后的字符串
*/
function createLinkstring($para) {
$arg = "";
while (list ($key, $val) = each ($para)) {
$arg.=$key."=".$val."&";
}
//去掉最后一个&字符
$arg = substr($arg,0,count($arg)-2);
//如果存在转义字符,那么去掉转义
if(get_magic_quotes_gpc()){$arg = stripslashes($arg);}
return $arg;
function createLinkstring($para)
{
$arg = "";
while (list ($key, $val) = each($para)) {
$arg.=$key . "=" . $val . "&";
}
//去掉最后一个&字符
$arg = substr($arg, 0, count($arg) - 2);
//如果存在转义字符,那么去掉转义
if (get_magic_quotes_gpc()) {
$arg = stripslashes($arg);
}
return $arg;
}
/**
* 把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串,并对字符串做urlencode编码
* @param $para 需要拼接的数组
* return 拼接完成以后的字符串
*/
function createLinkstringUrlencode($para) {
$arg = "";
while (list ($key, $val) = each ($para)) {
$arg.=$key."=".urlencode($val)."&";
}
//去掉最后一个&字符
$arg = substr($arg,0,count($arg)-2);
//如果存在转义字符,那么去掉转义
if(get_magic_quotes_gpc()){$arg = stripslashes($arg);}
return $arg;
function createLinkstringUrlencode($para)
{
$arg = "";
while (list ($key, $val) = each($para)) {
$arg.=$key . "=" . urlencode($val) . "&";
}
//去掉最后一个&字符
$arg = substr($arg, 0, count($arg) - 2);
//如果存在转义字符,那么去掉转义
if (get_magic_quotes_gpc()) {
$arg = stripslashes($arg);
}
return $arg;
}
/**
* 除去数组中的空值和签名参数
* @param $para 签名参数组
* return 去掉空值与签名参数后的新签名参数组
*/
function paraFilter($para) {
$para_filter = array();
while (list ($key, $val) = each ($para)) {
if($key == "sign" || $key == "sign_type" || $val == "")continue;
else $para_filter[$key] = $para[$key];
}
return $para_filter;
function paraFilter($para)
{
$para_filter = array();
while (list ($key, $val) = each($para)) {
if ($key == "sign" || $key == "sign_type" || $val == "")
continue;
else
$para_filter[$key] = $para[$key];
}
return $para_filter;
}
/**
* 对数组排序
* @param $para 排序前的数组
* return 排序后的数组
*/
function argSort($para) {
ksort($para);
reset($para);
return $para;
function argSort($para)
{
ksort($para);
reset($para);
return $para;
}
/**
* 写日志,方便测试(看网站需求,也可以改成把记录存入数据库)
* 注意:服务器需要开通fopen配置
* @param $word 要写入日志里的文本内容 默认值:空值
*/
function logResult($word='') {
$fp = fopen("log.txt","a");
flock($fp, LOCK_EX) ;
fwrite($fp,"执行日期:".strftime("%Y%m%d%H%M%S",time())."\n".$word."\n");
flock($fp, LOCK_UN);
fclose($fp);
function logResult($word = '')
{
$fp = fopen("log.txt", "a");
flock($fp, LOCK_EX);
fwrite($fp, "执行日期:" . strftime("%Y%m%d%H%M%S", time()) . "\n" . $word . "\n");
flock($fp, LOCK_UN);
fclose($fp);
}
/**
... ... @@ -92,24 +108,25 @@ function logResult($word='') {
* @param $input_charset 编码格式。默认值:空值
* return 远程输出的数据
*/
function getHttpResponsePOST($url, $cacert_url, $para, $input_charset = '') {
if (trim($input_charset) != '') {
$url = $url."_input_charset=".$input_charset;
}
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);//SSL证书认证
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);//严格认证
curl_setopt($curl, CURLOPT_CAINFO,$cacert_url);//证书地址
curl_setopt($curl, CURLOPT_HEADER, 0 ); // 过滤HTTP头
curl_setopt($curl,CURLOPT_RETURNTRANSFER, 1);// 显示输出结果
curl_setopt($curl,CURLOPT_POST,true); // post传输数据
curl_setopt($curl,CURLOPT_POSTFIELDS,$para);// post传输数据
$responseText = curl_exec($curl);
//var_dump( curl_error($curl) );//如果执行curl过程中出现异常,可打开此开关,以便查看异常内容
curl_close($curl);
return $responseText;
function getHttpResponsePOST($url, $cacert_url, $para, $input_charset = '')
{
if (trim($input_charset) != '') {
$url = $url . "_input_charset=" . $input_charset;
}
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true); //SSL证书认证
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2); //严格认证
curl_setopt($curl, CURLOPT_CAINFO, $cacert_url); //证书地址
curl_setopt($curl, CURLOPT_HEADER, 0); // 过滤HTTP头
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 显示输出结果
curl_setopt($curl, CURLOPT_POST, true); // post传输数据
curl_setopt($curl, CURLOPT_POSTFIELDS, $para); // post传输数据
$responseText = curl_exec($curl);
//var_dump( curl_error($curl) );//如果执行curl过程中出现异常,可打开此开关,以便查看异常内容
curl_close($curl);
return $responseText;
}
/**
... ... @@ -121,18 +138,19 @@ function getHttpResponsePOST($url, $cacert_url, $para, $input_charset = '') {
* @param $cacert_url 指定当前工作目录绝对路径
* return 远程输出的数据
*/
function getHttpResponseGET($url,$cacert_url) {
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, 0 ); // 过滤HTTP头
curl_setopt($curl,CURLOPT_RETURNTRANSFER, 1);// 显示输出结果
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);//SSL证书认证
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);//严格认证
curl_setopt($curl, CURLOPT_CAINFO,$cacert_url);//证书地址
$responseText = curl_exec($curl);
//var_dump( curl_error($curl) );//如果执行curl过程中出现异常,可打开此开关,以便查看异常内容
curl_close($curl);
return $responseText;
function getHttpResponseGET($url, $cacert_url)
{
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, 0); // 过滤HTTP头
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 显示输出结果
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true); //SSL证书认证
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2); //严格认证
curl_setopt($curl, CURLOPT_CAINFO, $cacert_url); //证书地址
$responseText = curl_exec($curl);
//var_dump( curl_error($curl) );//如果执行curl过程中出现异常,可打开此开关,以便查看异常内容
curl_close($curl);
return $responseText;
}
/**
... ... @@ -142,18 +160,22 @@ function getHttpResponseGET($url,$cacert_url) {
* @param $_input_charset 输入的编码格式
* return 编码后的字符串
*/
function charsetEncode($input,$_output_charset ,$_input_charset) {
$output = "";
if(!isset($_output_charset) )$_output_charset = $_input_charset;
if($_input_charset == $_output_charset || $input ==null ) {
$output = $input;
} elseif (function_exists("mb_convert_encoding")) {
$output = mb_convert_encoding($input,$_output_charset,$_input_charset);
} elseif(function_exists("iconv")) {
$output = iconv($_input_charset,$_output_charset,$input);
} else die("sorry, you have no libs support for charset change.");
return $output;
function charsetEncode($input, $_output_charset, $_input_charset)
{
$output = "";
if (!isset($_output_charset))
$_output_charset = $_input_charset;
if ($_input_charset == $_output_charset || $input == null) {
$output = $input;
} elseif (function_exists("mb_convert_encoding")) {
$output = mb_convert_encoding($input, $_output_charset, $_input_charset);
} elseif (function_exists("iconv")) {
$output = iconv($_input_charset, $_output_charset, $input);
} else
die("sorry, you have no libs support for charset change.");
return $output;
}
/**
* 实现多种字符解码方式
* @param $input 需要解码的字符串
... ... @@ -161,20 +183,23 @@ function charsetEncode($input,$_output_charset ,$_input_charset) {
* @param $_input_charset 输入的解码格式
* return 解码后的字符串
*/
function charsetDecode($input,$_input_charset ,$_output_charset) {
$output = "";
if(!isset($_input_charset) )$_input_charset = $_input_charset ;
if($_input_charset == $_output_charset || $input ==null ) {
$output = $input;
} elseif (function_exists("mb_convert_encoding")) {
$output = mb_convert_encoding($input,$_output_charset,$_input_charset);
} elseif(function_exists("iconv")) {
$output = iconv($_input_charset,$_output_charset,$input);
} else die("sorry, you have no libs support for charset changes.");
return $output;
function charsetDecode($input, $_input_charset, $_output_charset)
{
$output = "";
if (!isset($_input_charset))
$_input_charset = $_input_charset;
if ($_input_charset == $_output_charset || $input == null) {
$output = $input;
} elseif (function_exists("mb_convert_encoding")) {
$output = mb_convert_encoding($input, $_output_charset, $_input_charset);
} elseif (function_exists("iconv")) {
$output = iconv($_input_charset, $_output_charset, $input);
} else
die("sorry, you have no libs support for charset changes.");
return $output;
}
/** MD5加密 **/
/** MD5加密 * */
/**
* 签名字符串
... ... @@ -182,7 +207,8 @@ function charsetDecode($input,$_input_charset ,$_output_charset) {
* @param $key 私钥
* return 签名结果
*/
function md5Sign($prestr, $key) {
function md5Sign($prestr, $key)
{
$prestr = $prestr . $key;
return md5($prestr);
}
... ... @@ -194,15 +220,16 @@ function md5Sign($prestr, $key) {
* @param $key 私钥
* return 签名结果
*/
function md5Verify($prestr, $sign, $key) {
function md5Verify($prestr, $sign, $key)
{
$prestr = $prestr . $key;
$mysgin = md5($prestr);
if($mysgin == $sign) {
if ($mysgin == $sign) {
return true;
}
else {
} else {
return false;
}
}
?>
\ No newline at end of file
... ...
... ... @@ -4,7 +4,7 @@ namespace Plugin\Partner\qqconnect;
use Plugin\Partner\Factory;
define('QC_CLASS_PATH', dirname (__FILE__) . '/class/');
define('QC_CLASS_PATH', dirname(__FILE__) . '/class/');
require QC_CLASS_PATH . 'QC.class.php';
/**
... ... @@ -18,17 +18,18 @@ require QC_CLASS_PATH . 'QC.class.php';
*/
class Call extends Factory
{
/*QQ互联对象*/
/* QQ互联对象 */
protected $qc;
/**
* 初始化
*/
protected function init()
protected function init()
{
$this->qc = new \QC();
}
/**
* 获取授权URL
*
... ... @@ -38,7 +39,7 @@ class Call extends Factory
{
return $this->qc->qq_login();
}
/**
* 获取授权的TOKEN
*
... ... @@ -47,20 +48,20 @@ class Call extends Factory
public function getAccessToken()
{
$token = array();
// try
// {
$token = $this->qc->qq_callback();
$token['openid'] = $this->qc->get_openid();
$token = $this->qc->qq_callback();
$token['openid'] = $this->qc->get_openid();
// }
// catch (Exception $e)
// {
// // do nothing
// }
return $token;
}
/**
* 获取当前用户的基本资料
*
... ... @@ -70,22 +71,20 @@ class Call extends Factory
public function getUserInfo($token)
{
$userInfo = array();
if (is_array($token) && isset($token['openid']))
{
if (is_array($token) && isset($token['openid'])) {
$this->qc = new \QC($token['access_token'], $token['openid']);
$userInfo = $this->qc->get_user_info();
if (isset($userInfo['ret']) && $userInfo['ret'] != 0)
{
if (isset($userInfo['ret']) && $userInfo['ret'] != 0) {
$userInfo = array();
}
}
return $userInfo;
}
/**
* 获取当前用户的偶像(关注)列表
*
... ... @@ -107,22 +106,20 @@ class Call extends Factory
public function getFriends($token, $params)
{
$friends = array();
if (is_array($token) && isset($token['openid']))
{
if (is_array($token) && isset($token['openid'])) {
$this->qc = new \QC($token['access_token'], $token['openid']);
$friends = $this->qc->get_idollist($params);
if (isset($friends['ret']) && $friends['ret'] != 0)
{
if (isset($friends['ret']) && $friends['ret'] != 0) {
$friends = array();
}
}
return $friends;
}
/**
* 同步分享
*
... ... @@ -135,22 +132,21 @@ class Call extends Factory
public function syncShare($token, $content, $image, $link)
{
$result = false;
if (is_array($token) && isset($token['openid']))
{
if (is_array($token) && isset($token['openid'])) {
$this->qc = new \QC($token['access_token'], $token['openid']);
$param = array('title' => '来自YOHO.CN的分享', 'url' => $link, 'summary' => $content,
'images' => $image, 'site' => 'yoho.cn', 'fromurl' => SITE_MAIN,);
$param = array('title' => '来自YOHO.CN的分享', 'url' => $link, 'summary' => $content,
'images' => $image, 'site' => 'yoho.cn', 'fromurl' => SITE_MAIN,);
$response = $this->qc->add_share($param);
if (isset($response['ret']) && $response['ret'] == 0)
{
if (isset($response['ret']) && $response['ret'] == 0) {
$result = true;
}
}
return $result;
}
}
\ No newline at end of file
}
... ...
<?php
defined('SITE_MAIN') || define('SITE_MAIN', $_SERVER['HTTP_HOST']);
return array(
'appid' => '100229394',
'appkey' => 'c0af9c29e0900813028c2ccb42021792',
'callback' => SITE_MAIN . '/passport/login/qqcallback',
'scope' => 'get_user_info,add_share,upload_pic,get_idollist,get_fanslist',
'errorReport' => true,
);
\ No newline at end of file
'appid' => '100229394',
'appkey' => 'c0af9c29e0900813028c2ccb42021792',
'callback' => SITE_MAIN . '/passport/login/qqcallback',
'scope' => 'get_user_info,add_share,upload_pic,get_idollist,get_fanslist',
'errorReport' => true,
);
... ...
<?php
/* PHP SDK
* @version 2.0.0
* @author connect@qq.com
* @copyright © 2013, Tencent Corporation. All rights reserved.
*/
require_once(QC_CLASS_PATH.'Recorder.class.php');
require_once(QC_CLASS_PATH . 'Recorder.class.php');
/*
* @brief ErrorCase类,封闭异常
* */
class ErrorCase{
class ErrorCase
{
private $errorMsg;
public function __construct(){
public function __construct()
{
$this->errorMsg = array(
"20001" => "<h2>配置文件损坏或无法读取,请重新执行intall</h2>",
"30001" => "<h2>The state does not match. You may be a victim of CSRF.</h2>",
"50001" => "<h2>可能是服务器无法请求https协议</h2>可能未开启curl支持,请尝试开启curl支持,重启web服务器,如果问题仍未解决,请联系我们"
);
);
}
/**
... ... @@ -27,22 +32,27 @@ class ErrorCase{
* @param int $code 错误代码
* @param string $description 描述信息(可选)
*/
public function showError($code, $description = '$'){
public function showError($code, $description = '$')
{
$recorder = new Recorder();
if(! $recorder->readInc("errorReport")){
die();//die quietly
if (!$recorder->readInc("errorReport")) {
die(); //die quietly
}
echo "<meta charset=\"UTF-8\">";
if($description == "$"){
if ($description == "$") {
die($this->errorMsg[$code]);
}else{
} else {
echo "<h3>error:</h3>$code";
echo "<h3>msg :</h3>$description";
exit();
exit();
}
}
public function showTips($code, $description = '$'){
public function showTips($code, $description = '$')
{
}
}
... ...
<?php
/* PHP SDK
* @version 2.0.0
* @author connect@qq.com
* @copyright © 2013, Tencent Corporation. All rights reserved.
*/
require_once(QC_CLASS_PATH.'Recorder.class.php');
require_once(QC_CLASS_PATH.'URL.class.php');
require_once(QC_CLASS_PATH.'ErrorCase.class.php');
require_once(QC_CLASS_PATH . 'Recorder.class.php');
require_once(QC_CLASS_PATH . 'URL.class.php');
require_once(QC_CLASS_PATH . 'ErrorCase.class.php');
use Hood\Session;
class Oauth{
class Oauth
{
const VERSION = "2.0";
const GET_AUTH_CODE_URL = "https://graph.qq.com/oauth2.0/authorize";
... ... @@ -20,15 +23,16 @@ class Oauth{
protected $recorder;
public $urlUtils;
protected $error;
function __construct(){
function __construct()
{
$this->recorder = new Recorder();
$this->urlUtils = new URL();
$this->error = new ErrorCase();
}
public function qq_login(){
public function qq_login()
{
$appid = $this->recorder->readInc("appid");
$callback = $this->recorder->readInc("callback");
$scope = $this->recorder->readInc("scope");
... ... @@ -37,9 +41,9 @@ class Oauth{
$state = md5(uniqid(rand(), TRUE));
// $this->recorder->write('state',$state);
//$_SESSION['qqstate'] = $state;
setcookie('_QQ_STATE', $state, 0, '/', '.yohobuy.com');
//-------构造请求参数列表
$keysArr = array(
"response_type" => "code",
... ... @@ -49,14 +53,14 @@ class Oauth{
"scope" => $scope
);
$login_url = $this->urlUtils->combineURL(self::GET_AUTH_CODE_URL, $keysArr);
$login_url = $this->urlUtils->combineURL(self::GET_AUTH_CODE_URL, $keysArr);
header("Location:$login_url");
}
public function qq_callback(){
public function qq_callback()
{
//$state = $this->recorder->read("state");
//--------验证state防止CSRF攻击
// if($_GET['state'] != $state){
$state = isset($_COOKIE['_QQ_STATE']) ? $_COOKIE['_QQ_STATE'] : null;
... ... @@ -77,14 +81,14 @@ class Oauth{
$token_url = $this->urlUtils->combineURL(self::GET_ACCESS_TOKEN_URL, $keysArr);
$response = $this->urlUtils->get_contents($token_url);
if(strpos($response, "callback") !== false){
if (strpos($response, "callback") !== false) {
$lpos = strpos($response, "(");
$rpos = strrpos($response, ")");
$response = substr($response, $lpos + 1, $rpos - $lpos -1);
$response = substr($response, $lpos + 1, $rpos - $lpos - 1);
$msg = json_decode($response);
if(isset($msg->error)){
if (isset($msg->error)) {
$this->error->showError($msg->error, $msg->error_description);
}
}
... ... @@ -94,12 +98,12 @@ class Oauth{
$this->recorder->write("access_token", $params["access_token"]);
// return $params["access_token"];
// 根据业务需要改造了一下
return $params;
}
public function get_openid(){
public function get_openid()
{
//-------请求参数列表
$keysArr = array(
... ... @@ -110,21 +114,21 @@ class Oauth{
$response = $this->urlUtils->get_contents($graph_url);
//--------检测错误是否发生
if(strpos($response, "callback") !== false){
if (strpos($response, "callback") !== false) {
$lpos = strpos($response, "(");
$rpos = strrpos($response, ")");
$response = substr($response, $lpos + 1, $rpos - $lpos -1);
$response = substr($response, $lpos + 1, $rpos - $lpos - 1);
}
$user = json_decode($response);
if(isset($user->error)){
if (isset($user->error)) {
$this->error->showError($user->error, $user->error_description);
}
//------记录openid
$this->recorder->write("openid", $user->openid);
return $user->openid;
}
}
... ...
<?php
/* PHP SDK
* @version 2.0.0
* @author connect@qq.com
* @copyright © 2013, Tencent Corporation. All rights reserved.
*/
require_once(QC_CLASS_PATH.'Oauth.class.php');
require_once(QC_CLASS_PATH . 'Oauth.class.php');
/*
* @brief QC类,api外部对象,调用接口全部依赖于此对象
* */
class QC extends Oauth{
class QC extends Oauth
{
private $kesArr, $APIMap;
/**
... ... @@ -22,19 +26,20 @@ class QC extends Oauth{
* @param string $openid openid value
* @return Object QC
*/
public function __construct($access_token = "", $openid = ""){
public function __construct($access_token = "", $openid = "")
{
parent::__construct();
//如果access_token和openid为空,则从session里去取,适用于demo展示情形
if($access_token === "" || $openid === ""){
if ($access_token === "" || $openid === "") {
$this->keysArr = array(
"oauth_consumer_key" => (int)$this->recorder->readInc("appid"),
"oauth_consumer_key" => (int) $this->recorder->readInc("appid"),
"access_token" => $this->recorder->read("access_token"),
"openid" => $this->recorder->read("openid")
);
}else{
} else {
$this->keysArr = array(
"oauth_consumer_key" => (int)$this->recorder->readInc("appid"),
"oauth_consumer_key" => (int) $this->recorder->readInc("appid"),
"access_token" => $access_token,
"openid" => $openid
);
... ... @@ -46,8 +51,6 @@ class QC extends Oauth{
* 规则 array( baseUrl, argListArr, method)
*/
$this->APIMap = array(
/* qzone */
"add_blog" => array(
"https://graph.qq.com/blog/add_one_blog",
... ... @@ -56,7 +59,7 @@ class QC extends Oauth{
),
"add_topic" => array(
"https://graph.qq.com/shuoshuo/add_topic",
array("richtype","richval","con","#lbs_nm","#lbs_x","#lbs_y","format" => "json", "#third_source"),
array("richtype", "richval", "con", "#lbs_nm", "#lbs_x", "#lbs_y", "format" => "json", "#third_source"),
"POST"
),
"get_user_info" => array(
... ... @@ -85,18 +88,17 @@ class QC extends Oauth{
),
"add_share" => array(
"https://graph.qq.com/share/add_share",
array("title", "url", "#comment","#summary","#images","format" => "json","#type","#playurl","#nswb","site","fromurl"),
array("title", "url", "#comment", "#summary", "#images", "format" => "json", "#type", "#playurl", "#nswb", "site", "fromurl"),
"POST"
),
"check_page_fans" => array(
"https://graph.qq.com/user/check_page_fans",
array("page_id" => "314416946","format" => "json")
array("page_id" => "314416946", "format" => "json")
),
/* wblog */
"add_t" => array(
"https://graph.qq.com/t/add_t",
array("format" => "json", "content","#clientip","#longitude","#compatibleflag"),
array("format" => "json", "content", "#clientip", "#longitude", "#compatibleflag"),
"POST"
),
"add_pic_t" => array(
... ... @@ -140,55 +142,54 @@ class QC extends Oauth{
"POST"
),
/* pay */
"get_tenpay_addr" => array(
"https://graph.qq.com/cft_info/get_tenpay_addr",
array("ver" => 1,"limit" => 5,"offset" => 0,"format" => "json")
array("ver" => 1, "limit" => 5, "offset" => 0, "format" => "json")
)
);
}
//调用相应api
private function _applyAPI($arr, $argsList, $baseUrl, $method){
private function _applyAPI($arr, $argsList, $baseUrl, $method)
{
$pre = "#";
$keysArr = $this->keysArr;
$optionArgList = array();//一些多项选填参数必选一的情形
foreach($argsList as $key => $val){
$optionArgList = array(); //一些多项选填参数必选一的情形
foreach ($argsList as $key => $val) {
$tmpKey = $key;
$tmpVal = $val;
if(!is_string($key)){
if (!is_string($key)) {
$tmpKey = $val;
if(strpos($val,$pre) === 0){
if (strpos($val, $pre) === 0) {
$tmpVal = $pre;
$tmpKey = substr($tmpKey,1);
if(preg_match("/-(\d$)/", $tmpKey, $res)){
$tmpKey = substr($tmpKey, 1);
if (preg_match("/-(\d$)/", $tmpKey, $res)) {
$tmpKey = str_replace($res[0], "", $tmpKey);
$optionArgList[$res[1]][] = $tmpKey;
}
}else{
} else {
$tmpVal = null;
}
}
//-----如果没有设置相应的参数
if(!isset($arr[$tmpKey]) || $arr[$tmpKey] === ""){
if (!isset($arr[$tmpKey]) || $arr[$tmpKey] === "") {
if($tmpVal == $pre){//则使用默认的值
if ($tmpVal == $pre) {//则使用默认的值
continue;
}else if($tmpVal){
} else if ($tmpVal) {
$arr[$tmpKey] = $tmpVal;
}else{
if($v = $_FILES[$tmpKey]){
} else {
if ($v = $_FILES[$tmpKey]) {
$filename = dirname($v['tmp_name'])."/".$v['name'];
$filename = dirname($v['tmp_name']) . "/" . $v['name'];
move_uploaded_file($v['tmp_name'], $filename);
$arr[$tmpKey] = "@$filename";
}else{
$this->error->showError("api调用参数错误","未传入参数$tmpKey");
} else {
$this->error->showError("api调用参数错误", "未传入参数$tmpKey");
}
}
}
... ... @@ -196,29 +197,30 @@ class QC extends Oauth{
$keysArr[$tmpKey] = $arr[$tmpKey];
}
//检查选填参数必填一的情形
foreach($optionArgList as $val){
foreach ($optionArgList as $val) {
$n = 0;
foreach($val as $v){
if(in_array($v, array_keys($keysArr))){
foreach ($val as $v) {
if (in_array($v, array_keys($keysArr))) {
$n ++;
}
}
if(! $n){
$str = implode(",",$val);
$this->error->showError("api调用参数错误",$str."必填一个");
if (!$n) {
$str = implode(",", $val);
$this->error->showError("api调用参数错误", $str . "必填一个");
}
}
if($method == "POST"){
if($baseUrl == "https://graph.qq.com/blog/add_one_blog") $response = $this->urlUtils->post($baseUrl, $keysArr, 1);
else $response = $this->urlUtils->post($baseUrl, $keysArr, 0);
}else if($method == "GET"){
if ($method == "POST") {
if ($baseUrl == "https://graph.qq.com/blog/add_one_blog")
$response = $this->urlUtils->post($baseUrl, $keysArr, 1);
else
$response = $this->urlUtils->post($baseUrl, $keysArr, 0);
}else if ($method == "GET") {
$response = $this->urlUtils->get($baseUrl, $keysArr);
}
return $response;
}
/**
... ... @@ -229,10 +231,11 @@ class QC extends Oauth{
* @since 5.0
* @return array 返加调用结果数组
*/
public function __call($name,$arg){
public function __call($name, $arg)
{
//如果APIMap不存在相应的api
if(empty($this->APIMap[$name])){
$this->error->showError("api调用名称错误","不存在的API: <span style='color:red;'>$name</span>");
if (empty($this->APIMap[$name])) {
$this->error->showError("api调用名称错误", "不存在的API: <span style='color:red;'>$name</span>");
}
//从APIMap获取api相应参数
... ... @@ -240,18 +243,18 @@ class QC extends Oauth{
$argsList = $this->APIMap[$name][1];
$method = isset($this->APIMap[$name][2]) ? $this->APIMap[$name][2] : "GET";
if(empty($arg)){
if (empty($arg)) {
$arg[0] = null;
}
//对于get_tenpay_addr,特殊处理,php json_decode对\xA312此类字符支持不好
if($name != "get_tenpay_addr"){
if ($name != "get_tenpay_addr") {
$response = json_decode($this->_applyAPI($arg[0], $argsList, $baseUrl, $method));
$responseArr = $this->objToArr($response);
}else{
} else {
$responseArr = $this->simple_json_parser($this->_applyAPI($arg[0], $argsList, $baseUrl, $method));
}
// 根据业务需求,返回结果
//检查返回ret判断api是否成功调用
// if($responseArr['ret'] == 0){
... ... @@ -264,18 +267,18 @@ class QC extends Oauth{
}
//php 对象到数组转换
private function objToArr($obj){
if(!is_object($obj) && !is_array($obj)) {
private function objToArr($obj)
{
if (!is_object($obj) && !is_array($obj)) {
return $obj;
}
$arr = array();
foreach($obj as $k => $v){
foreach ($obj as $k => $v) {
$arr[$k] = $this->objToArr($v);
}
return $arr;
}
/**
* get_access_token
* 获得access_token
... ... @@ -283,19 +286,22 @@ class QC extends Oauth{
* @since 5.0
* @return string 返加access_token
*/
public function get_access_token(){
public function get_access_token()
{
return $this->recorder->read("access_token");
}
//简单实现json到php数组转换功能
private function simple_json_parser($json){
$json = str_replace("{","",str_replace("}","", $json));
private function simple_json_parser($json)
{
$json = str_replace("{", "", str_replace("}", "", $json));
$jsonValue = explode(",", $json);
$arr = array();
foreach($jsonValue as $v){
foreach ($jsonValue as $v) {
$jValue = explode(":", $v);
$arr[str_replace('"',"", $jValue[0])] = (str_replace('"', "", $jValue[1]));
$arr[str_replace('"', "", $jValue[0])] = (str_replace('"', "", $jValue[1]));
}
return $arr;
}
}
... ...
... ... @@ -25,7 +25,7 @@ class Recorder
if (empty($this->inc)) {
$this->error->showError("20001");
}
self::$data = array();
// if(empty($_SESSION['QC_userData'])){
... ...
<?php
/* PHP SDK
* @version 2.0.0
* @author connect@qq.com
* @copyright © 2013, Tencent Corporation. All rights reserved.
*/
require_once(QC_CLASS_PATH.'ErrorCase.class.php');
require_once(QC_CLASS_PATH . 'ErrorCase.class.php');
/*
* @brief url封装类,将常用的url请求操作封装在一起
* */
class URL{
class URL
{
private $error;
public function __construct(){
public function __construct()
{
$this->error = new ErrorCase();
}
... ... @@ -24,17 +29,18 @@ class URL{
* @param array $keysArr 参数列表数组
* @return string 返回拼接的url
*/
public function combineURL($baseURL,$keysArr){
$combined = $baseURL."?";
public function combineURL($baseURL, $keysArr)
{
$combined = $baseURL . "?";
$valueArr = array();
foreach($keysArr as $key => $val){
foreach ($keysArr as $key => $val) {
$valueArr[] = "$key=$val";
}
$keyStr = implode("&",$valueArr);
$keyStr = implode("&", $valueArr);
$combined .= ($keyStr);
return $combined;
}
... ... @@ -44,7 +50,8 @@ class URL{
* @param string $url 请求的url,拼接后的
* @return string 请求返回的内容
*/
public function get_contents($url){
public function get_contents($url)
{
if (ini_get("allow_url_fopen") == "1") {
//2015-3-5 wuxiao 尝试解决Maximum execution time of 30 seconds exceeded
//$response = file_get_contents($url);
... ... @@ -54,22 +61,22 @@ class URL{
'timeout' => 10,
)
)));
}else{
} else {
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_URL, $url);
//2015-3-5 wuxiao 尝试解决Maximum execution time of 30 seconds exceeded
curl_setopt ( $ci, CURLOPT_CONNECTTIMEOUT, 3 );
curl_setopt ( $ci, CURLOPT_TIMEOUT, 7 );
$response = curl_exec($ch);
curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 3);
curl_setopt($ci, CURLOPT_TIMEOUT, 7);
$response = curl_exec($ch);
curl_close($ch);
}
//-------请求为空
if(empty($response)){
if (empty($response)) {
$this->error->showError("50001");
}
... ... @@ -83,7 +90,8 @@ class URL{
* @param array $keysArr 参数列表数组
* @return string 返回的资源内容
*/
public function get($url, $keysArr){
public function get($url, $keysArr)
{
$combined = $this->combineURL($url, $keysArr);
return $this->get_contents($combined);
}
... ... @@ -96,22 +104,25 @@ class URL{
* @param int $flag 标志位
* @return string 返回的资源内容
*/
public function post($url, $keysArr, $flag = 0){
public function post($url, $keysArr, $flag = 0)
{
$ch = curl_init();
if(! $flag) curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $keysArr);
if (!$flag)
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $keysArr);
curl_setopt($ch, CURLOPT_URL, $url);
//2015-3-5 wuxiao 尝试解决Maximum execution time of 30 seconds exceeded
curl_setopt ( $ci, CURLOPT_CONNECTTIMEOUT, 3 );
curl_setopt ( $ci, CURLOPT_TIMEOUT, 7 );
curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 3);
curl_setopt($ci, CURLOPT_TIMEOUT, 7);
$ret = curl_exec($ch);
curl_close($ch);
return $ret;
}
}
... ...
... ... @@ -17,20 +17,21 @@ require dirname(__FILE__) . '/class/Saev2.class.php';
*/
class Call extends Factory
{
/*OAuth2.0对象*/
/* OAuth2.0对象 */
protected $oauth;
/*客户端操作对象*/
/* 客户端操作对象 */
protected $client;
/**
* 初始化
*/
protected function init()
protected function init()
{
$this->oauth = new \SaeTOAuthV2($this->apiConfig['appId'], $this->apiConfig['appKey']);
}
/**
* 获取授权URL
*/
... ... @@ -38,20 +39,19 @@ class Call extends Factory
{
return $this->oauth->getAuthorizeURL($this->apiConfig['appCallbackUrl']);
}
/**
* 获取授权的TOKEN
*/
public function getAccessToken()
{
$token = array();
if (isset($_REQUEST['code']))
{
if (isset($_REQUEST['code'])) {
$keys = array();
$keys['code'] = $_REQUEST['code'];
$keys['redirect_uri'] = $this->apiConfig['appCallbackUrl'];
$token = $this->oauth->getAccessToken('code', $keys);
// try
// {
... ... @@ -62,10 +62,10 @@ class Call extends Factory
// // do nothing
// }
}
return $token;
}
/**
* 获取当前用户的基本资料
*
... ... @@ -75,22 +75,20 @@ class Call extends Factory
public function getUserInfo($token)
{
$userInfo = array();
if (is_array($token) && isset($token['uid']))
{
if (is_array($token) && isset($token['uid'])) {
$this->client = new \SaeTClientV2($this->apiConfig['appId'], $this->apiConfig['appKey'], $token['access_token']);
$userInfo = $this->client->show_user_by_id($token['uid']);
if (isset($userInfo['error_code']) && $userInfo['error_code'] > 0)
{
if (isset($userInfo['error_code']) && $userInfo['error_code'] > 0) {
$userInfo = array();
}
}
return $userInfo;
}
/**
* 获取当前用户的关注列表
*
... ... @@ -106,22 +104,20 @@ class Call extends Factory
public function getFriends($token, $params)
{
$result = array();
if (is_array($token) && isset($token['access_token']))
{
if (is_array($token) && isset($token['access_token'])) {
$this->client = new \SaeTClientV2($this->apiConfig['appId'], $this->apiConfig['appKey'], $token['access_token']);
$result = $this->client->friends_by_id($params['uid'], $params['cursor'], $params['count']);
if (isset($result['error_code']) && $result['error_code'] > 0)
{
if (isset($result['error_code']) && $result['error_code'] > 0) {
$result = array();
}
}
return $result;
}
/**
* 获取用户的双向关注列表,即互粉列表
*
... ... @@ -131,22 +127,20 @@ class Call extends Factory
public function getBilateral($token, $params)
{
$result = array();
if (is_array($token) && isset($token['access_token']))
{
if (is_array($token) && isset($token['access_token'])) {
$this->client = new \SaeTClientV2($this->apiConfig['appId'], $this->apiConfig['appKey'], $token['access_token']);
$result = $this->client->bilateral($params['uid'], $params['page'], $params['count']);
if (isset($result['error_code']) && $result['error_code'] > 0)
{
if (isset($result['error_code']) && $result['error_code'] > 0) {
$result = array();
}
}
return $result;
}
/**
* 同步分享
*
... ... @@ -159,24 +153,22 @@ class Call extends Factory
public function syncShare($token, $content, $image, $link)
{
$result = false;
if (is_array($token) && isset($token['access_token']))
{
if (is_array($token) && isset($token['access_token'])) {
$content .= $link;
$this->client = new \SaeTClientV2($this->apiConfig['appId'], $this->apiConfig['appKey'], $token['access_token']);
$response = $this->client->upload($content, $image);
if (!isset($response['error_code']) || $response['error_code'] == 0)
{
if (!isset($response['error_code']) || $response['error_code'] == 0) {
$result = true;
}
}
return $result;
}
/**
* 加关注
*
... ... @@ -188,24 +180,20 @@ class Call extends Factory
public function follow($token, $uid = null, $screenName = null)
{
$result = array();
if (is_array($token) && isset($token['access_token']))
{
if (is_array($token) && isset($token['access_token'])) {
$this->client = new \SaeTClientV2($this->apiConfig['appId'], $this->apiConfig['appKey'], $token['access_token']);
if ($uid !== null)
{
if ($uid !== null) {
$result = $this->client->follow_by_id($uid);
}
elseif ($screenName !== null)
{
} elseif ($screenName !== null) {
$result = $this->client->follow_by_name($screenName);
}
}
return $result;
}
/**
* 发布文字微博
*
... ... @@ -213,20 +201,19 @@ class Call extends Factory
* @param string $content 要发布的微博文本内容,必须做URLencode,内容不超过140个汉字
* @return array
*/
public function publish($token, $content)
public function publish($token, $content)
{
$result = array();
if (is_array($token) && isset($token['access_token']) && is_string($content))
{
if (is_array($token) && isset($token['access_token']) && is_string($content)) {
$this->client = new \SaeTClientV2($this->apiConfig['appId'], $this->apiConfig['appKey'], $token['access_token']);
$this->client->update($content);
}
return $result;
}
/**
* 发送一条私信
*
... ... @@ -237,11 +224,10 @@ class Call extends Factory
*/
public function sendMessage($token, $uid, $content, $id = null)
{
if (is_array($token) && isset($token['access_token']) && isset($uid))
{
if (is_array($token) && isset($token['access_token']) && isset($uid)) {
$this->client = new \SaeTClientV2($this->apiConfig['appId'], $this->apiConfig['appKey'], $token['access_token']);
$this->client->send_dm_by_id($uid, $content, $id);
}
}
}
\ No newline at end of file
}
... ...
<?php
defined('SITE_MAIN') || define('SITE_MAIN', $_SERVER['HTTP_HOST']);
return array(
'appId' => '3739328910',
'appKey' => '9d44cded26d048e23089e5e975c93df1',
'appCallbackUrl' => SITE_MAIN . '/passport/login/sinacallback',
);
\ No newline at end of file
'appId' => '3739328910',
'appKey' => '9d44cded26d048e23089e5e975c93df1',
'appCallbackUrl' => SITE_MAIN . '/passport/login/sinacallback',
);
... ...
This diff could not be displayed because it is too large.