<?PHP
/**
* VK
* Класс для взаимодействия с API социальной сети вКонтакте
* Описание возможностей API тут http://vk.com/developers.php
*/
class VKException extends Exception {}
class VK{
/**
* App ID
* @var integer
*/
private $iAppID = 0;
/**
* App secret key
* @var string
*/
private $sAppSecret = '';
/**
* Access token
* @var string
*/
private $sToken ='';
/**
* Auth display method
* @var string
*/
private $sDisplay = VK::VK_DISPLAY_PAGE;
/**
* On this page you will be redirected after login
* @var string
*/
private $sRedirectURI = '';
/**
* Auth permission
* @var string
*/
private $sScope = 'offline';
/**
* Request uri
* @var string
*/
private $sRequest;
/**
* Response JSON string
* @var string
*/
private $sResponse;
/**
* decoded response
* @var object
*/
private $oResponse;
/**
* Array containts data for POST request
* @var array
*/
private $rgPostData = array();
/**
* Request method
* @var array
*/
private $iRequestMethod = self::VK_GET_REQUEST;
/**
* Curl resourse
* @var string
*/
private $rCurl;
/**
* Access token file path
* @var string
*/
private $sTokenFile = '.vk_token';
/**
* Разделитель прав доступа в URL авторизации
*/
const VK_PERMISSION_SEPARATOR = ',';
/**
* Методы запросов
*/
const VK_POST_REQUEST = 1;
const VK_GET_REQUEST = 2;
/**
* Константы возможных прав доступа
*/
const VK_ACCESS_NOTIFY = 'notify';
const VK_ACCESS_FRIENDS = 'friends';
const VK_ACCESS_PHOTOS = 'photos';
const VK_ACCESS_AUDIO = 'audio';
const VK_ACCESS_VIDEO = 'video';
const VK_ACCESS_DOCS = 'docs';
const VK_ACCESS_NOTES = 'notes';
const VK_ACCESS_PAGES = 'pages';
const VK_ACCESS_GROUPS = 'groups';
const VK_ACCESS_NOTIFICATIONS = 'notifications';
const VK_ACCESS_OFFLINE = 'offline';
/**
* Константы возможных типов страницы авторизации
*/
const VK_DISPLAY_PAGE = 'page';
const VK_DISPLAY_POPUP = 'popup';
const VK_DISPLAY_WAP = 'wap';
/**
* init()
* Выполняет инициализацию объекта
* @access public
* @return void
*/
public function init(){
$this->__checkRequired();
$this->_checkToken();
}
/**
* setAppId()
* Устанавливает ID приложения
* @access public
* @param integer $iAppID ID приложения
* @return $this
*/
public function setAppId($iAppID){
$this->iAppID = $iAppID;
return $this;
}
/**
* setTokenFilePath()
* Устанавливает путь к файлу, в который будет сохранен токен доступа
* @access public
* @param string $sTokenFilePath Путь к файлу access tokena
* @return $this
*/
public function setTokenFilePath($sTokenFilePath){
if(!is_string($sTokenFilePath)) $this->__setError
('Invalid argument for setTokenFilePath'); if(!empty($this->sTokenFile))$this->sTokenFile = $sTokenFilePath; return $this;
}
/**
* getToken()
* Возвращает текущий токен доступа
* @access public
* @return string
*/
public function getToken(){
return $this->sToken;
}
/**
* setSecretKey()
* Устанавливает URL на который будет перенаправление после авторизации
* @access public
* @param string $sSecretKey Секретный ключ приложения
* @return $this
*/
public function setSecretKey($sSecretKey){
$this->sAppSecret = $sSecretKey;
return $this;
}
/**
* setRedirectUri()
* Устанавливает URL на который будет перенаправление после авторизации
* @access public
* @param string $sRedirectURI URL с http://
* @return $this
*/
public function setRedirectUri($sRedirectURI){
$this->sRedirectURI = urlencode($sRedirectURI); return $this;
}
/**
* setPermission()
* Добавляет права доступа которые будут запрошены при авторизации
* @access public
* @param mixed $mPermission Значение параметра
* @return $this
*/
public function setPermission($mPermission){
$this->sScope = implode(self::VK_PERMISSION_SEPARATOR, $mPermission); $this->sScope = $mPermission;
}else{
$this->sScope = '';
}
return $this;
}
/**
* addPermission()
* Добавляет права доступа которые будут запрошены при авторизации
* @access public
* @param string $sPermission
* @return $this
*/
public function addPermission($sPermission){
if(!empty($sPermission) && !stripos($this->sScope, $sPermission)) $this->sScope .= self::VK_PERMISSION_SEPARATOR.$sPermission;
return $this;
}
/**
* setOAuthDisplayType()
* Устанавливает тип страницы авторизации вКонтакте
* @access public
* @param string $sDisplayType Тип страницы авторизации
* @return $this
*/
public function setOAuthDisplayType($sDisplayType){
$this->sDisplay = $sDisplayType;
return $this;
}
/**
* setRequestMethod()
* Устанавливает метод котором будет выполнен запрос
* @access public
* @param integer $iRequestMethod Метод
* @return $this
*/
public function setRequestMethod($iRequestMethod){
$this->iRequestMethod = $iRequestMethod;
return $this;
}
/**
* setPostData()
* Устанавливает данные для POST запроса
* @access public
* @param array $rgPostData Массив данных для пост запроса
* @return $this
*/
public function setPostData($rgPostData){
if(is_array($rgPostData)) $this->rgPostData = $rgPostData; return $this;
}
/**
* addPostData()
* Добавляет данные для POST запроса
* @access public
* @param string $sKey Имя параметра
* @param string $sValue Значение параметра
* @return $this
*/
public function addPostData($sKey, $sValue){
$this->rgPostData[$sKey] = $sValue;
return $this;
}
/**
* setRequestUri()
* Устанавливает URL запроса
* @access public
* @param string $sUri URL
* @return $this
*/
public function setRequestUri($sUri){
$this->sRequest = $sUri;
return $this;
}
/**
* execute()
* Выполняет запрос
* @access public
* @return $this
*/
public function execute(){
curl_setopt($this->rCurl, CURLOPT_URL
, $this->sRequest); if($this->iRequestMethod === 1){
curl_setopt($this->rCurl, CURLOPT_POSTFIELDS
, $this->rgPostData); }
return $this;
}
/**
* fetchObject()
* Возвращает объект содержащий ответ от вКонтакте
* @access public
* @return object
*/
public function fetchObject(){
$this->_prepareResponse();
if(!isset($this->oResponse->response) && isset($this->oResponse)){ return $this->oResponse;
}elseif(isset($this->oResponse->response)){ return $this->oResponse->response;
}else{
return NULL;
}
}
/**
* fetchJson()
* Возвращает JSON строку ответа от вКонтакте
* @access public
* @return string
*/
public function fetchJson(){
return $this->sResponse;
}
/**
* vk_method()
* Формирует запрос к API
* @access public
* @param string $sMethod Имя метода API
* @param array $rgRequestData Параметры запроса
* @return $this
*/
public function vk_method($sMethod, $rgRequestData){
$rgRequestData['access_token'] = $this->sToken;
$this->sRequest = 'https://api.vkontakte.ru/method/'.$sMethod.'?';
if($this->iRequestMethod !==1 ){
}else{
$this->rgPostData = $rgRequestData;
}
return $this;
}
protected function _checkResponse(){
if(isset($this->oResponse->error)) return false; return true;
}
protected function _checkToken(){
if(!$this->sToken){
if(isset($_GET['code']) && !empty($_GET['code'])){ if($this->__getGrant()){
header('Location: '.$_SERVER['PHP_SELF']); return true;
}
}
$this->__showLogin();
$this->__setError('Autorization required!');
}
return ;
}
protected function _prepareResponse(){
$this->__decodeResponse();
if($this->_checkResponse()){
return true;
}else{
$this->__apiErrorHandler();
}
}
private function __showLogin(){
echo $sButton = "<a href='http://api.vkontakte.ru/oauth/authorize?client_id={$this->iAppID}&scope={$this->sScope}&redirect_uri={$this->sRedirectURI}&response_type=code&display={$this->sDisplay}'>Авторизация Вконтакте</a><br/>";
return;
}
private function __getGrant(){
$sTokenURI = "https://api.vkontakte.ru/oauth/access_token?client_id={$this->iAppID}&client_secret={$this->sAppSecret}&code={$_GET['code']}";
$this->setRequestUri($sTokenURI);
$this->execute()->_prepareResponse();
if(!isset($this->oResponse->error) && isset($this->oResponse->access_token)){ if(!file_put_contents($this->sTokenFile, $this->oResponse->access_token)) $this->__setError
('Не удалось сохранить access token в фаил'); return true;
}else{
return false;
}
}
private function __decodeResponse(){
return $this;
}
private function __apiErrorHandler(){
if(!isset($this->oResponse->error->error_code)){ $this->__setError('API ERROR: '.$this->oResponse->error.' - '.$this->oResponse->error_description);
}else{
$this->__setError('API ERROR: '.$this->oResponse->error->error_code.' - '.$this->oResponse->error->error_msg);
}
}
private function __setError($sError){
throw new VKException($sError);
}
private function __checkRequired(){
if(!$this->iAppID) $this->__setError('Не установлен Aplication ID');
if(!$this->sScope) $this->__setError('Не установлен не установлены необходимые права доступа');
if(!$this->sRedirectURI) $this->__setError('Не установлен адрес возврата');
if(!$this->sAppSecret) $this->__setError('Не установлен Aplication secret key');
}
}