Authored by 周少峰

Merge branch 'develop' of git.dev.yoho.cn:web/yohobuy into feature/web-list

Showing 55 changed files with 4768 additions and 5 deletions

Too many changes to show.

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

... ... @@ -838,6 +838,14 @@
},
...
],
defaultSizes: [
{
numZero: true,
name: 'X',
numStr: '0/10'
},
...
]
totalNum: 20
}
... ...
... ... @@ -375,7 +375,7 @@ class AbstractAction extends Controller_Abstract
return $udid;
}
/*
* 设置网站SEO的标题
*
... ...
<?php
namespace LibModels\Web\Passport;
use Api\Sign;
use Api\Yohobuy;
/**
* 登录的数据模型
*
* @name LoginData
* @package LibModels/Web/Passport
* @copyright yoho.inc
* @version 1.0 (2015-12-30 14:05:04)
* @author xiaowei <xiaowei.gong@yoho.cn>
*/
class LoginData extends \LibModels\Wap\Passport\LoginData
{
/**
* 第三方登录接口(包括alipay,qq,sina)
* @param string $nickname 姓名
* @param string $openId 第三方唯一识别码
* @param string $sourceType 登录方式
* @param string $shoppingKey 未登录用户唯一识别码, 默认为空
* @return array 登录返回结果
*/
public static function signinByOpenID($nickname, $openId, $sourceType, $shoppingKey = null)
{
// 构建必传参数
$param = Yohobuy::param();
$param['v'] = '4';
$param['method'] = 'app.passport.signinByOpenID';
$param['openId'] = $openId;
$param['source_type'] = $sourceType;
$param['nickname'] = $nickname;
if (!empty($shoppingKey)) {
$param['shopping_key'] = $shoppingKey;
}
$param['client_secret'] = Sign::getSign($param);
return Yohobuy::get(Yohobuy::API_URL, $param);
}
}
... ...
<?php
namespace LibModels\Web\Passport;
use Api\Yohobuy;
use Api\Sign;
use Plugin\Helpers;
class RegData extends \LibModels\Wap\Passport\RegData
{
/**
* 根据手机号获取用户信息[TODO +cache]
*
* @param string $area
* @param string $mobile
* @return string
*/
public static function getUserInfoByMobile($area, $mobile)
{
$param = Yohobuy::param();
$param['method'] = 'app.passport.userlist';
$param['mobile'] = Helpers::makeMobile($area, $mobile);
$param['debug'] = 'Y';
$param['screen_size'] = '320x568';
$param['client_secret'] = Sign::getSign($param);
return Yohobuy::post(Yohobuy::API_URL, $param);
}
}
\ No newline at end of file
... ...
... ... @@ -109,5 +109,45 @@ class Cache
{
return md5($prefix . '_' . $key);
}
/**
* 累加
*
* @param string $key
* @param int $offset
* @param int $initialValue
* @param int $expiry
* @return boolean
*/
public static function increment($key, $offset = 1, $initialValue = 0, $expiry = 0) {
return self::getMemcache('master')->increment(self::makeKey($key, 'master'), $offset, $initialValue, $expiry);
}
/**
* 递减
*
* @param string $key
* @param int $offset
* @return boolean
*/
public static function decrement($key, $offset = 1) {
return self::getMemcache('master')->decrement(self::makeKey($key, 'master'), $offset);
}
/**
* 获取memcache
*
* @param string $host
* @return object
*/
private static function getMemcache($host) {
$cache = new \stdClass();
if (DIRECTORY_SEPARATOR === '\\') {
$cache = HoodCache::Memcache($host);
}
else {
$cache = HoodCache::Memcached($host);
}
return $cache;
}
}
... ...
<?php
namespace Plugin;
use Hood\Session;
class Captcha {
private static $V = array(
"a",
"e",
"i",
"o",
"u",
"y"
);
private static $VN = array(
"a",
"e",
"i",
"o",
"u",
"y",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9"
);
private static $C = array(
"b",
"c",
"d",
"f",
"g",
"h",
"j",
"k",
"m",
"n",
"p",
"q",
"r",
"s",
"t",
"u",
"v",
"w",
"x",
"z"
);
private static $CN = array(
"b",
"c",
"d",
"f",
"g",
"h",
"j",
"k",
"m",
"n",
"p",
"q",
"r",
"s",
"t",
"u",
"v",
"w",
"x",
"z",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9"
);
private $_width = 160;
private $_height = 60;
private $_fs = 28;
private $_dotNoiseLevel = 50;
private $_lineNoiseLevel = 5;
private $_wordLen = 6;
private $_useNumbers = true;
/**
* Generate new random word
*
* @return string
*/
protected function _generateWord() {
$word = '';
$wordLen = $this->getWordLen ();
$vowels = $this->_useNumbers ? self::$VN : self::$V;
$consonants = $this->_useNumbers ? self::$CN : self::$C;
for($i = 0; $i < $wordLen; $i = $i + 2) {
$consonant = $consonants [array_rand ( $consonants )];
$vowel = $vowels [array_rand ( $vowels )];
$word .= $consonant . $vowel;
}
if (strlen ( $word ) > $wordLen) {
$word = substr ( $word, 0, $wordLen );
}
return $word;
}
public function getWordLen() {
return $this->_wordLen;
}
/**
* 设置验证码长度
*
* @param string $wordLen
* @return \Plugin\Captcha
*/
public function setWordLen($wordLen) {
$this->_wordLen = $wordLen;
return $this;
}
/**
* 获取图像宽度
*
* @return int
*/
public function getWidth() {
return $this->_width;
}
/**
* 获取图像高度
*
* @return int
*/
public function getHeight() {
return $this->_height;
}
/**
* 设置图像宽度
*
* @param int $width
* @return \Plugin\Captcha
*/
public function setWidth($width) {
$this->_width = $width;
return $this;
}
/**
* 设置图像高度
*
* @param int $height
* @return \Plugin\Captcha
*/
public function setHeight($height) {
$this->_height = $height;
return $this;
}
/**
*
*/
public function getFontSize() {
return $this->_fs;
}
public function setFontSize($fs) {
$this->_fs = $fs;
return $this;
}
/**
* 设置干扰点
*
* @param string $noise
* @return \Plugin\Captcha
*/
public function setDotNoiseLevel($noise = 100) {
$this->_dotNoiseLevel = $noise;
return $this;
}
/**
* 设置干扰线
*
* @param string $noise
* @return \Plugin\Captcha
*/
public function setLineNoiseLevel($noise = 5) {
$this->_lineNoiseLevel = $noise;
return $this;
}
/**
* 获取干扰点
*
* @return string
*/
public function getDotNoiseLevel() {
return $this->_dotNoiseLevel;
}
/**
* 获取干扰线
*
* @return string
*/
public function getLineNoiseLevel() {
return $this->_lineNoiseLevel;
}
/**
* Generate random frequency
*
* @return float
*/
protected function _randomFreq() {
return mt_rand ( 700000, 1000000 ) / 15000000;
}
/**
* Generate random phase
*
* @return float
*/
protected function _randomPhase() {
// random phase from 0 to pi
return mt_rand ( 0, 3141592 ) / 1000000;
}
/**
* Generate random character size
*
* @return int
*/
protected function _randomSize() {
return 0;
return mt_rand ( 300, 700 ) / 100;
}
public function getFont() {
return dirname ( __FILE__ ) . '/ttf/2.ttf';
}
/**
* 将验证码存入Sessioin
*
* @param string $namespace
* @param string $code
* @return true
*/
public static function setToSession($namespace, $code) {
self::getSessionObject($namespace)->captcha = $code;
return true;
}
/**
* 从session中取出已经生成的验证码
*
* @param string $namespace
* @return string|false
*/
public static function getFromSession($namespace) {
$code = self::getSessionObject($namespace)->captcha;
if (!empty( $code )) {
return $code;
} else {
return false;
}
}
/**
* Constructor
*
* @param array $options
* @return void
*/
public function __construct($options = null) {
if (isset ( $options )) {
foreach ( $options as $k => $v ) {
call_user_func ( array ($this, 'set' . ucfirst ( $k ) ), $v );
}
}
}
public function generate($namespace) {
$word = $this->_generateWord ();
self::setToSession ( $namespace, $word );
header ( "Content-type: image/png" );
$this->_generateImage ( $word );
return $word;
}
/**
* 生成验证码
*
* @param string $word
*/
protected function _generateImage($word) {
if (! extension_loaded("gd")) {
exit("Image CAPTCHA requires GD extension");
}
if (! function_exists("imagepng")) {
exit("Image CAPTCHA requires PNG support");
}
if (! function_exists("imageftbbox")) {
exit("Image CAPTCHA requires FT fonts support");
}
$font = $this->getFont();
if (empty($font)) {
exit("Image CAPTCHA requires font");
}
$w = $this->getWidth ();
$h = $this->getHeight ();
$fsize = $this->getFontSize ();
$img = imagecreatetruecolor ( $w, $h );
$text_color = imagecolorallocate ( $img, 0, 0, 0 );
$bg_color = imagecolorallocate ( $img, 255, 255, 255 );
imagefilledrectangle ( $img, 0, 0, $w - 1, $h - 1, $bg_color );
$textbox = imageftbbox ( $fsize, 0, $font, $word );
$x = ($w - ($textbox [2] - $textbox [0])) / 2;
$y = ($h - ($textbox [7] - $textbox [1])) / 2;
imagefttext ( $img, $fsize, 0, $x, $y, $text_color, $font, $word );
// generate noise
for($i = 0; $i < $this->_dotNoiseLevel; $i ++) {
imagefilledellipse ( $img, mt_rand ( 0, $w ), mt_rand ( 0, $h ), 2, 2, $text_color );
}
for($i = 0; $i < $this->_lineNoiseLevel; $i ++) {
imageline ( $img, mt_rand ( 0, $w ), mt_rand ( 0, $h ), mt_rand ( 0, $w ), mt_rand ( 0, $h ), $text_color );
}
// transformed image
$img2 = imagecreatetruecolor ( $w, $h );
$bg_color = imagecolorallocate ( $img2, 255, 255, 255 );
imagefilledrectangle ( $img2, 0, 0, $w - 1, $h - 1, $bg_color );
// apply wave transforms
$freq1 = $this->_randomFreq ();
$freq2 = $this->_randomFreq ();
$freq3 = $this->_randomFreq ();
$freq4 = $this->_randomFreq ();
$ph1 = $this->_randomPhase ();
$ph2 = $this->_randomPhase ();
$ph3 = $this->_randomPhase ();
$ph4 = $this->_randomPhase ();
$szx = $this->_randomSize ();
$szy = $this->_randomSize ();
for($x = 0; $x < $w; $x ++) {
for($y = 0; $y < $h; $y ++) {
$sx = $x + (sin ( $x * $freq1 + $ph1 ) + sin ( $y * $freq3 + $ph3 )) * $szx;
$sy = $y + (sin ( $x * $freq2 + $ph2 ) + sin ( $y * $freq4 + $ph4 )) * $szy;
if ($sx < 0 || $sy < 0 || $sx >= $w - 1 || $sy >= $h - 1) {
continue;
} else {
$color = (imagecolorat ( $img, $sx, $sy ) >> 16) & 0xFF;
$color_x = (imagecolorat ( $img, $sx + 1, $sy ) >> 16) & 0xFF;
$color_y = (imagecolorat ( $img, $sx, $sy + 1 ) >> 16) & 0xFF;
$color_xy = (imagecolorat ( $img, $sx + 1, $sy + 1 ) >> 16) & 0xFF;
}
if ($color == 255 && $color_x == 255 && $color_y == 255 && $color_xy == 255) {
// ignore background
continue;
} elseif ($color == 0 && $color_x == 0 && $color_y == 0 && $color_xy == 0) {
// transfer inside of the image as-is
$newcolor = 0;
} else {
// do antialiasing for border items
$frac_x = $sx - floor ( $sx );
$frac_y = $sy - floor ( $sy );
$frac_x1 = 1 - $frac_x;
$frac_y1 = 1 - $frac_y;
$newcolor = $color * $frac_x1 * $frac_y1 + $color_x * $frac_x * $frac_y1 + $color_y * $frac_x1 * $frac_y + $color_xy * $frac_x * $frac_y;
}
imagesetpixel ( $img2, $x, $y, imagecolorallocate ( $img2, $newcolor, $newcolor, $newcolor ) );
}
}
// generate noise
for($i = 0; $i < $this->_dotNoiseLevel; $i ++) {
imagefilledellipse ( $img2, mt_rand ( 0, $w ), mt_rand ( 0, $h ), 2, 2, $text_color );
}
for($i = 0; $i < $this->_lineNoiseLevel; $i ++) {
imageline ( $img2, mt_rand ( 0, $w ), mt_rand ( 0, $h ), mt_rand ( 0, $w ), mt_rand ( 0, $h ), $text_color );
}
imagepng ( $img2 );
imagedestroy ( $img );
imagedestroy ( $img2 );
}
/**
* 获取session对象
*
* @param string $namespace
* @return object
*/
public static function getSessionObject($namespace)
{
if(strtoupper(substr(PHP_OS,0,3)) === 'WIN')
{
return Session::fileStart($namespace);
}
else
{
return Session::start($namespace, null, 'yohobuy.com');
}
}
}
\ No newline at end of file
... ...
... ... @@ -13,6 +13,9 @@ class Channel
public static function getFormat($channel, $data)
{
if(empty($data)) {
return array();
}
// 通用处理器
$result = Process::getContent($data, $channel);
$channelResult = array();
... ...
... ... @@ -322,11 +322,14 @@ class Process
'singlehot' => array(
'name' => '',
'imgHot' => array(),
'brands' => array()
'brands' => array(),
'navs'=> array(),
)
);
// text模版
$result['singlehot']['name'] = $title;
//textNav模版
$result['singlehot']['navs'] = self::mergeNavProcess($source, $type);
// goods模版
$result['singlehot']['imgHot'] = self::mergeGoodsProcess($goods, $type);
// floor模版
... ... @@ -503,6 +506,7 @@ class Process
);
// text
$result['girlkids']['name'] = $data[$key]['data']['text'];
// goods
$result['girlkids']['imgHot'] = self::mergeGoodsProcess($data[$key + 2], $type);
unset($data[$key], $data[$key + 1], $data[$key + 2]);
... ... @@ -762,7 +766,7 @@ class Process
$skns = '';
foreach ($data['data'] as $val) {
$skns .= $val['id'] . ' ';
}
}
$params = array(
'query' => rtrim($skns),
'client_type' => 'web'
... ...
... ... @@ -776,5 +776,34 @@ class Helpers
}
return 'http://item.yohobuy.com/product/pro_' . $product_id . '_' . $goods_id . '/' . $cn_alphabet. '.html';
}
/**
* 获取真实IP
*
* @return string
*/
public static function getClientIp()
{
$ip = '0.0.0.0';
if (isset($_SERVER['HTTP_CLIENT_IP']) && $_SERVER['HTTP_CLIENT_IP'] != '')
$ip = $_SERVER['HTTP_CLIENT_IP'];
elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR'] != '')
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
elseif (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] != '')
$ip = $_SERVER['REMOTE_ADDR'];
return $ip;
}
/**
* 组合国际手机号
* @param $area
* @param $mobile
* @return string
*/
public static function makeMobile($area, $mobile){
if(empty($area) || $area == 86){
return $mobile;
}
return $area.'-'.$mobile;
}
}
... ...
<?php
namespace Plugin\Partner\douban;
use Plugin\Partner\Factory;
define('DB_CLASS_PATH', dirname(__FILE__).'/class/');
require DB_CLASS_PATH . 'DoubanClient.class.php';
/**
* 豆瓣的调用接口
*
* @name Call
* @package lib/partner/douban
* @copyright yoho.inc
* @version 5.0 (2015-12-31 10:54:54)
* @author xiaowei <xiaowei.gong@yoho.cn>
*/
class Call extends Factory
{
/*人人网对象*/
protected $douban;
/**
* 初始化
*/
protected function init()
{
$this->douban = new \DoubanClient($this->apiConfig['appId'], $this->apiConfig['appKey'], $this->apiConfig['callback'], $this->apiConfig['scope']);
}
/**
* 获取授权URL
*
* @return string
*/
public function getAuthorizeUrl()
{
return $this->douban->getAuthorizeURL();
}
/**
* 获取授权的TOKEN
*
* @return array
*/
public function getAccessToken()
{
$token = array();
if (isset($_GET['code']))
{
try
{
// 设置authorizeCode
$this->douban->setAuthorizeCode($_GET['code']);
// 通过authorizeCode获取accessToken,至此完成用户授权
$this->douban->requestAccessToken();
$token = (array) $this->douban->getToken();
}
catch (Exception $e)
{
// do nothing
}
}
return $token;
}
/**
* 获取当前用户的基本资料
*
* @param array $token 授权成功的TOKEN, 默认为NULL
* @return array
*/
public function getUserInfo($token)
{
$userInfo = array();
if (is_array($token) && isset($token['access_token']))
{
// 获得保存的token
$this->douban->setAccessToken($token);
// 获得当前登录用户信息
$userInfo = $this->douban->api('/v2/user/~me', 'GET', null, true);
}
return $userInfo;
}
/**
* 获取当前用户的偶像(关注)列表
*
* 此接口暂未开放
*
* @return array
*/
public function getFriends($token, $params)
{
return array();
}
/**
* 同步分享
*
* @param String $image 新鲜事图片地址
* @param String $content 新鲜事主体内容 注意:最多200个字符。
* @param String $link 新鲜事标题和图片指向的链接
* @return Long 发布新鲜事的ID
*/
public function syncShare($token, $content, $image, $link)
{
$result = false;
if (is_array($token) && isset($token['access_token']))
{
// 获得保存的token
$this->douban->setAccessToken($token);
// 发表一篇说说
$param = array('source' => $this->apiConfig['appKey'], 'text' => $content, 'rec_image' => $image, 'rec_url' => $link,);
$result = $this->douban->api('/shuo/v2/statuses', 'POST', $param, true);
}
return $result;
}
}
\ No newline at end of file
... ...
<?php
defined('DOMAIN') || define('DOMAIN', $_SERVER['HTTP_HOST']);
return array(
'appId' => '09f4fa0661be14ec1ddeee13253a3ec4',
'appKey' => 'b4204e2055d63102',
'callback' => DOMAIN . '/passport/login/doubanback',
'scope' => 'douban_basic_common',
);
\ No newline at end of file
... ...
<?php
class DoubanClient {
/**
* @brief 豆瓣Oauth类词头
*/
const PREFIX = 'Douban';
/**
* @brief authorizeCode请求链接
*/
protected $authorizeUri = 'https://www.douban.com/service/auth2/auth';
/**
* @brief accessToken请求链接
*/
protected $accessUri = 'https://www.douban.com/service/auth2/token';
/**
* @brief api请求链接
*/
protected $apiUri = 'https://api.douban.com';
/**
* @brief 豆瓣应用public key
*/
protected $clientId;
/**
* @brief 豆瓣应用secret key
*/
protected $secret;
/**
* @brief callback链接
*/
protected $redirectUri;
/**
* @brief Api权限
*/
protected $scope;
/**
* @brief 返回类型,默认使用code
*/
protected $responseType;
/**
* @brief 用户授权码
*/
protected $authorizeCode;
/**
* @brief 储存返回的令牌(accessToken,refreshToken)
*/
protected $tokens;
/**
* @brief 通过authorizeCode获得的访问令牌
*/
protected $accessToken;
/**
* @brief 用于刷新accessToken
*/
protected $refreshToken;
/**
* @var 默认请求头信息
*/
protected $defaultHeader = array(
'Content_type: application/x-www-form-urlencoded'
);
/**
* @var 需授权的请求头
*/
protected $authorizeHeader;
/**
* @var curl默认设置
*/
protected $CURL_OPTS = array(
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_TIMEOUT => 60,
CURLOPT_USERAGENT => 'simple-douban-oauth2-0.4',
);
/**
* @brief 初始化豆瓣OAUTH,设置相关参数
*
* @param string $client_id
* @param string $secret
* @param string $redirect_uri
* @param string $scope
* @param string $responseType
*
* @return void
*/
public function __construct($clientId, $secret, $redirectUri, $scope ='douban_basic_common', $responseType = 'code')
{
$this->clientId = $clientId;
$this->secret = $secret;
$this->redirectUri = $redirectUri;
$this->scope = $scope;
$this->responseType = $responseType;
// // API基类路径
// $basePath = dirname(__FILE__).'/api/DoubanBase.php';
// // 载入API基类
// try {
// $this->fileLoader($basePath);
// } catch(Exception $e) {
// echo 'Baseloader error:'.$e->getMessage();
// }
}
/**
* @brief 跳转到豆瓣用户授权页面,获取AuthorizeCode
*
* @return redirect
*/
public function requestAuthorizeCode()
{
// 获取AuthorizeCode请求链接
$authorizeUrl = $this->getAuthorizeUrl();
header('Location:'.$authorizeUrl);
}
/**
* @brief 设置AuthorizeCode
*
* @param string $authorizeCode
*
* @return void
*/
public function setAuthorizeCode($authorizeCode)
{
$this->authorizeCode = $authorizeCode;
}
/**
* @brief 通过AuthorizeCode获取accessToken
*
* @return string
*/
public function requestAccessToken()
{
// 获取accessToken请求链接
$accessUrl = $this->getAccessUrl();
$header = $this->defaultHeader;
$result = $this->curl($accessUrl, 'POST', $header);
$this->tokens = json_decode($result);
$this->refreshToken = $this->tokens->refresh_token;
$this->accessToken = $this->tokens->access_token;
}
/**
* @brief 获取token
*
* @return string
*/
public function getToken()
{
return $this->tokens;
}
/**
* @brief 获取accessToken
*
* @return string
*/
public function getAccessToken()
{
return $this->accessToken;
}
/**
* @brief 设置token
*
* @return string
*/
public function setAccessToken($token)
{
if (is_array($token) && isset($token['access_token'])) {
$this->accessToken = $token['access_token'];
}
}
/**
* @brief 生成豆瓣用户授权页面完整地址
*
* @return string
*/
public function getAuthorizeUrl()
{
$params = array(
'client_id' => $this->clientId,
'redirect_uri' => $this->redirectUri,
'response_type' => $this->responseType,
'scope' => $this->scope
);
return $this->authorizeUri.'?'.http_build_query($params);
}
/**
* @brief 生成豆瓣access_token完整获取链接
*
* @return string
*/
public function getAccessUrl()
{
$params = array(
'client_id' => $this->clientId,
'client_secret' => $this->secret,
'redirect_uri' => $this->redirectUri,
'grant_type' => 'authorization_code',
'code' => $this->authorizeCode,
);
return $this->accessUri.'?'.http_build_query($params);
}
/**
* @brief 请求豆瓣API,返回包含相关数据的对象
*
* @param object $API
* @param array $data
* @param boolean 为true时会在header中发送accessToken
*
* @return object
*/
public function api($api, $type = 'POST', $data = null, $authorization = false)
{
// API的完整URL
$url = $this->apiUri.$api;
$header = $authorization ? $this->getAuthorizeHeader() : $this->defaultHeader;
$response = $this->curl($url, $type, $header, $data);
$result = json_decode($response, true);
return $result;
}
/**
* @brief 请求豆瓣API,返回包含相关数据的对象
*
* @param object $API
* @param array $data
* @param boolean 为true时会在header中发送accessToken
*
* @return object
*/
public function makeRequest($api, $data = null, $authorization = false)
{
// API的完整URL
$url = $this->apiUri.$api->uri;
$header = $authorization ? $this->getAuthorizeHeader() : $this->defaultHeader;
$type = $api->type;
return $this->curl($url, $type, $header, $data);
}
/**
* @brief 豆瓣API实例注册函数
*
* @param string $api
*
* @return object
*/
public function apiRegister($api)
{
$doubanApi = self::PREFIX.ucfirst(strtolower($api));
// 需要注册的API路径
$apiPath = dirname(__FILE__).'/api/'.$doubanApi.'.php';
try {
$this->fileLoader($apiPath);
} catch(Exception $e) {
echo 'Apiloader error:'.$e->getMessage();
}
return new $doubanApi($this->clientId);
}
/**
* @brief 获取Authorization header
*
* @return array
*/
protected function getAuthorizeHeader()
{
return $this->authorizeHeader = array('Authorization: Bearer '.$this->accessToken);
}
/**
* @brief 使用CURL模拟请求,并返回取得的数据
*
* @param string $url
* @param string $type
* @param array $header
* @param array $data
*
* @return object
*/
protected function curl($url, $type, $header, $data = null)
{
$opts = $this->CURL_OPTS;
$opts[CURLOPT_URL] = $url;
$opts[CURLOPT_CUSTOMREQUEST] = $type;
$header[] = 'Expect:';
$opts[CURLOPT_HTTPHEADER] = $header;
if ($type == 'POST' || $type =='PUT') {
$opts[CURLOPT_POSTFIELDS] = $data;
}
$ch = curl_init();
curl_setopt_array($ch, $opts);
$result = curl_exec($ch);
// if (curl_errno($ch)) {
// die('CURL error: '.curl_error($ch));
// }
curl_close($ch);
return $result;
}
/**
* @brief 文件加载类
*
* @param string $path
*
* @return void
*/
protected function fileLoader($path)
{
// 文件路径错误时抛出异常
if ( ! file_exists($path)) {
throw new Exception('The file you wanted to load does not exists.');
}
require $path;
}
}
... ...
<?php
/**
* @file DoubanBase.php
* @brief 豆瓣api的Base类
* @author JonChou <ilorn.mc@gmail.com>
* @date 2012-11-27
*/
class DoubanBase {
/**
* @brief 豆瓣API uri
*/
protected $uri;
/**
* @brief API请求方式
*/
protected $type;
/**
* @brief 豆瓣应用public key
*/
protected $clientId;
/**
* @brief 使用魔术方法获取类属性
*
* @param mixed $name
*
* @return mixed
*/
public function __get($name)
{
if (property_exists($this, $name)) {
return $this->$name;
}
}
}
... ...
<?php
/**
* @file DoubanBook.php
* @brief 豆瓣图书API
* @author JonChou <ilorn.mc@gmail.com>
* @date 2012-11-27
*/
class DoubanBook extends DoubanBase {
/**
* @brief 构造函数,初始设置clientId
*
* @param string $clientId
*
* @return void
*/
public function __construct($clientId)
{
$this->clientId = $clientId;
}
/**
* @brief 获取指定书籍
*
* @param int $id
*
* @return object
*/
public function getBook($id)
{
$this->uri = '/v2/book/'.$id;
$this->type = 'GET';
return $this;
}
/**
* @brief 获取Isbn对应书籍
*
* @param string $name
*
* @return object
*/
public function isbn($name)
{
$this->uri = '/v2/book/isbn/'.$name;
$this->type = 'GET';
return $this;
}
/**
* @brief 图书搜素接口(未测试),q和tag必选其一。
*
* @param string $q
* @param string $tag
* @param int $start
* @param int $count
*
* @return object
*/
public function search($q, $tag, $start = 0, $count = 20)
{
$params = array(
'q' => $q,
'tag' => $tag,
'start' => $start,
'count' => $count
);
$this->uri = '/v2/book/search?'.http_build_query($params);
$this->type = 'GET';
return $this;
}
/**
* @brief 获取某个图书中标记最多的标签(未测试)
*
* @param string $id
*
* @return object
*/
public function bookTags($id)
{
$this->uri = '/v2/book/'.$id.'/tags';
$this->type = 'GET';
return $this;
}
/**
* @brief 获取用户对图书的所有标签(未测试)
*
* @param string $name
*
* @return object
*/
public function userTags($name)
{
$this->uri = '/v2/book/user/'.$name.'/tags';
$this->type = 'GET';
return $this;
}
/**
* @brief 获取某个用户的所有图书收藏信息(未测试)
*
* @param string $name
*
* @return object
*/
public function collections($name)
{
$this->uri = '/v2/book/user/'.$name.'/collections';
$this->type = 'GET';
return $this;
}
/**
* @brief 获取用户对某本图书的收藏信息(为测试)
*
* @param string $id
*
* @return object
*/
public function getCollection($id)
{
$this->uri = '/v2/book/'.$id.'/collection';
$this->type = 'GET';
return $this;
}
/**
* @brief 用户收藏某本图书(未测试)
*
* @param string $id
*
* @return object
*/
public function addCollection($id)
{
$this->uri = '/v2/book/'.$id.'/collection';
$this->type = 'POST';
return $this;
}
/**
* @brief 用户修改对某本图书的收藏(未测试)
*
* @param string $id
*
* @return object
*/
public function editCollection($id)
{
$this->uri = '/v2/book/'.$id.'/collection';
$this->type = 'PUT';
return $this;
}
/**
* @brief 用户删除对某本图书的收藏(未测试)
*
* @param string $id
*
* @return object
*/
public function deleteCollection($id)
{
$this->uri = '/v2/book/'.$id.'/collection';
$this->type = 'DELETE';
return $this;
}
/**
* @brief 获取某个用户的所有笔记(未测试)
*
* @param string $name
*
* @return object
*/
public function userAnnotations($name)
{
$this->uri = '/v2/book/user/'.$name.'/annotations';
$this->type = 'GET';
return $this;
}
/**
* @brief 获取某本图书的所有笔记(未测试)
*
* @param string $id
*
* @return object
*/
public function bookAnnotations($id)
{
$this->uri = '/v2/book/user/'.$id.'/annotations';
$this->type = 'GET';
return $this;
}
/**
* @brief 获取某篇笔记的信息(未测试)
*
* @param string $id
*
* @return object
*/
public function getAnnotation($id)
{
$this->uri = '/v2/book/annotation/'.$id;
$this->type = 'GET';
return $this;
}
/**
* @brief 用户给某本图书写笔记(未测试)
*
* @param string $id
*
* @return object
*/
public function addAnnotation($id)
{
$this->uri = '/v2/book/'.$id.'/annotations';
$this->type = 'POST';
return $this;
}
/**
* @brief 用户修改某篇笔记(未测试)
*
* @param string $id
*
* @return object
*/
public function editAnnotation($id)
{
$this->uri = '/v2/book/annotation/'.$id;
$this->type = 'PUT';
return $this;
}
/**
* @brief 用户删除某篇笔记(未测试)
*
* @param string $id
*
* @return object
*/
public function deleteAnnotation($id)
{
$this->uri = '/v2/book/annotation/'.$id;
$this->type = 'DELETE';
return $this;
}
/**
* @brief 添加书评
*
* @return object
*/
public function addReview()
{
$this->uri = '/v2/book/reviews';
$this->type = 'POST';
return $this;
}
/**
* @brief 修改书评
*
* @param string $id
*
* @return object
*/
public function editReview($id)
{
$this->uri = '/v2/book/review/'.$id;
$this->type = 'PUT';
return $this;
}
/**
* @brief 删除书评
*
* @param string $id
*
* @return object
*/
public function deleteReview($id)
{
$this->uri = '/v2/book/review/'.$id;
$this->type = 'DELETE';
return $this;
}
}
... ...
<?php
/**
* @file DuobanComment.php
* @brief 豆瓣回复API接口
* @author JonChou <ilorn.mc@gmail.com>
* @date 2012-12-05
*/
class DoubanComment extends DoubanBase {
/**
* @brief 构造函数,初始设置clientId
*
* @param string $clientId
*
* @return void
*/
public function __construct($clientId)
{
$this->clientId = $clientId;
}
public function getCommentsList($target, $id)
{
$this->uri = '/v2/'.$target.'/'.$id.'/comments';
$this->type = 'GET';
return $this;
}
public function addComment($target, $id)
{
$this->uri = '/v2/'.$target.'/'.$id.'/comments';
$this->type = 'POST';
return $this;
}
public function getComment($target, $targetId, $commentId)
{
$this->uri = '/v2/'.$target.'/'.$targetId.'/comment/'.$commentId;
$this->type = 'GET';
return $this;
}
public function deleteComment($target, $targetId, $commentId)
{
$this->uri = '/v2/'.$target.'/'.$targetId.'/comment/'.$commentId;
$this->type = 'DELETE';
return $this;
}
}
... ...
<?php
/**
* @file DoubanDiscussion.php
* @brief 豆瓣论坛API接口
* @author JonChou <ilorn.mc@gmail.com>
* @date 2012-12-05
*/
class DoubanDiscussion extends DoubanBase {
/**
* @brief 构造函数,初始设置clientId
*
* @param string $clientId
*
* @return void
*/
public function __construct($clientId)
{
$this->clientId = $clientId;
}
public function getDiscussion($id)
{
$this->uri = '/v2/discussion/'.$id;
$this->type = 'GET';
return $this;
}
public function editDiscussion($id)
{
$this->uri = '/v2/discussion/'.$id;
$this->type = 'PUT';
return $this;
}
public function deleteDiscussion($id)
{
$this->uri = '/v2/discussion/'.$id;
$this->type = 'DELETE';
return $this;
}
public function addDiscussion($target, $id)
{
$this->uri = '/v2/'.$target.'/'.$id.'/discussions';
$this->type = 'POST';
return $this;
}
public function getDiscussionsList($target, $id)
{
$this->uri = '/v2/'.$target.'/'.$id.'/discussions';
$this->type = 'GET';
return $this;
}
}
... ...
<?php
/**
* @file DoubanDoumail.php
* @brief 豆邮API接口
* @author JonChou <ilorn.mc@gmail.com>
* @date 2012-12-05
*/
class DoubanDoumail extends DoubanBase {
/**
* @brief 构造函数,初始设置clientId
*
* @param string $clientId
*
* @return void
*/
public function __construct($clientId)
{
$this->clientId = $clientId;
}
/**
* @brief 获取一封豆邮
*
* @param string $id 豆邮id
*
* @return object
*/
public function get($id)
{
$this->uri = '/v2/doumail/'.$id;
$this->type = 'GET';
return $this;
}
/**
* @brief 获取用户收件箱
*
* @return object
*/
public function inbox()
{
$this->uri = '/v2/doumail/inbox';
$this->type = 'GET';
return $this;
}
public function outbox()
{
$this->uri = '/v2/doumail/outbox';
$this->type = 'GET';
return $this;
}
public function unread()
{
$this->uri = '/v2/doumail/inbox/unread';
$this->type = 'GET';
return $this;
}
public function read($id)
{
$this->uri = '/v2/doumail/'.$id;
$this->type = 'PUT';
return $this;
}
public function mutilRead()
{
$this->uri = '/v2/doumail/read';
$this->type = 'PUT';
return $this;
}
public function delete($id)
{
$this->uri = '/v2/doumail/'.$id;
$this->type = "DELETE";
return $this;
}
public function mutilDelete()
{
$this->uri = '/v2/doumail/delete';
$this->type = 'POST';
return $this;
}
public function add()
{
$this->uri = '/v2/doumails';
$this->type = 'POST';
return $this;
}
}
... ...
<?php
/**
* @file DoubanEvent.php
* @brief 豆瓣同城API接口
* @author JonChou <ilorn.mc@gmail.com>
* @date 2012-12-05
*/
class DoubanEvent extends DoubanBase {
/**
* @brief 构造函数,初始设置clientId
*
* @param string $clientId
*
* @return void
*/
public function __construct($clientId)
{
$this->clientId = $clientId;
}
public function get($id)
{
$this->uri = '/v2/event/'.$id;
$this->type = 'GET';
return $this;
}
public function participants($id)
{
$this->uri = '/v2/event/'.$id.'/participants';
$this->type = 'GET';
return $this;
}
public function wishers($id)
{
$this->uri = '/v2/event/'.$id.'/wishers';
$this->type = 'GET';
return $this;
}
public function userCreated($id)
{
$this->uri = '/v2/event/user_created/'.$id;
$this->type = 'GET';
return $this;
}
public function userParticipated($id)
{
$this->uri = '/v2/event/user_participated/'.$id;
$this->type = 'GET';
return $this;
}
public function userWished($id)
{
$this->uri = '/v2/event/user_wished/'.$id;
$this->type = 'GET';
return $this;
}
public function eventList()
{
$this->uri = '/v2/event/list';
$this->type = 'GET';
return $this;
}
public function loc($id)
{
$this->uri = '/v2/loc/'.$id;
$this->type = 'GET';
return $this;
}
public function locList()
{
$this->uri = '/v2/loc/list';
$this->type = 'GET';
return $this;
}
public function join($id)
{
$this->uri = '/v2/event/'.$id.'/participants';
$this->type = 'POST';
return $this;
}
public function quit($id)
{
$this->uri = '/v2/event/'.$id.'/participants';
$this->type = 'DELETE';
return $this;
}
public function wish($id)
{
$this->uri = '/v2/event/'.$id.'/wishers';
$this->type = 'POST';
return $this;
}
public function unwish($id)
{
$this->uri = '/v2/event/'.$id.'/wishers';
$this->type = 'DELETE';
return $this;
}
}
... ...
<?php
/**
* @file DoubanMiniblog.php
* @brief 豆瓣广播API
* @author JonChou <ilorn.mc@gmail.com>
* @date 2012-12-03
*/
class DoubanMiniblog extends DoubanBase {
/**
* @brief 构造函数,初始设置clientId
*
* @param string $clientId
*
* @return void
*/
public function __construct($clientId)
{
$this->clientId = $clientId;
}
/**
* @brief 发送一条豆瓣广播
*
* @return object
*/
public function addMiniblog()
{
$this->uri = '/shuo/v2/statuses/';
$this->type = 'POST';
return $this;
}
/**
* @brief 读取一条广播
*
* @param string $id
*
* @return object
*/
public function getMiniblog($id)
{
$this->uri = '/shuo/v2/statuses/'.$id;
$this->type = 'GET';
return $this;
}
/**
* @brief 删除一条广播
*
* @param string $id
*
* @return object
*/
public function deleteMiniblog($id)
{
$this->uri = '/shuo/v2/statuses/'.$id;
$this->type = 'DELETE';
return $this;
}
/**
* @brief 获取一条广播的回复列表(未测试)
*
* @param string $id
* @param int $start
* @param int $count
*
* @return object
*/
public function getCommentsList($id, $start = 0, $count = 20)
{
$this->uri = '/shuo/v2/statuses/'.$id.'/comments?start='.$start.'&count='.$count;
$this->type = 'GET';
return $this;
}
/**
* @brief 回复某条广播(未测试)
*
* @param string $id
*
* @return object
*/
public function addComment($id)
{
$this->uri = '/shuo/v2/statuses/'.$id.'/comments';
$this->type = 'POST';
return $this;
}
/**
* @brief 获取广播的单条回复(未测试)
*
* @param string $id
*
* @return object
*/
public function getComment($id)
{
$this->uri ='/shuo/v2/statuses/comment/'.$id;
$this->type = 'GET';
return $this;
}
/**
* @brief 删除广播的单条回复
*
* @param string $id
*
* @return object
*/
public function deleleComment($id)
{
$this->uri = '/shuo/v2/statuses/comment/'.$id;
$this->type = 'DELETE';
return $this;
}
/**
* @brief 获取一条广播的转发相关信息(未测试)
*
* @param string $id
*
* @return object
*/
public function getReshare($id)
{
$this->uri = '/shuo/v2/statuses/'.$id.'/reshare';
$this->type = 'GET';
return $this;
}
/**
* @brief 转发一条广播
*
* @param string $id
*
* @return object
*/
public function reshare($id)
{
$this->uri = '/shuo/v2/statuses/'.$id.'/reshare';
$this->type = 'POST';
return $this;
}
/**
* @brief 获取一条广播的赞相关信息(未测试)
*
* @param string $id
*
* @return object
*/
public function getLikers($id)
{
$this->uri = '/shuo/v2/statuses/'.$id.'/like';
$this->type = 'GET';
return $this;
}
/**
* @brief 赞一条广播
*
* @param string $id
*
* @return object
*/
public function like($id)
{
$this->uri = '/shuo/v2/statuses/'.$id.'/like';
$this->type = 'POST';
return $this;
}
/**
* @brief 取消赞(未测试)
*
* @param string $id
*
* @return object
*/
public function dislike($id)
{
$this->uri = '/shuo/v2/statuses/'.$id.'/like';
$this->type = 'DELETE';
return $this;
}
public function following($id)
{
$this->uri = '/shuo/v2/users/'.$id.'/following';
$this->type = 'GET';
return $this;
}
public function followers($id)
{
$this->uri = '/shuo/v2/users/'.$id.'/followers';
$this->type = 'GET';
return $this;
}
public function followInCommon($id)
{
$this->uri = '/shuo/v2/users/'.$id.'/follow_in_common';
$this->type = 'GET';
return $this;
}
public function suggestions($id)
{
$this->uri = '/shuo/v2/users/'.$id.'/following_followers_of';
$this->type = 'GET';
return $this;
}
public function block($id)
{
$this->uri = '/shuo/v2/users/'.$id.'/block';
$this->type = 'POST';
return $this;
}
public function unfollow()
{
$this->uri = '/shuo/v2/friendships/destroy';
$this->type = 'POST';
return $this;
}
public function show($source, $sourceId, $targetId)
{
$params = array(
'source' => $source,
'source_id' => $sourceId,
'target_id' => $targetId
);
$this->uri = '/shuo/v2/friendships/show?'.http_build_query($params);
$this->type = 'GET';
return $this;
}
/**
* @brief 获取当前登录用户及其所关注用户的最新广播(友邻广播)
*
* @param string $sinceId
* @param string $untilId
* @param string $count
* @param string $start
*
* @return object
*/
public function homeTimeline($sinceId = null, $untilId = null, $count = null, $start = null )
{
$params = array(
'since_id' => $sinceId,
'until_id' => $untilId,
'count' => $count,
'start' => $start
);
$this->uri = '/shuo/v2/statuses/home_timeline?'.http_build_query($params);
$this->type = 'GET';
return $this;
}
/**
* @brief 获取用户发布的广播列表
*
* @param string $user
* @param string $sinceId
* @param string $untilId
*
* @return object
*/
public function userTimeline($user, $sinceId = null, $untilId = null)
{
$params = array(
'since_id' => $sinceId,
'until_id' => $untilId
);
$this->uri = '/shuo/v2/statuses/user_timeline/'.$user.'?'.http_build_query($params);
$this->type = 'GET';
return $this;
}
}
... ...
<?php
/**
* @file DoubanMovie.php
* @brief 豆瓣电影API接口
* @author JonChou <ilorn.mc@gmail.com>
* @date 2012-12-05
*/
class DoubanMovie extends DoubanBase {
/**
* @brief 构造函数,初始设置clientId
*
* @param string $clientId
*
* @return void
*/
public function __construct($clientId)
{
$this->clientId = $clientId;
}
/**
* @brief 获取电影信息
*
* @param string $id
*
* @return object
*/
public function get($id)
{
$this->uri = '/v2/movie/'.$id;
$this->type = 'GET';
return $this;
}
/**
* @brief 根据imdb号获取电影信息
*
* @param string $name
*
* @return object
*/
public function imdb($name)
{
$this->uri = '/v2/movie/imdb/'.$name;
$this->type = 'GET';
return $this;
}
public function search($q, $tag, $start = 0, $count = 20)
{
$params = array(
'q' => $q,
'tag' => $tag,
'start' => $start,
'count' => $count
);
$this->uri = '/v2/movie/search?'.http_build_query($params);
$this->type = 'GET';
return $this;
}
public function movieTags($id)
{
$this->uri = '/v2/movie/'.$id.'/tags';
$this->type = 'GET';
return $this;
}
public function userTags($id)
{
$this->uri = '/v2/movie/user_tags/'.$id;
$this->type = 'GET';
return $this;
}
public function addReview()
{
$this->uri = '/v2/movie/reviews';
$this->type = 'POST';
return $this;
}
public function editReview($id)
{
$this->uri = '/v2/movie/review/'.$id;
$this->type = 'PUT';
return $this;
}
public function deleteReview($id)
{
$this->uri = '/v2/movie/review/'.$id;
$this->type = 'DELETE';
return $this;
}
}
... ...
<?php
/**
* @file DoubanMusic.php
* @brief 豆瓣音乐API接口
* @author JonChou <ilorn.mc@gmail.com>
* @date 2012-12-05
*/
class DoubanMusic extends DoubanBase {
/**
* @brief 构造函数,初始设置clientId
*
* @param string $clientId
*
* @return void
*/
public function __construct($clientId)
{
$this->clientId = $clientId;
}
/**
* @brief 获取音乐信息
*
* @param $id
*
* @return object
*/
public function get($id)
{
$this->uri = '/v2/music/'.$id;
$this->type = 'GET';
return $this;
}
/**
* @brief 搜索音乐
*
* @param $q
* @param $tag
* @param $start
* @param $count
*
* @return object
*/
public function search($q, $tag = null, $start = 0, $count = 20)
{
$params = array(
'q' => $q,
'tag' => $tag,
'start' => $start,
'count' => $count
);
$this->uri = '/v2/music/search?'.http_build_query($params);
$this->type = 'GET';
return $this;
}
/**
* @brief 某个音乐中标记最多的标签
*
* @param $id
*
* @return object
*/
public function musicTags($id)
{
$this->uri = '/v2/music/'.$id.'/tags';
$this->type = 'GET';
return $this;
}
public function addReview()
{
$this->uri = '/v2/music/reviews';
$this->type = 'POST';
return $this;
}
public function editReview($id)
{
$this->uri = '/v2/music/review/'.$id;
$this->type = 'PUT';
return $this;
}
public function deleteReview($id)
{
$this->uri = '/v2/music/review/'.$id;
$this->type = 'DELETE';
return $this;
}
/**
* @brief 用户对音乐的所有标签
*
* @param $id
*
* @return object
*/
public function userTags($id)
{
$this->uri = '/v2/music/user_tags/'.$id;
$this->type = 'GET';
return $this;
}
}
... ...
<?php
/**
* @file DoubanNote.php
* @brief 豆瓣日记API接口
* @author JonChou <ilorn.mc@gmail.com>
* @date 2012-12-05
*/
class DoubanNote extends DoubanBase {
/**
* @brief 构造函数,初始设置clientId
*
* @param string $clientId
*
* @return void
*/
public function __construct($clientId)
{
$this->clientId = $clientId;
}
/**
* @brief 获取一条日记
*
* @param $id
* @param $format
*
* @return object
*/
public function getNote($id, $format = 'text')
{
$this->uri = '/v2/note/'.$id.'?format='.$format;
$this->type = 'GET';
return $this;
}
public function addNote()
{
$this->uri = '/v2/notes';
$this->type = 'POST';
return $this;
}
public function editNote($id)
{
$this->uri = '/v2/note/'.$id;
$this->type = 'PUT';
return $this;
}
public function deleteNote($id)
{
$this->uri = '/v2/note/'.$id;
$this->type = 'DELETE';
return $this;
}
public function like($id)
{
$this->uri = '/v2/note/'.$id.'/like';
$this->type = 'POST';
return $this;
}
public function dislike($id)
{
$this->uri = '/v2/note/'.$id.'/like';
$this->type = 'DELETE';
return $this;
}
public function image($id)
{
$this->uri = '/v2/note/'.$id;
$this->type = 'POST';
return $this;
}
public function getCommentsList($id)
{
$this->uri = '/v2/note/'.$id.'/comments';
$this->type = 'GET';
return $this;
}
public function reply($id)
{
$this->uri = '/v2/note/'.$id.'/comments';
$this->type = 'POST';
return $this;
}
public function getComment($noteId, $commentId)
{
$this->uri = '/v2/note/'.$noteId.'/comment/'.$commentId;
$this->type = 'GET';
return $this;
}
public function deleteComment($noteId, $commentId)
{
$this->uri = '/v2/note/'.$noteId.'/comment/'.$id;
$this->type = 'DELETE';
return $this;
}
}
... ...
<?php
/**
* @file DoubanOnline.php
* @brief 豆瓣线上活动API接口
* @author JonChou <ilorn.mc@gmail.com>
* @date 2012-12-05
*/
class DoubanOnline extends DoubanBase {
/**
* @brief 构造函数,初始设置clientId
*
* @param string $clientId
*
* @return void
*/
public function __construct($clientId)
{
$this->client = $clientId;
}
public function getOnline($id)
{
$this->uri = '/v2/online/'.$id;
$this->type = 'GET';
return $this;
}
public function participants($id)
{
$this->uri = '/v2/online/'.$id.'/participants';
$this->type = 'GET';
return $this;
}
public function getDiscussionsList($id)
{
$this->uri = '/v2/online/'.$id.'/discussions';
$this->type = 'GET';
return $this;
}
public function getOnlinesList($cate)
{
$this->uri = '/v2/onlines?cate='.$cate;
$this->type = 'GET';
return $this;
}
public function addOnline()
{
$this->uri = '/v2/onlines';
$this->type = 'POST';
return $this;
}
public function editOnline($id)
{
$this->uri = '/v2/onlines/'.$id;
$this->type = 'PUT';
return $this;
}
public function deleteOnline($id)
{
$this->uri = '/v2/onlines/'.$id;
$this->type = 'DELETE';
return $this;
}
public function join($id)
{
$this->uri = '/v2/online/'.$id.'/participants';
$this->type = 'POST';
return $this;
}
public function quit($id)
{
$this->uri = '/v2/online/'.$id.'/participants';
$this->type = 'DELETE';
return $this;
}
public function like($id)
{
$this->uri = '/v2/online/'.$id.'/like';
$this->type = 'POST';
return $this;
}
public function dislike($id)
{
$this->uri = '/v2/online/'.$id.'/like';
$this->type = 'DELETE';
return $this;
}
public function getPhoto($id)
{
$this->uri = '/v2/online/'.$id.'/photos';
$this->type = 'GET';
return $this;
}
public function addPhoto($id)
{
$this->uri = '/v2/online/'.$id.'/photos';
$this->type = 'POST';
return $this;
}
public function replyDiscussion($id)
{
$this->uri = '/v2/online/'.$id.'/discussions';
$this->type = 'POST';
return $this;
}
public function userParticipated($id, $excludeExpired = true)
{
$this->uri = '/v2/online/user_participated/'.$id.'?exclude_expired='.$excludeExpired;
$this->type = 'GET';
return $this;
}
public function userCreated($id)
{
$this->uri = '/v2/online/user_created/'.$id;
$this->type = 'GET';
return $this;
}
}
... ...
<?php
/**
* @file DoubanPhoto.php
* @brief 豆瓣相册API接口
* @author JonChou <ilorn.mc@gmail.com>
* @date 2012-12-05
*/
class DoubanPhoto extends DoubanBase {
/**
* @brief 构造函数,初始设置clientId和accessToken
*
* @param string $clientId
*
* @return void
*/
public function __construct($clientId)
{
$this->clientId = $clientId;
}
public function getAlbum($id)
{
$this->uri = '/v2/album/'.$id;
$this->type = 'GET';
return $this;
}
public function addAlbum()
{
$this->uri = '/v2/albums';
$this->type = 'POST';
return $this;
}
public function editAlbum($id)
{
$this->uri = '/v2/album/'.$id;
$this->type = 'PUT';
return $this;
}
public function deleteAlbum($id)
{
$this->uri = '/v2/album/'.$id;
$this->type = 'DELETE';
return $this;
}
public function getPhotosList($id)
{
$this->uri = '/v2/album/'.$id.'/photos';
$this->type = 'GET';
return $this;
}
public function getPhoto($id)
{
$this->uri = '/v2/photo/'.$id;
$this->type = 'GET';
return $this;
}
public function likeAlbum($id)
{
$this->uri = '/v2/album/'.$id.'/like';
$this->type = 'POST';
return $this;
}
public function dislikeAlbum($id)
{
$this->uri = '/v2/album/'.$id.'/like';
$this->type = 'DELETE';
return $this;
}
public function getUserAlbumList($id)
{
$this->uri = '/v2/album/user_created/'.$id;
$this->type = 'GET';
return $this;
}
public function userLiked($id)
{
$this->uri = '/v2/album/user_liked/'.$id;
$this->type = 'GET';
return $this;
}
public function addPhoto($id)
{
$this->uri = '/v2/album/'.$id;
$this->type = 'POST';
return $this;
}
public function editPhoto($id)
{
$this->uri = '/v2/album/'.$id;
$this->type = 'PUT';
return $this;
}
public function deletePhoto($id)
{
$this->uri = '/v2/album/'.$id;
$this->type = 'DELETE';
return $this;
}
public function likePhoto($id)
{
$this->uri = '/v2/photo/'.$id.'/like';
$this->type = 'POST';
return $this;
}
public function dislikePhoto($id)
{
$this->uri = '/v2/photo/'.$id.'/like';
$this->type = 'DELETE';
return $this;
}
}
... ...
<?php
/**
* @file DoubanUser.php
* @brief 豆瓣用户API
* @author JonChou <ilorn.mc@gmail.com>
* @date 2012-12-03
*/
class DoubanUser extends DoubanBase {
/**
* @brief 构造函数,初始设置clientId
*
* @param string $clientId
*
* @return void
*/
public function __construct($clientId)
{
$this->clientId = $clientId;
}
/**
* @brief 获取当前授权用户信息
*
* @return object
*/
public function me()
{
$this->uri = '/v2/user/~me';
$this->type = 'GET';
return $this;
}
/**
* @brief 获取指定ID用户信息
*
* @param string $id
*
* @return object
*/
public function get($id)
{
$this->uri = '/v2/user/'.$id;
$this->type = 'GET';
return $this;
}
/**
* @brief 搜索用户
*
* @param string $q
* @param int $start
* @param int $count
*
* @return object
*/
public function search($q, $start = null, $count = null)
{
$params = array(
'q' => $q,
'start' => $start,
'count' => $count
);
$this->uri = '/v2/user?'.http_build_query($params);
$this->type = 'GET';
return $this;
}
}
... ...
<?php
namespace Plugin\Partner\renren;
use Plugin\Partner\Factory;
define('RENREN_CLASS_PATH', dirname (__FILE__) . '/class/');
require RENREN_CLASS_PATH . 'RennClientBase.class.php';
/**
* 人人网的调用接口
*
* @name Call
* @package lib/partner/renren
* @copyright yoho.inc
* @version 5.0 (2015-12-31 10:54:54)
* @author xiaowei <xiaowei.gong@yoho.cn>
*/
class Call extends Factory
{
/*人人网对象*/
protected $renn;
/**
* 初始化
*/
protected function init()
{
$this->renn = new \RennClientBase($this->apiConfig['appId'], $this->apiConfig['appKey']);
}
/**
* 获取授权URL
*
* @return string
*/
public function getAuthorizeUrl()
{
return $this->renn->getAuthorizeURL($this->apiConfig['callback'], 'code', null, null, true, $this->apiConfig['scope']);
}
/**
* 获取授权的TOKEN
*
* @return array
*/
public function getAccessToken()
{
$token = array();
if (isset($_REQUEST['code']))
{
$keys = array();
$keys['code'] = $_REQUEST['code'];
$keys['redirect_uri'] = $this->apiConfig['callback'];
try
{
$token = $this->renn->getTokenFromTokenEndpoint('code', $keys, TokenType::Bearer);
// 返回数组格式的信息
$token = $this->renn->getTokens();
}
catch (Exception $e)
{
// do nothing
}
}
return $token;
}
/**
* 获取当前用户的基本资料
*
* @see http://open.renren.com/wiki/API/v2/user/get
* @param object $token 授权成功的TOKEN, 默认为NULL
* @return array
*/
public function getUserInfo($token)
{
$userInfo = array();
if (!empty($token))
{
if (is_array($token))
{
$token = new AccessToken(isset($token['type']) ? $token['type'] : TokenType::Bearer, $token['accessToken'], isset($token['refreshToken']) ? $token['refreshToken'] : null, isset($token['macKey']) ? $token['macKey'] : null, isset($token['macAlgorithm']) ? $token['macAlgorithm'] : null);
}
// 获得保存的token
$this->renn->authWithToken($token);
// 获得当前登录用户
if (isset($token->accessToken))
{
$parts = explode('-', $token->accessToken);
if (isset($parts[1]))
{
$params = array('userId' => $parts[1]);
try
{
$userInfo = $this->renn->execute('/v2/user/login/get', 'GET', $params, array(), array());
}
catch (Exception $e)
{
// do nothing
}
}
}
}
return $userInfo;
}
/**
* 获取当前用户的偶像(关注)列表
*
* @see http://open.renren.com/wiki/V2/friend/list
* @param object $token 访问令牌
* @param array $params 参数列表
* Long $userId 用户ID。该字段默认为当前用户
* Integer $pageSize 页面大小。默认大小500。
* Integer $pageNumber 页码。取值大于零,默认值为1
* @return array
*/
public function getFriends($token, $params)
{
$friends = array();
if (!empty($token))
{
if (is_array($token))
{
$token = new AccessToken(isset($token['type']) ? $token['type'] : TokenType::Bearer, $token['accessToken'], isset($token['refreshToken']) ? $token['refreshToken'] : null, isset($token['macKey']) ? $token['macKey'] : null, isset($token['macAlgorithm']) ? $token['macAlgorithm'] : null);
}
// 获得保存的token
$this->renn->authWithToken($token);
// 获取当前登录用户的好友列表
if (!isset($params['userId']) && isset($token->accessToken))
{
$parts = explode('-', $token->accessToken);
if (isset($parts[1]))
{
$params['userId'] = $parts[1];
}
}
try
{
$friends = $this->renn->execute('/v2/user/friend/list', 'GET', $params, array(), array());
}
catch (Exception $e)
{
// do nothing
}
}
return $friends;
}
/**
* 同步分享
*
* 发送自定义新鲜事。新鲜事会发布用户的个人动态信息到用户人人网主页,同时会出现在好友的新鲜事中
*
* @see http://open.renren.com/wiki/API/v2/feed/put
* @param object $token 访问令牌
* @param String $image 新鲜事图片地址
* @param String $content 新鲜事主体内容 注意:最多200个字符。
* @param String $link 新鲜事标题和图片指向的链接
* @return Long 发布新鲜事的ID
*/
public function syncShare($token, $content, $image, $link)
{
$result = false;
if (!empty($token))
{
if (is_array($token))
{
$token = new AccessToken(isset($token['type']) ? $token['type'] : TokenType::Bearer, $token['accessToken'], isset($token['refreshToken']) ? $token['refreshToken'] : null, isset($token['macKey']) ? $token['macKey'] : null, isset($token['macAlgorithm']) ? $token['macAlgorithm'] : null);
}
// 获得保存的token
$this->renn->authWithToken($token);
$params = array('title' => '来自YOHO的分享', 'message' => $content, 'actionTargetUrl' => $link,
'imageUrl' => $image, 'description' => $content, 'targetUrl' => $link,);
try
{
$result = $this->renn->execute('/v2/feed/put', 'POST', $params, array(), array());
}
catch (Exception $e)
{
// do nothing
}
}
return $result;
}
/**
* 返回token的所有信息(包括user)
*
* 备注:所有此方法必须先调用 getAccessToken()
*
* @return array
*/
public function getTokens()
{
return $this->renn->getTokens();
}
}
\ No newline at end of file
... ...
<?php
defined('DOMAIN') || define('DOMAIN', $_SERVER['HTTP_HOST']);
return array(
'appId' => '783130c654c94a77ace97054ae266019',
'appKey' => '05e430de8c1e40d3a1f39ca8d3f8252c',
'callback' => DOMAIN . '/passport/login/renrenback',
'scope' => 'publish_feed,photo_upload',
);
\ No newline at end of file
... ...
<?php
include_once ('RennClientBase.class.php');
include_once ('service/RennServiceBase.php');
include_once ('service/AlbumService.php');
include_once ('service/BlogService.php');
include_once ('service/ShareService.php');
include_once ('service/UbbService.php');
include_once ('service/NotificationService.php');
include_once ('service/FeedService.php');
include_once ('service/InvitationService.php');
include_once ('service/ProfileService.php');
include_once ('service/AppService.php');
include_once ('service/StatusService.php');
include_once ('service/LikeService.php');
include_once ('service/PhotoService.php');
include_once ('service/CommentService.php');
include_once ('service/UserService.php');
include_once ('service/FriendService.php');
class RennClient extends RennClientBase {
private $albumService;
private $blogService;
private $shareService;
private $ubbService;
private $notificationService;
private $feedService;
private $invitationService;
private $profileService;
private $appService;
private $statusService;
private $likeService;
private $photoService;
private $commentService;
private $userService;
private $friendService;
function getAlbumService() {
if (empty ($this -> albumService )) {
$this->albumService = new AlbumService ( $this, $this->accessToken );
}
return $this->albumService;
}
function getBlogService() {
if (empty ($this -> blogService )) {
$this->blogService = new BlogService ( $this, $this->accessToken );
}
return $this->blogService;
}
function getShareService() {
if (empty ($this -> shareService )) {
$this->shareService = new ShareService ( $this, $this->accessToken );
}
return $this->shareService;
}
function getUbbService() {
if (empty ($this -> ubbService )) {
$this->ubbService = new UbbService ( $this, $this->accessToken );
}
return $this->ubbService;
}
function getNotificationService() {
if (empty ($this -> notificationService )) {
$this->notificationService = new NotificationService ( $this, $this->accessToken );
}
return $this->notificationService;
}
function getFeedService() {
if (empty ($this -> feedService )) {
$this->feedService = new FeedService ( $this, $this->accessToken );
}
return $this->feedService;
}
function getInvitationService() {
if (empty ($this -> invitationService )) {
$this->invitationService = new InvitationService ( $this, $this->accessToken );
}
return $this->invitationService;
}
function getProfileService() {
if (empty ($this -> profileService )) {
$this->profileService = new ProfileService ( $this, $this->accessToken );
}
return $this->profileService;
}
function getAppService() {
if (empty ($this -> appService )) {
$this->appService = new AppService ( $this, $this->accessToken );
}
return $this->appService;
}
function getStatusService() {
if (empty ($this -> statusService )) {
$this->statusService = new StatusService ( $this, $this->accessToken );
}
return $this->statusService;
}
function getLikeService() {
if (empty ($this -> likeService )) {
$this->likeService = new LikeService ( $this, $this->accessToken );
}
return $this->likeService;
}
function getPhotoService() {
if (empty ($this -> photoService )) {
$this->photoService = new PhotoService ( $this, $this->accessToken );
}
return $this->photoService;
}
function getCommentService() {
if (empty ($this -> commentService )) {
$this->commentService = new CommentService ( $this, $this->accessToken );
}
return $this->commentService;
}
function getUserService() {
if (empty ($this -> userService )) {
$this->userService = new UserService ( $this, $this->accessToken );
}
return $this->userService;
}
function getFriendService() {
if (empty ($this -> friendService )) {
$this->friendService = new FriendService ( $this, $this->accessToken );
}
return $this->friendService;
}
}
?>
... ...
<?php
if (!function_exists('curl_init')) {
throw new Exception('Renn PHP SDK needs the CURL PHP extension.');
}
if (!function_exists('json_decode')) {
throw new Exception('Renn PHP SDK needs the JSON PHP extension.');
}
class RennClientBase {
/**
* token终端
*/
const TOKEN_ENDPOINT = 'http://graph.renren.com/oauth/token';
/**
* 授权终端
*/
const AUTHORIZATION_ENDPOINT = 'http://graph.renren.com/oauth/grant';
/**
* API host
*/
const API_HOST = 'api.renren.com';
/**
* Set the useragnet.
*/
const USERAGENT = 'Renn API2.0 SDK PHP v0.1';
/**
* Set timeout default.
*/
const TIMEOUT = 60;
/**
* Set connect timeout.
*/
const CONNECTTIMEOUT = 30;
/**
* Default options for curl.
*/
public static $CURL_OPTS = array (
CURLOPT_CONNECTTIMEOUT => self::CONNECTTIMEOUT,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => self::TIMEOUT,
CURLOPT_USERAGENT => self::USERAGENT
);
/**
* 应用id
*/
protected $clientId;
/**
* 应用密钥
*/
protected $clientSecret;
/**
* token
*/
protected $accessToken;
/**
* 签名方法的工厂
*/
protected $signatureMethodFactory;
/**
* token存储
*/
protected $tokenStore;
/**
* tokens
*/
protected $tokens;
/**
* print the debug info
*/
public $debug = FALSE;
/**
* 构造函数
*/
function __construct($clientId, $clientSecret) {
$this->clientId = $clientId;
$this->clientSecret = $clientSecret;
$this->signatureMethodFactory = new OAuth2SignatureMethodFactory ();
$this->tokenStore = new CookieTokenStore ();
}
/**
* 用code来授权:通过code来获得token
*
* @param string $code
*/
public function authWithAuthorizationCode($code, $redirectUri) {
$keys = array ();
$keys ['code'] = $code;
$keys ['redirect_uri'] = $redirectUri;
try {
// 根据code来获得token
$token = $this->getTokenFromTokenEndpoint ( 'code', $keys );
} catch ( RennException $e ) {
throw new InvalideAuthorizationException ( "Authorization failed with Authorization Code. " . $e->getMessage () );
}
}
/**
* 用已有的token来授权
*
* @param string $token
*/
public function authWithToken($token) {
$this->accessToken = $token;
}
/**
* Client Credentials来授权
*/
public function authWithClientCredentials() {
$keys = array ();
$keys ['client_id'] = $this->clientId;
$keys ['client_secret'] = $this->clientSecret;
try {
$token = $this->getTokenFromTokenEndpoint ( 'client_credentials', $keys );
} catch ( RennException $e ) {
throw new InvalideAuthorizationException ( "Authorization failed with Client Credentials. " . $e->getMessage () );
}
}
/**
* 用已用户的用户名和密码授权
*/
public function authWithResourceOwnerPassword($username, $password) {
$keys = array ();
$keys ['username'] = $username;
$keys ['password'] = $password;
try {
$token = $this->getTokenFromTokenEndpoint ( 'password', $keys );
} catch ( RennException $e ) {
throw new InvalideAuthorizationException ( "Authorization failed with Resource Owner Password. " . $e->getMessage () );
}
}
/**
* 用存储的token来授权
*/
public function authWithStoredToken() {
$token = $this->getTokenFromTokenStore ();
if (! isset ( $token )) {
throw new InvalideAuthorizationException ( "Authorization failed with Stored Token. token: null" );
}
}
/**
* ********************************** 获得token ****************************************
*/
/**
* authorize接口
*
* @param string $redirectUri
* 授权后的回调地址,站外应用需与回调地址一致,站内应用需要填写canvas page的地址
* @param string $responseType
* 支持的值包括 code 和token 默认值为code
* @param string $state
* 用于保持请求和回调的状态。在回调时,会在Query Parameter中回传该参数
* @param string $display
* 授权页面类型 可选范围:
* @param bool $forcelogin
* 是否强制用户重新登录,true:是,false:否。默认false。
* @param string $language
* 授权页语言,缺省为中文简体版,en为英文版。
* @return array
*/
public function getAuthorizeURL($redirectUri, $responseType = 'code', $state = null, $display = null, $forcelogin = null, $scope = null) {
$params = array ();
$params ['client_id'] = $this->clientId;
$params ['redirect_uri'] = $redirectUri;
$params ['response_type'] = $responseType;
$params ['state'] = $state;
$params ['display'] = $display;
$params ['x_renew'] = $forcelogin;
$params ['scope'] = $scope;
return self::AUTHORIZATION_ENDPOINT . "?" . http_build_query ( $params );
}
/**
* 获取完整的token信息
*
* @return array
*/
public function getTokens() {
return $this->tokens;
}
/**
* 从token endpoint获得token
*
* @param string $grantType
* 请求的类型,可以为:code, password, token
* @param array $keys
* 其他参数:
* - 当$grant_type为code时: array('code'=>..., 'redirect_uri'=>...)
* - 当$grant_type为password时: array('username'=>..., 'password'=>...)
* - 当$grant_type为token时: array('refresh_token'=>...)
* @param
* string token_type token的类型,可以为:bearer,mac
* @return array
*/
public function getTokenFromTokenEndpoint($grantType, $keys, $tokenType = TokenType::MAC) {
$params = array ();
$params ['client_id'] = $this->clientId;
$params ['client_secret'] = $this->clientSecret;
$params ['token_type'] = $tokenType;
if ($grantType === 'token') {
$params ['grant_type'] = 'refresh_token';
$params ['refresh_token'] = $keys ['refresh_token'];
} elseif ($grantType === 'code') {
$params ['grant_type'] = 'authorization_code';
$params ['code'] = $keys ['code'];
$params ['redirect_uri'] = $keys ['redirect_uri'];
} elseif ($grantType === 'client_credentials') {
$params ['grant_type'] = 'client_credentials';
} elseif ($grantType === 'password') {
$params ['grant_type'] = 'password';
$params ['username'] = $keys ['username'];
$params ['password'] = $keys ['password'];
} else {
throw new ClientException ( "wrong auth type" );
}
// 获得token
$response = $this->http ( self::TOKEN_ENDPOINT, 'POST', http_build_query ( $params, null, '&' ) );
$token = json_decode ( $response, true );
$tokenObj = null;
if (is_array ( $token ) && ! isset ( $token ['error'] )) {
$tokenType = null;
$accessToken = $token ['access_token'];
$refreshToken = null;
$macAlgorithm = null;
$macKey = null;
if (isset ( $token ['refresh_token'] )) {
$refreshToken = $token ['refresh_token'];
}
// TODO use token type
if (isset ( $token ['mac_algorithm'] ) && isset ( $token ['mac_key'] )) { // mac token
$tokenType = TokenType::MAC;
$macAlgorithm = $token ['mac_algorithm'];
$macKey = $token ['mac_key'];
} else { // bearer token
$tokenType = TokenType::Bearer;
}
$tokenObj = new AccessToken ( $tokenType, $accessToken, $refreshToken, $macKey, $macAlgorithm );
$this->accessToken = $tokenObj;
$this->tokens = $token;
} else {
throw new ClientException ( "Get access token failed. " . $token ['error'] . ": " . $token ['error_description'] );
}
// 存储token
$this->tokenStore->saveToken ( 'renren_' . $this->clientId, $tokenObj );
return $tokenObj;
}
/**
* 从token存储中获得token
*/
private function getTokenFromTokenStore() {
$token = $this->tokenStore->loadToken ( 'renren_' . $this->clientId );
$this->accessToken = $token;
return $token;
}
public function execute($path, $httpMethod, $queryParams, $bodyParams = null, $fileParams = null) {
$schema = "http";
// 组装URL
if ($this->accessToken->type == TokenType::Bearer) {
$schema = "https";
}
// path & query
$url = $schema . "://" . self::API_HOST . $path;
$pathAndQuery = $path;
if (! empty ( $queryParams )) { // 注意:在get请求的url中,有参数有'?',无参数无'?'
$query = http_build_query ( $queryParams );
if (!empty ($query)) {
$url = $url . '?' . $query;
$pathAndQuery = $path . '?' . $query;
}
}
// headers
$headers = array ();
// authorization header
if ($this->accessToken) {
$headers [] = $this->getAuthorizationHeader ( $schema, $pathAndQuery, $httpMethod );
}
// body
if (! empty ( $fileParams )) {
// body里的参数和文件参数都用multipart方式传输
$boundary = uniqid ( '------------------' );
$headers [] = "Content-Type: multipart/form-data; boundary=" . $boundary;
$body = $this->http_build_multipart_body ( $fileParams, $bodyParams, $boundary );
$response = $this->http ( $url, $httpMethod, $body, $headers );
} else {
$headers [] = 'Content-type: application/x-www-form-urlencoded';
if (isset ( $bodyParams )) {
$body = http_build_query ( $bodyParams, null, '&' );
$length = strlen ( $body );
$headers [] = 'Content-length: ' . $length;
$response = $this->http ( $url, $httpMethod, $body, $headers );
} else {
$headers [] = 'Content-length: 0';
$response = $this->http ( $url, $httpMethod, null, $headers );
}
}
// // body
// if (isset ( $fileParams )) {
// // body里的参数和文件参数都用multipart方式传输
// $headers [] = "Content-Type: multipart/form-data; boundary=" . self::$boundary;
// $body = $this->http_build_multipart_body ( $fileParams, $bodyParams );
// $response = $this->http ( $url, $httpMethod, $body, $headers );
// } else {
// if (isset ( $bodyParams )) {
// $body = http_build_query ( $bodyParams );
// $response = $this->http ( $url, $httpMethod, $body, $headers );
// } else {
// $response = $this->http ( $url, $httpMethod, null, $headers );
// }
// }
$result = json_decode ( $response, true );
if (isset ( $result ['error'] ) && $result ['error']) {
throw new ServerException ( $result ['error'] ['code'], $result ['error'] ['message'] );
}
return $result ['response'];
}
private function http_build_multipart_body($fileParams, $textParams, $boundary) {
$MPboundary = '--' . $boundary;
$endMPboundary = $MPboundary . '--';
$multipartbody = '';
foreach ( $fileParams as $fileParamName => $fileUrl ) {
$content = file_get_contents ( $fileUrl );
$array = explode ( '?', basename ( $fileUrl ) );
$filename = $array [0];
$multipartbody .= $MPboundary . "\r\n";
$multipartbody .= 'Content-Disposition: form-data; name="' . $fileParamName . '"; filename="' . $filename . '"' . "\r\n";
$multipartbody .= "Content-Type: image/unknown\r\n\r\n";
$multipartbody .= $content . "\r\n";
}
foreach ( $textParams as $param => $value ) {
$multipartbody .= $MPboundary . "\r\n";
$multipartbody .= 'Content-Disposition: form-data; name="' . $param . "\"\r\n\r\n";
$multipartbody .= $value . "\r\n";
}
$multipartbody .= $endMPboundary;
return $multipartbody;
}
// /**
// * Makes an HTTP request.
// * This method can be overridden by subclasses if
// * developers want to do fancier things or use something other than curl to
// * make the request.
// *
// * @param string $url
// * The URL to make the request to
// * @param array $postdata
// * The parameters to use for the POST body
// * @param CurlHandler $ch
// * Initialized curl handle
// *
// * @return string The response text
// */
// protected function http($url, $method, $postdata = null, $header = array()) {
// $ch = curl_init ();
// $opts = self::$CURL_OPTS;
// $opts [CURLOPT_HTTPHEADER] = $header;
// if ($method === 'POST') {
// $opts [CURLOPT_POST] = true;
// $opts [CURLOPT_POSTFIELDS] = $postdata;
// }
// $opts [CURLOPT_URL] = $url;
// curl_setopt_array ( $ch, $opts );
// $result = curl_exec ( $ch );
// curl_close ( $ch );
// return $result;
// }
/**
* Make an HTTP request
*
* @return string API results
*/
private function http($url, $method, $postfields = null, $headers = array()) {
$this->httpInfo = array ();
$ci = curl_init ();
/* Curl settings */
curl_setopt ( $ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0 );
curl_setopt ( $ci, CURLOPT_USERAGENT, self::USERAGENT );
curl_setopt ( $ci, CURLOPT_CONNECTTIMEOUT, self::CONNECTTIMEOUT );
curl_setopt ( $ci, CURLOPT_TIMEOUT, self::TIMEOUT );
curl_setopt ( $ci, CURLOPT_RETURNTRANSFER, TRUE );
curl_setopt ( $ci, CURLOPT_ENCODING, "" );
curl_setopt ( $ci, CURLOPT_SSL_VERIFYPEER, FALSE );
curl_setopt ( $ci, CURLOPT_SSL_VERIFYHOST, 2 );
curl_setopt ( $ci, CURLOPT_HEADER, FALSE );
// 方法
switch ($method) {
case 'POST' :
curl_setopt ( $ci, CURLOPT_POST, TRUE );
if (! empty ( $postfields )) {
curl_setopt ( $ci, CURLOPT_POSTFIELDS, $postfields );
$this->postdata = $postfields;
}
break;
case 'DELETE' :
curl_setopt ( $ci, CURLOPT_CUSTOMREQUEST, 'DELETE' );
if (! empty ( $postfields )) {
$url = "{$url}?{$postfields}";
}
}
curl_setopt ( $ci, CURLOPT_URL, $url );
curl_setopt ( $ci, CURLOPT_HTTPHEADER, $headers );
curl_setopt ( $ci, CURLINFO_HEADER_OUT, TRUE );
$response = curl_exec ( $ci );
$this->httpCode = curl_getinfo ( $ci, CURLINFO_HTTP_CODE );
$this->httpInfo = array_merge ( $this->httpInfo, curl_getinfo ( $ci ) );
if ($this->debug) {
echo "=====post data======\r\n";
var_dump ( $postfields );
echo "=====headers======\r\n";
print_r ( $headers );
echo '=====request info=====' . "\r\n";
print_r ( curl_getinfo ( $ci ) );
echo '=====response=====' . "\r\n";
print_r ( $response );
}
curl_close ( $ci );
return $response;
}
/**
* 根据token类型来获得认证头
*/
private function getAuthorizationHeader($schema, $pathAndQuery, $method) {
// bearer token
if ($this->accessToken->type !== TokenType::MAC) {
return "Authorization:Bearer " . $this->accessToken->accessToken;
}
// mac token
// 根据签名方法名来获得签名方法
$signMethod = $this->signatureMethodFactory->getSignatureMethod ( $this->accessToken->macAlgorithm );
if (empty ( $signMethod )) {
throw new ClientException ( "wrong mac algorithm" );
}
// 签名相关参数
$timestamp = intval ( time () / 1000 ); // 时间戳,以秒为单位,以客户端的时间为准
$nonce = $this->generateRandomString ( 8 ); // 随机码,随即字符串,由客户端生成
$ext = ""; // 其他信息,客户端自定义
$host = self::API_HOST; // 目标服务器的主机 TODO 常量
$port = $schema == "https" ? 443 : 80;
// 签名的原始字符串
$signatureBaseString = $timestamp . "\n" . $nonce . "\n" . $method . "\n" . $pathAndQuery . "\n" . $host . "\n" . $port . "\n" . $ext . "\n";
// 签名
$signature = $signMethod->buildSignature ( $signatureBaseString, $this->accessToken->macKey );
return sprintf ( "Authorization:MAC id=\"%s\",ts=\"%s\",nonce=\"%s\",mac=\"%s\"", $this->accessToken->accessToken, $timestamp, $nonce, $signature );
}
/**
* 生成随机字符串
*
* @param integer $length
*/
private function generateRandomString($length = 8) {
// 密码字符集,可任意添加你需要的字符
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$random_str = "";
for($i = 0; $i < $length; $i ++) {
// 这里提供两种字符获取方式
// 第一种是使用 substr 截取$chars中的任意一位字符;
// $random_str .= substr($chars, mt_rand(0, strlen($chars) – 1), 1);
// 第二种是取字符数组 $chars 的任意元素
$random_str .= $chars [mt_rand ( 0, strlen ( $chars ) - 1 )];
}
return $random_str;
}
/**
* 开启调试信息
*
* 开启调试信息后,SDK会将每次请求微博API所发送的POST Data、Headers以及请求信息、返回内容输出出来。
*
* @access public
* @param bool $enable
* 是否开启调试信息
* @return void
*/
function setDebug($enable) {
$this->debug = $enable;
}
}
/**
* token类型
*/
class TokenType {
const Bearer = "Bearer";
const MAC = "MAC";
}
class AccessToken {
public $type;
public $accessToken;
public $refreshToken;
public $macKey;
public $macAlgorithm;
function __construct($type, $accessToken, $refreshToken, $macKey, $macAlgorithm) {
$this->type = $type;
$this->accessToken = $accessToken;
$this->refreshToken = $refreshToken;
$this->macKey = $macKey;
$this->macAlgorithm = $macAlgorithm;
}
}
/**
* oauth2异常
*/
class RennException extends Exception {
// pass
}
/**
* *************************** 客户端的异常 *************************************
*/
/**
* 客户端的异常
*/
class ClientException extends RennException {
// pass
}
class InvalideAuthorizationException extends ClientException {
// pass
}
class UnauthorizedException extends ClientException {
// pass
}
/**
* *************************** 服务端的异常 *************************************
*/
/**
* 服务端的异常
*/
class ServerException extends RennException {
protected $errorCode;
/**
*
* @param unknown $code
* code和message使用父类的属性
* @param unknown $message
* code和message使用父类的属性
* @param string $previous
*/
function __construct($code, $message, $previous = null) {
parent::__construct ( $message, null, $previous );
$this->errorCode = $code;
}
function getErrorCode() {
return $this->errorCode;
}
}
/**
* http error code is 400.
* 请求参数错误,参数使业务逻辑无法正常运行下去。
*/
class InvalidRequestException extends ServerException {
public function __construct($code, $message, $previous = null) {
parent::__construct ( $code, $message, $previous );
}
}
/**
* http error code is 401.
* 认证信息错误,token错误,签名错误等。
*/
class InvalidAuthorizationException extends ServerException {
public function __construct($code, $message, $previous = null) {
parent::__construct ( $code, $message, $previous );
}
}
/**
* http error code is 403 认证通过,但是也不允许其访问。例如超配额
*/
class ForbiddenException extends ServerException {
public function __construct($code, $message, $previous = null) {
parent::__construct ( $code, $message, $previous );
}
}
/**
* http error code is 500 内部错误
*/
class InternalErrorException extends ServerException {
public function __construct($code, $message, $previous = null) {
parent::__construct ( $code, $message, $previous );
}
}
/**
* oauth签名方法的工厂
*/
class OAuth2SignatureMethodFactory {
/* 签名方法的数组 */
private $signature_methods;
function __construct() {
$this->signature_methods = array ();
// 注册HMAC_SHA1签名方法
$signatureMethod_HMAC_SHA1 = new OAuth2SignatureMethod_HMAC_SHA1 ();
$this->signature_methods [$signatureMethod_HMAC_SHA1->getName ()] = $signatureMethod_HMAC_SHA1;
}
/**
* 根据方法名来获得签名方法
*
* @param string $methodName
* @return OAuth2SignatureMethod
*/
function getSignatureMethod($methodName) {
return $this->signature_methods [$methodName];
}
}
/**
* oauth签名方法
* A class for implementing a Signature Method
* See section 9 ("Signing Requests") in the spec
*/
abstract class OAuth2SignatureMethod {
/**
* 获得签名方法名
* Needs to return the name of the Signature Method (ie HMAC-SHA1)
*
* @return string
*/
abstract public function getName();
/**
* 生成 签名
* Build up the signature
* NOTE: The output of this function MUST NOT be urlencoded.
* the encoding is handled in OAuthRequest when the final
* request is serialized
*
* @param string $signatureBaseString
* @param string $signatureSecret
* @return string
*/
abstract public function buildSignature($signatureBaseString, $signatureSecret);
/**
* 检验签名
* Verifies that a given signature is correct
*
* @param string $signatureBaseString
* @param string $signatureSecret
* @param string $signature
* @return bool
*/
public function checkSignature($signatureBaseString, $signatureSecret, $signature) {
$built = $this->buildSignature ( $signatureBaseString, $signatureSecret );
return $built == $signature;
}
}
/**
* 基于HMAC_SHA1算法的签名方法
* The HMAC-SHA1 signature method uses the HMAC-SHA1 signature algorithm as defined in [RFC2104]
* where the Signature Base String is the text and the key is the concatenated values (each first
* encoded per Parameter Encoding) of the Consumer Secret and Token Secret, separated by an '&'
* character (ASCII code 38) even if empty.
* - Chapter 9.2 ("HMAC-SHA1")
*/
class OAuth2SignatureMethod_HMAC_SHA1 extends OAuth2SignatureMethod {
/**
* 获得签名方法名
*
* @see OAuthSignatureMethod::get_name()
*/
function getName() {
return "hmac-sha-1";
}
/**
* 生成 签名
*
* @see OAuthSignatureMethod::build_signature()
*/
public function buildSignature($signatureBaseString, $signatureSecret) {
return base64_encode ( hash_hmac ( 'sha1', $signatureBaseString, $signatureSecret, true ) );
}
}
/**
* token存储
*/
interface TokenStore {
/**
* 加载token
*
* @param string $key
* @return array 成功返回array('access_token'=>'value', 'refresh_token'=>'value'); 失败返回false
*/
public function loadToken($key);
/**
* 保存token
*
* @param string $key
* @param array $token
*/
public function saveToken($key, $token);
}
/**
* 基于cookie的token存储
*/
class CookieTokenStore implements TokenStore {
/**
* 加载token
*
* @param string $key
* @return array 成功返回array('access_token'=>'value', 'refresh_token'=>'value'); 失败返回false
*/
public function loadToken($key) {
if (isset ( $_COOKIE [$key] ) && $cookie = $_COOKIE [$key]) {
parse_str ( $cookie, $token );
return new AccessToken ( $token ['type'], $token ['accessToken'], isset ( $token ['refreshToken'] ) ? $token ['refreshToken'] : null, isset ( $token ['macKey'] ) ? $token ['macKey'] : null, isset ( $token ['macAlgorithm'] ) ? $token ['macAlgorithm'] : null );
} else {
return null;
}
}
/**
* 保存token
*
* @param string $key
* @param array $token
*/
public function saveToken($key, $token) {
// echo $key;
setcookie ( $key, http_build_query ( $token ) );
}
}
?>
... ...
<?php
class AlbumService extends RennServiceBase {
/**
* 以分页的方式获取某个用户的相册列表
* <br />对应API:{$link http://dev.renren.com/API/v2/album/list }
* @param Long $ownerId 相册所有者的ID
* @param Integer $pageSize 页面大小。取值范围1-100,默认大小20
* @param Integer $pageNumber 页码。取值大于零,默认值为1
* @return Album 相册
*/
function listAlbum($ownerId, $pageSize, $pageNumber) {
$params = array();
$bodyParams = array();
$fileParams = array();
if (isset($ownerId)) {
$params ['ownerId'] = $ownerId;
}
if (isset($pageSize)) {
$params ['pageSize'] = $pageSize;
}
if (isset($pageNumber)) {
$params ['pageNumber'] = $pageNumber;
}
return $this->client->execute('/v2/album/list', 'GET', $params, $bodyParams, $fileParams);
}
/**
* 获取某个用户的某个相册
* <br />对应API:{$link http://dev.renren.com/API/v2/album/get }
* @param Long $albumId 相册的ID
* @param Long $ownerId 相册所有者的ID
* @return Album 相册
*/
function getAlbum($albumId, $ownerId) {
$params = array();
$bodyParams = array();
$fileParams = array();
if (isset($albumId)) {
$params ['albumId'] = $albumId;
}
if (isset($ownerId)) {
$params ['ownerId'] = $ownerId;
}
return $this->client->execute('/v2/album/get', 'GET', $params, $bodyParams, $fileParams);
}
/**
* 创建一个相册
* <br />对应API:{$link http://dev.renren.com/API/v2/album/put }
* @param String $location 相册拍摄的地点。不能超过60个字符。
* @param String $description 相册的描述。不能超过200个字符。
* @param String $name 相册的名字。不能超过30个字符
* @param AccessControl $accessControl 相册的访问控制
* @param String $password 相册的访问密码,1-16个字符
* @return Album 相册
*/
function putAlbum($location, $description, $name, $accessControl, $password) {
$params = array();
$bodyParams = array();
$fileParams = array();
if (isset($location)) {
$params ['location'] = $location;
}
if (isset($description)) {
$params ['description'] = $description;
}
if (isset($name)) {
$params ['name'] = $name;
}
if (isset($accessControl)) {
$params ['accessControl'] = $accessControl;
}
if (isset($password)) {
$params ['password'] = $password;
}
return $this->client->execute('/v2/album/put', 'POST', $params, $bodyParams, $fileParams);
}
}
?>
... ...
<?php
class AppService extends RennServiceBase {
/**
* 获取某个应用的信息,部分信息取自缓存,不能立即生效
* <br />对应API:{$link http://dev.renren.com/API/v2/app/get }
* @return App App
*/
function getApp() {
$params = array();
$bodyParams = array();
$fileParams = array();
return $this->client->execute('/v2/app/get', 'GET', $params, $bodyParams, $fileParams);
}
}
?>
... ...
<?php
class BlogService extends RennServiceBase {
/**
* 以分页的方式获取某个用户的日志列表
* <br />对应API:{$link http://dev.renren.com/API/v2/blog/list }
* @param Long $ownerId 日志所有者的ID
* @param Integer $pageSize 页面大小。取值范围1-20,默认大小10
* @param Integer $pageNumber 页码。取值大于零,默认值为1
* @return Blog 日志
*/
function listBlog($ownerId, $pageSize, $pageNumber) {
$params = array();
$bodyParams = array();
$fileParams = array();
if (isset($ownerId)) {
$params ['ownerId'] = $ownerId;
}
if (isset($pageSize)) {
$params ['pageSize'] = $pageSize;
}
if (isset($pageNumber)) {
$params ['pageNumber'] = $pageNumber;
}
return $this->client->execute('/v2/blog/list', 'GET', $params, $bodyParams, $fileParams);
}
/**
* 创建一篇日志
* <br />对应API:{$link http://dev.renren.com/API/v2/blog/put }
* @param String $title 日志的标题
* @param AccessControl $accessControl 日志的访问控制
* @param String $password 日志的访问密码,1-16个字符
* @param $paramter.simpleType2 $content 日志的内容
* @return Blog 日志
*/
function putBlog($title, $accessControl, $password, $content) {
$params = array();
$bodyParams = array();
$fileParams = array();
if (isset($title)) {
$params ['title'] = $title;
}
if (isset($accessControl)) {
$params ['accessControl'] = $accessControl;
}
if (isset($password)) {
$params ['password'] = $password;
}
if (isset($content)) {
$bodyParams ['content'] = $content;
}
return $this->client->execute('/v2/blog/put', 'POST', $params, $bodyParams, $fileParams);
}
/**
* 获取某个用户的某篇日志
* <br />对应API:{$link http://dev.renren.com/API/v2/blog/get }
* @param Long $ownerId 日志所有者的ID
* @param Long $blogId 日志的ID
* @param String $password 日志访问密码
* @return Blog 日志
*/
function getBlog($ownerId, $blogId, $password) {
$params = array();
$bodyParams = array();
$fileParams = array();
if (isset($ownerId)) {
$params ['ownerId'] = $ownerId;
}
if (isset($blogId)) {
$params ['blogId'] = $blogId;
}
if (isset($password)) {
$params ['password'] = $password;
}
return $this->client->execute('/v2/blog/get', 'GET', $params, $bodyParams, $fileParams);
}
}
?>
... ...
<?php
class CommentService extends RennServiceBase {
/**
* 对某个对象(日志、状态、照片、相册、分享等)进行评论
* <br />对应API:{$link http://dev.renren.com/API/v2/comment/put }
* @param String $content 评论内容。状态评论字数限制为240个字符,其余字数限制为500个字符。
* @param Long $targetUserId 评论回复目标用户的ID,若为0或不传此参数为:添加一条评论
* @param CommentType $commentType 评论的类型
* @param Long $entryOwnerId 评论对象所有者的ID
* @param Long $entryId 被评论对象的ID
* @return Comment 评论
*/
function putComment($content, $targetUserId, $commentType, $entryOwnerId, $entryId) {
$params = array();
$bodyParams = array();
$fileParams = array();
if (isset($content)) {
$params ['content'] = $content;
}
if (isset($targetUserId)) {
$params ['targetUserId'] = $targetUserId;
}
if (isset($commentType)) {
$params ['commentType'] = $commentType;
}
if (isset($entryOwnerId)) {
$params ['entryOwnerId'] = $entryOwnerId;
}
if (isset($entryId)) {
$params ['entryId'] = $entryId;
}
return $this->client->execute('/v2/comment/put', 'POST', $params, $bodyParams, $fileParams);
}
/**
* 以分页的方式获取某个UGC的评论
* <br />对应API:{$link http://dev.renren.com/API/v2/comment/list }
* @param Boolean $desc 是否降序。true:按评论时间降序;false:按评论时间升序;默认:true,按评论时间降序。
* @param Integer $pageSize 页面大小。取值范围1-100,默认大小20
* @param Integer $pageNumber 页码。取值大于零,默认值为1
* @param CommentType $commentType 评论的类型
* @param Long $entryOwnerId 评论对象所有者的ID
* @param Long $entryId 被评论对象的ID
* @return Comment 评论
*/
function listComment($desc, $pageSize, $pageNumber, $commentType, $entryOwnerId, $entryId) {
$params = array();
$bodyParams = array();
$fileParams = array();
if (isset($desc)) {
$params ['desc'] = $desc;
}
if (isset($pageSize)) {
$params ['pageSize'] = $pageSize;
}
if (isset($pageNumber)) {
$params ['pageNumber'] = $pageNumber;
}
if (isset($commentType)) {
$params ['commentType'] = $commentType;
}
if (isset($entryOwnerId)) {
$params ['entryOwnerId'] = $entryOwnerId;
}
if (isset($entryId)) {
$params ['entryId'] = $entryId;
}
return $this->client->execute('/v2/comment/list', 'GET', $params, $bodyParams, $fileParams);
}
}
?>
... ...
<?php
class FeedService extends RennServiceBase {
/**
* 发送自定义新鲜事。新鲜事会发布用户的个人动态信息到用户人人网主页,<br> 同时会出现在好友的新鲜事中。
* <br />对应API:{$link http://dev.renren.com/API/v2/feed/put }
* @param String $message 用户输入的自定义内容。注意:最多200个字符
* @param String $title 新鲜事标题 注意:最多30个字符
* @param String $actionTargetUrl 新鲜事动作模块链接
* @param String $imageUrl 新鲜事图片地址
* @param String $description 新鲜事主体内容 注意:最多200个字符。
* @param String $subtitle 新鲜事副标题 注意:最多20个字符
* @param String $actionName 新鲜事动作模块文案。 注意:最多10个字符
* @param String $targetUrl 新鲜事标题和图片指向的链接
* @return Long 发布新鲜事的ID
*/
function putFeed($message, $title, $actionTargetUrl, $imageUrl, $description, $subtitle, $actionName, $targetUrl) {
$params = array();
$bodyParams = array();
$fileParams = array();
if (isset($message)) {
$params ['message'] = $message;
}
if (isset($title)) {
$params ['title'] = $title;
}
if (isset($actionTargetUrl)) {
$params ['actionTargetUrl'] = $actionTargetUrl;
}
if (isset($imageUrl)) {
$params ['imageUrl'] = $imageUrl;
}
if (isset($description)) {
$params ['description'] = $description;
}
if (isset($subtitle)) {
$params ['subtitle'] = $subtitle;
}
if (isset($actionName)) {
$params ['actionName'] = $actionName;
}
if (isset($targetUrl)) {
$params ['targetUrl'] = $targetUrl;
}
return $this->client->execute('/v2/feed/put', 'POST', $params, $bodyParams, $fileParams);
}
/**
* 根据新鲜事类型获取新鲜事列表
* <br />对应API:{$link http://dev.renren.com/API/v2/feed/list }
* @param FeedType $feedType 新鲜事类型
* @param Long $userId 用户id,不传时表示获取当前用户人人网首页新鲜事,否则获取对应用户的个人主页新鲜事
* @param Integer $pageSize 页面大小。取值范围1-100,默认大小30
* @param Integer $pageNumber 页数,取值大于0,默认值为1
* @return Feed 新鲜事
*/
function listFeed($feedType, $userId, $pageSize, $pageNumber) {
$params = array();
$bodyParams = array();
$fileParams = array();
if (isset($feedType)) {
$feedTypeList=null;
foreach($feedType as $value) {
if($feedTypeList == null) {
$feedTypeList = strval($value);
} else {
$feedTypeList =$feedTypeList.",".strval($value);
}
}
$params ['feedType'] = $feedTypeList;
}
if (isset($userId)) {
$params ['userId'] = $userId;
}
if (isset($pageSize)) {
$params ['pageSize'] = $pageSize;
}
if (isset($pageNumber)) {
$params ['pageNumber'] = $pageNumber;
}
return $this->client->execute('/v2/feed/list', 'GET', $params, $bodyParams, $fileParams);
}
}
?>
... ...
<?php
class FriendService extends RennServiceBase {
/**
* 获取某个用户的好友ID列表
* <br />对应API:{$link http://dev.renren.com/API/v2/friend/list }
* @param Long $userId 用户ID。该字段默认为当前用户
* @param Integer $pageSize 页面大小。默认大小500。
* @param Integer $pageNumber 页码。取值大于零,默认值为1
* @return Integer [] 好友ID列表
*/
function listFriend($userId, $pageSize, $pageNumber) {
$params = array();
$bodyParams = array();
$fileParams = array();
if (isset($userId)) {
$params ['userId'] = $userId;
}
if (isset($pageSize)) {
$params ['pageSize'] = $pageSize;
}
if (isset($pageNumber)) {
$params ['pageNumber'] = $pageNumber;
}
return $this->client->execute('/v2/friend/list', 'GET', $params, $bodyParams, $fileParams);
}
}
?>
... ...
<?php
class InvitationService extends RennServiceBase {
/**
* 发送邀请
* <br />对应API:{$link http://dev.renren.com/API/v2/invitation/put }
* @param InvitationType $invitationType 邀请类别,默认为应用邀请
* @param Long $userId 被邀请用户id
* @param String $img 图片链接
* @param String $gitName 礼物名称,InvitationType为GIFT时有效,不能超过6个字符
* @param String $url 应用的链接地址
* @return Invitation 邀请信息
*/
function putInvitation($invitationType, $userId, $img, $gitName, $url) {
$params = array();
$bodyParams = array();
$fileParams = array();
if (isset($invitationType)) {
$params ['invitationType'] = $invitationType;
}
if (isset($userId)) {
$params ['userId'] = $userId;
}
if (isset($img)) {
$params ['img'] = $img;
}
if (isset($gitName)) {
$params ['gitName'] = $gitName;
}
if (isset($url)) {
$params ['url'] = $url;
}
return $this->client->execute('/v2/invitation/put', 'POST', $params, $bodyParams, $fileParams);
}
}
?>
... ...
<?php
class LikeService extends RennServiceBase {
/**
* 取消对站内资源的赞。
* <br />对应API:{$link http://dev.renren.com/API/v2/like/ugc/remove }
* @param Long $ugcOwnerId UGC所有者的用户ID
* @param LikeUGCType $likeUGCType
* @param Long $ugcId UGC的ID
* @return Integer 取消成功返回1
*/
function removeLikeUgc($ugcOwnerId, $likeUGCType, $ugcId) {
$params = array();
$bodyParams = array();
$fileParams = array();
if (isset($ugcOwnerId)) {
$params ['ugcOwnerId'] = $ugcOwnerId;
}
if (isset($likeUGCType)) {
$params ['likeUGCType'] = $likeUGCType;
}
if (isset($ugcId)) {
$params ['ugcId'] = $ugcId;
}
return $this->client->execute('/v2/like/ugc/remove', 'POST', $params, $bodyParams, $fileParams);
}
/**
* 赞人人内部资源,相册、照片、日志、分享、视频等。
* <br />对应API:{$link http://dev.renren.com/API/v2/like/ugc/put }
* @param Long $ugcOwnerId UGC所有者的用户ID
* @param LikeUGCType $likeUGCType
* @param Long $ugcId UGC的ID
* @return Integer 赞成功返回1
*/
function putLikeUgc($ugcOwnerId, $likeUGCType, $ugcId) {
$params = array();
$bodyParams = array();
$fileParams = array();
if (isset($ugcOwnerId)) {
$params ['ugcOwnerId'] = $ugcOwnerId;
}
if (isset($likeUGCType)) {
$params ['likeUGCType'] = $likeUGCType;
}
if (isset($ugcId)) {
$params ['ugcId'] = $ugcId;
}
return $this->client->execute('/v2/like/ugc/put', 'POST', $params, $bodyParams, $fileParams);
}
/**
* 获取站内资源被赞的次数。
* <br />对应API:{$link http://dev.renren.com/API/v2/like/ugc/info/get }
* @param Integer $limit 最多返回喜欢此资源的用户数,最大为50,默认值为10。
* @param Boolean $withLikeUsers 是否包含喜欢此资源的用户
* @param LikeUGCType $likeUGCType 可以赞的UGC类型。
* @param Long $ugcId UGC的ID
* @return LikeInfo 获取资源被喜欢的信息,包括喜欢数、当前用户是否喜欢
*/
function getLikeUgcInfo($limit, $withLikeUsers, $likeUGCType, $ugcId) {
$params = array();
$bodyParams = array();
$fileParams = array();
if (isset($limit)) {
$params ['limit'] = $limit;
}
if (isset($withLikeUsers)) {
$params ['withLikeUsers'] = $withLikeUsers;
}
if (isset($likeUGCType)) {
$params ['likeUGCType'] = $likeUGCType;
}
if (isset($ugcId)) {
$params ['ugcId'] = $ugcId;
}
return $this->client->execute('/v2/like/ugc/info/get', 'GET', $params, $bodyParams, $fileParams);
}
}
?>
... ...
<?php
class NotificationService extends RennServiceBase {
/**
* 以用户身份向用户发送通知
* <br />对应API:{$link http://dev.renren.com/API/v2/notification/user/put }
* @param String $content 通知的内容,可以是XNML类型的文本信息,支持的XNML有<xn:name/>和<a/>,请注意:使用<xn:name/>标签的时候,其uid属性值只能是真实的用户id(阿拉伯数字)。例如:hello,<xn:name uid="200032219" linked="true"/> ,去看看这部电影<a href="http://www.tudou.com/programs/view/Tzpw9PIj8zM/">狮子王</a>。通知长度不能大于500个字符
* @param Long $userIds 接收通知的用户列表。这些用户必须是当前登录用户的好友或应用安装用户。请确保一次传入的用户id数少于20个。不能给当前用户发送通知,发送的通知会被忽略
* @return Integer 发送成功返回1
*/
function putNotificationUser($content, $userIds) {
$params = array();
$bodyParams = array();
$fileParams = array();
if (isset($content)) {
$params ['content'] = $content;
}
if (isset($userIds)) {
$userIdsList=null;
foreach($userIds as $value) {
if($userIdsList == null) {
$userIdsList = strval($value);
} else {
$userIdsList =$userIdsList.",".strval($value);
}
}
$params ['userIds'] = $userIdsList;
}
return $this->client->execute('/v2/notification/user/put', 'POST', $params, $bodyParams, $fileParams);
}
/**
* 以应用身份向用户发送通知
* <br />对应API:{$link http://dev.renren.com/API/v2/notification/app/put }
* @param String $content 通知的内容,可以是XNML类型的文本信息,支持的XNML有<xn:name/>和<a/>,请注意:使用<xn:name/>标签的时候,其uid属性值只能是真实的用户id(阿拉伯数字)。例如:hello,<xn:name uid="200032219" linked="true"/> ,去看看这部电影<a href="http://www.tudou.com/programs/view/Tzpw9PIj8zM/">狮子王</a>。通知长度不能大于500个字符
* @param Long $userIds 接收通知的用户列表。这些用户必须安装了此应用。请确保一次传入的用户id数少于20个
* @return Integer 发送成功返回1
*/
function putNotificationApp($content, $userIds) {
$params = array();
$bodyParams = array();
$fileParams = array();
if (isset($content)) {
$params ['content'] = $content;
}
if (isset($userIds)) {
$userIdsList=null;
foreach($userIds as $value) {
if($userIdsList == null) {
$userIdsList = strval($value);
} else {
$userIdsList =$userIdsList.",".strval($value);
}
}
$params ['userIds'] = $userIdsList;
}
return $this->client->execute('/v2/notification/app/put', 'POST', $params, $bodyParams, $fileParams);
}
}
?>
... ...
<?php
class PhotoService extends RennServiceBase {
/**
* 上传照片至用户相册。此接口需要采用multipart/form-data的编码方式。
* <br />对应API:{$link http://dev.renren.com/API/v2/photo/upload }
* @param Long $albumId 相册ID,albumId省略时会上传到应用相册
* @param String $description 照片描述。不能超过200个字符
* @param $paramter.simpleType2 $file 照片
* @return Photo 照片
*/
function uploadPhoto($albumId, $description, $file) {
$params = array();
$bodyParams = array();
$fileParams = array();
if (isset($albumId)) {
$params ['albumId'] = $albumId;
}
if (isset($description)) {
$params ['description'] = $description;
}
if (isset($file)) {
$fileParams ['file'] = $file;
}
return $this->client->execute('/v2/photo/upload', 'POST', $params, $bodyParams, $fileParams);
}
/**
* 获取某个用户某个相册里的某张照片
* <br />对应API:{$link http://dev.renren.com/API/v2/photo/get }
* @param Long $albumId 相册的ID
* @param Long $photoId 照片的ID
* @param Long $ownerId 相册所有者的ID
* @param String $password 相册的密码
* @return Photo 照片
*/
function getPhoto($albumId, $photoId, $ownerId, $password) {
$params = array();
$bodyParams = array();
$fileParams = array();
if (isset($albumId)) {
$params ['albumId'] = $albumId;
}
if (isset($photoId)) {
$params ['photoId'] = $photoId;
}
if (isset($ownerId)) {
$params ['ownerId'] = $ownerId;
}
if (isset($password)) {
$params ['password'] = $password;
}
return $this->client->execute('/v2/photo/get', 'GET', $params, $bodyParams, $fileParams);
}
/**
* 以分页的方式获取某个用户某个相册里的照片列表
* <br />对应API:{$link http://dev.renren.com/API/v2/photo/list }
* @param Long $albumId 相册的ID
* @param Long $ownerId 相册所有者的ID
* @param Integer $pageSize 页面大小。取值范围1-100,默认大小20
* @param Integer $pageNumber 页码。取值大于零,默认值为1
* @param String $password 相册的密码,
* @return Photo 照片
*/
function listPhoto($albumId, $ownerId, $pageSize, $pageNumber, $password) {
$params = array();
$bodyParams = array();
$fileParams = array();
if (isset($albumId)) {
$params ['albumId'] = $albumId;
}
if (isset($ownerId)) {
$params ['ownerId'] = $ownerId;
}
if (isset($pageSize)) {
$params ['pageSize'] = $pageSize;
}
if (isset($pageNumber)) {
$params ['pageNumber'] = $pageNumber;
}
if (isset($password)) {
$params ['password'] = $password;
}
return $this->client->execute('/v2/photo/list', 'GET', $params, $bodyParams, $fileParams);
}
}
?>
... ...
<?php
class ProfileService extends RennServiceBase {
/**
* 获取用户的主页信息,包括各种统计数据。
* <br />对应API:{$link http://dev.renren.com/API/v2/profile/get }
* @param Long $userId 用户ID
* @return Profile 个人主页信息
*/
function getProfile($userId) {
$params = array();
$bodyParams = array();
$fileParams = array();
if (isset($userId)) {
$params ['userId'] = $userId;
}
return $this->client->execute('/v2/profile/get', 'GET', $params, $bodyParams, $fileParams);
}
}
?>
... ...
<?php
class RennServiceBase {
protected $client;
protected $accessToken;
/**
* 构造函数
*/
function __construct($client, $accessToken) {
$this->client = $client;
$this->accessToken = $accessToken;
}
}
\ No newline at end of file
... ...
<?php
class ShareService extends RennServiceBase {
/**
* 分享人人网内部UGC资源,例如:日志、照片、相册、分享(基于已有分享再次进行分享)
* <br />对应API:{$link http://dev.renren.com/API/v2/share/ugc/put }
* @param Long $ugcOwnerId UGC所有者的用户ID
* @param String $comment 分享时用户的评论,评论字数不能超过500字符
* @param Long $ugcId UGC的ID
* @param UGCType $ugcType UGC的类型。
* @return Share 分享
*/
function putShareUgc($ugcOwnerId, $comment, $ugcId, $ugcType) {
$params = array();
$bodyParams = array();
$fileParams = array();
if (isset($ugcOwnerId)) {
$params ['ugcOwnerId'] = $ugcOwnerId;
}
if (isset($comment)) {
$params ['comment'] = $comment;
}
if (isset($ugcId)) {
$params ['ugcId'] = $ugcId;
}
if (isset($ugcType)) {
$params ['ugcType'] = $ugcType;
}
return $this->client->execute('/v2/share/ugc/put', 'POST', $params, $bodyParams, $fileParams);
}
/**
* 获取人人推荐资源
* <br />对应API:{$link http://dev.renren.com/API/v2/share/hot/list }
* @param Integer $pageSize 页面大小。取值范围1-50,默认大小20
* @param Integer $pageNumber 页码。取值大于零,默认值为1
* @param ShareType $shareType 分享类型
* @return Share 分享
*/
function listShareHot($pageSize, $pageNumber, $shareType) {
$params = array();
$bodyParams = array();
$fileParams = array();
if (isset($pageSize)) {
$params ['pageSize'] = $pageSize;
}
if (isset($pageNumber)) {
$params ['pageNumber'] = $pageNumber;
}
if (isset($shareType)) {
$params ['shareType'] = $shareType;
}
return $this->client->execute('/v2/share/hot/list', 'GET', $params, $bodyParams, $fileParams);
}
/**
* 分享人人网外部资源,例如:视频、图片等<br> 如果要分享一张本地照片到人人网(即上传),建议使用[http://wiki.dev.renren.com/wiki/v2/photo/upload /v2/photo/upload]接口
* <br />对应API:{$link http://dev.renren.com/API/v2/share/url/put }
* @param String $comment 分享时用户的评论,评论字数不能超过500个字符
* @param String $url 分享资源的URL
* @return Share 分享
*/
function putShareUrl($comment, $url) {
$params = array();
$bodyParams = array();
$fileParams = array();
if (isset($comment)) {
$params ['comment'] = $comment;
}
if (isset($url)) {
$params ['url'] = $url;
}
return $this->client->execute('/v2/share/url/put', 'POST', $params, $bodyParams, $fileParams);
}
/**
* 获取某个用户的某个分享
* <br />对应API:{$link http://dev.renren.com/API/v2/share/get }
* @param Long $shareId 分享ID
* @param Long $ownerId 分享所有者ID
* @return Share 分享
*/
function getShare($shareId, $ownerId) {
$params = array();
$bodyParams = array();
$fileParams = array();
if (isset($shareId)) {
$params ['shareId'] = $shareId;
}
if (isset($ownerId)) {
$params ['ownerId'] = $ownerId;
}
return $this->client->execute('/v2/share/get', 'GET', $params, $bodyParams, $fileParams);
}
/**
* 以分页的方式获取某个用户的分享列表
* <br />对应API:{$link http://dev.renren.com/API/v2/share/list }
* @param Long $ownerId 分享所有者ID
* @param Integer $pageSize 页面大小。取值范围1-100,默认大小20
* @param Integer $pageNumber 页码。取值大于零,默认值为1
* @return Share 分享
*/
function listShare($ownerId, $pageSize, $pageNumber) {
$params = array();
$bodyParams = array();
$fileParams = array();
if (isset($ownerId)) {
$params ['ownerId'] = $ownerId;
}
if (isset($pageSize)) {
$params ['pageSize'] = $pageSize;
}
if (isset($pageNumber)) {
$params ['pageNumber'] = $pageNumber;
}
return $this->client->execute('/v2/share/list', 'GET', $params, $bodyParams, $fileParams);
}
}
?>
... ...
<?php
class StatusService extends RennServiceBase {
/**
* 获取用户状态
* <br />对应API:{$link http://dev.renren.com/API/v2/status/get }
* @param Long $statusId 状态ID
* @param Long $ownerId 状态所有者的用户ID
* @return Status 状态
*/
function getStatus($statusId, $ownerId) {
$params = array();
$bodyParams = array();
$fileParams = array();
if (isset($statusId)) {
$params ['statusId'] = $statusId;
}
if (isset($ownerId)) {
$params ['ownerId'] = $ownerId;
}
return $this->client->execute('/v2/status/get', 'GET', $params, $bodyParams, $fileParams);
}
/**
* 更新用户状态
* <br />对应API:{$link http://dev.renren.com/API/v2/status/put }
* @param String $content 状态的内容。状态内容不能长于240个字符。内容中的UBB表情代码未经过处理,需要开发者自行进行替换。UBB表情参见:[http://wiki.dev.renren.com/wiki/V2/ubb/list 获取人人网ubb列表]
* @return Status 状态
*/
function putStatus($content) {
$params = array();
$bodyParams = array();
$fileParams = array();
if (isset($content)) {
$params ['content'] = $content;
}
return $this->client->execute('/v2/status/put', 'POST', $params, $bodyParams, $fileParams);
}
/**
* 获取用户状态列表
* <br />对应API:{$link http://dev.renren.com/API/v2/status/list }
* @param Long $ownerId 状态所有者的用户ID
* @param Integer $pageSize 页面大小。取值范围1-100,默认大小20
* @param Integer $pageNumber 页码。取值大于零,默认值为1
* @return Status 状态
*/
function listStatus($ownerId, $pageSize, $pageNumber) {
$params = array();
$bodyParams = array();
$fileParams = array();
if (isset($ownerId)) {
$params ['ownerId'] = $ownerId;
}
if (isset($pageSize)) {
$params ['pageSize'] = $pageSize;
}
if (isset($pageNumber)) {
$params ['pageNumber'] = $pageNumber;
}
return $this->client->execute('/v2/status/list', 'GET', $params, $bodyParams, $fileParams);
}
/**
* 分享用户状态
* <br />对应API:{$link http://dev.renren.com/API/v2/status/share }
* @param String $content 状态的内容。状态内容不能长于240个字符。内容中的UBB表情代码未经过处理,需要开发者自行进行替换。UBB表情参见:[http://wiki.dev.renren.com/wiki/V2/ubb/list 获取人人网ubb列表]
* @param Long $statusId 状态ID
* @param Long $ownerId 状态所有者的用户ID
* @return Status 状态
*/
function shareStatus($content, $statusId, $ownerId) {
$params = array();
$bodyParams = array();
$fileParams = array();
if (isset($content)) {
$params ['content'] = $content;
}
if (isset($statusId)) {
$params ['statusId'] = $statusId;
}
if (isset($ownerId)) {
$params ['ownerId'] = $ownerId;
}
return $this->client->execute('/v2/status/share', 'POST', $params, $bodyParams, $fileParams);
}
}
?>
... ...
<?php
class UbbService extends RennServiceBase {
/**
* 获取人人网ubb列表
* <br />对应API:{$link http://dev.renren.com/API/v2/ubb/list }
* @return Ubb UBB表情
*/
function listUbb() {
$params = array();
$bodyParams = array();
$fileParams = array();
return $this->client->execute('/v2/ubb/list', 'GET', $params, $bodyParams, $fileParams);
}
}
?>
... ...
<?php
class UserService extends RennServiceBase {
/**
* 批量获取用户信息
* <br />对应API:{$link http://dev.renren.com/API/v2/user/batch }
* @param Long $userIds 批量获取的用户IDs,最多支持50个
* @return User 用户
*/
function batchUser($userIds) {
$params = array();
$bodyParams = array();
$fileParams = array();
if (isset($userIds)) {
$userIdsList=null;
foreach($userIds as $value) {
if($userIdsList == null) {
$userIdsList = strval($value);
} else {
$userIdsList =$userIdsList.",".strval($value);
}
}
$params ['userIds'] = $userIdsList;
}
return $this->client->execute('/v2/user/batch', 'GET', $params, $bodyParams, $fileParams);
}
/**
* 获取用户信息
* <br />对应API:{$link http://dev.renren.com/API/v2/user/get }
* @param Long $userId 用户ID
* @return User 用户
*/
function getUser($userId) {
$params = array();
$bodyParams = array();
$fileParams = array();
if (isset($userId)) {
$params ['userId'] = $userId;
}
return $this->client->execute('/v2/user/get', 'GET', $params, $bodyParams, $fileParams);
}
/**
* 获取某个用户的好友列表
* <br />对应API:{$link http://dev.renren.com/API/v2/user/friend/list }
* @param Long $userId 用户ID
* @param Integer $pageSize 页面大小。取值范围1-100,默认大小20
* @param Integer $pageNumber 页码。取值大于零,默认值为1
* @return User 用户
*/
function listUserFriend($userId, $pageSize, $pageNumber) {
$params = array();
$bodyParams = array();
$fileParams = array();
if (isset($userId)) {
$params ['userId'] = $userId;
}
if (isset($pageSize)) {
$params ['pageSize'] = $pageSize;
}
if (isset($pageNumber)) {
$params ['pageNumber'] = $pageNumber;
}
return $this->client->execute('/v2/user/friend/list', 'GET', $params, $bodyParams, $fileParams);
}
/**
* 获取当前登录用户未安装某应用里的好友列表
* <br />对应API:{$link http://dev.renren.com/API/v2/user/friend/uninstall/list }
* @return User 用户
*/
function listUserFriendUninstall() {
$params = array();
$bodyParams = array();
$fileParams = array();
return $this->client->execute('/v2/user/friend/uninstall/list', 'GET', $params, $bodyParams, $fileParams);
}
/**
* 以分页的方式获取某个用户与当前登录用户的共同好友
* <br />对应API:{$link http://dev.renren.com/API/v2/user/friend/mutual/list }
* @param Long $userId 用户ID
* @return User 用户
*/
function listUserFriendMutual($userId) {
$params = array();
$bodyParams = array();
$fileParams = array();
if (isset($userId)) {
$params ['userId'] = $userId;
}
return $this->client->execute('/v2/user/friend/mutual/list', 'GET', $params, $bodyParams, $fileParams);
}
/**
* 获取当前登录用户在某个应用里的好友列表
* <br />对应API:{$link http://dev.renren.com/API/v2/user/friend/app/list }
* @return User 用户
*/
function listUserFriendApp() {
$params = array();
$bodyParams = array();
$fileParams = array();
return $this->client->execute('/v2/user/friend/app/list', 'GET', $params, $bodyParams, $fileParams);
}
/**
* 获取当前登录用户信息
* <br />对应API:{$link http://dev.renren.com/API/v2/user/login/get }
* @return User 用户
*/
function getUserLogin() {
$params = array();
$bodyParams = array();
$fileParams = array();
return $this->client->execute('/v2/user/login/get', 'GET', $params, $bodyParams, $fileParams);
}
}
?>
... ...
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type