PageRenderTime 50ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/bitrix/modules/socialservices/classes/general/facebook.php

https://bitbucket.org/bohdan1217/norka
PHP | 524 lines | 430 code | 93 blank | 1 comment | 74 complexity | 437eea76cbe2b32135a752cdc8a1d270 MD5 | raw file
  1. <?
  2. IncludeModuleLangFile(__FILE__);
  3. class CSocServFacebook extends CSocServAuth
  4. {
  5. const ID = "Facebook";
  6. const CONTROLLER_URL = "https://www.bitrix24.ru/controller";
  7. protected $entityOAuth = null;
  8. public function GetSettings()
  9. {
  10. return array(
  11. array("facebook_appid", GetMessage("socserv_fb_id"), "", Array("text", 40)),
  12. array("facebook_appsecret", GetMessage("socserv_fb_secret"), "", Array("text", 40)),
  13. array("note"=>GetMessage("socserv_fb_sett_note")),
  14. );
  15. }
  16. public function GetFormHtml($arParams)
  17. {
  18. $url = $this->getUrl($arParams);
  19. $phrase = ($arParams["FOR_INTRANET"])
  20. ? GetMessage("socserv_fb_note_intranet")
  21. : GetMessage("socserv_fb_note");
  22. return $arParams["FOR_INTRANET"]
  23. ? array("ON_CLICK" => 'onclick="BX.util.popup(\''.htmlspecialcharsbx(CUtil::JSEscape($url)).'\', 580, 400)"')
  24. : '<a href="javascript:void(0)" onclick="BX.util.popup(\''.htmlspecialcharsbx(CUtil::JSEscape($url)).'\', 580, 400)" class="bx-ss-button facebook-button"></a><span class="bx-spacer"></span><span>'.$phrase.'</span>';
  25. }
  26. public function getUrl($arParams)
  27. {
  28. if(IsModuleInstalled('bitrix24') && defined('BX24_HOST_NAME'))
  29. {
  30. $redirect_uri = self::CONTROLLER_URL."/redirect.php?redirect_to=".urlencode(CSocServUtil::GetCurUrl('auth_service_id='.self::ID.'&check_key='.$_SESSION["UNIQUE_KEY"]));
  31. }
  32. else
  33. {
  34. $redirect_uri = CSocServUtil::GetCurUrl('auth_service_id='.self::ID.'&check_key='.$_SESSION["UNIQUE_KEY"]).(isset($arParams['BACKURL']) ? '&backurl='.urlencode($arParams['BACKURL']) : '');
  35. }
  36. return $this->getEntityOAuth()->GetAuthUrl($redirect_uri);
  37. }
  38. public function getEntityOAuth($code = false)
  39. {
  40. if(!$this->entityOAuth)
  41. {
  42. $this->entityOAuth = new CFacebookInterface();
  43. }
  44. if($code !== false)
  45. {
  46. $this->entityOAuth->setCode($code);
  47. }
  48. return $this->entityOAuth;
  49. }
  50. public function addScope($scope)
  51. {
  52. return $this->getEntityOAuth()->addScope($scope);
  53. }
  54. public function prepareUser($arFBUser, $short = false)
  55. {
  56. $arFields = array(
  57. 'EXTERNAL_AUTH_ID' => self::ID,
  58. 'XML_ID' => $arFBUser["id"],
  59. 'LOGIN' => "FB_".$arFBUser["id"],
  60. 'EMAIL' => ($arFBUser["email"] != '') ? $arFBUser["email"] : '',
  61. 'NAME'=> $arFBUser["first_name"],
  62. 'LAST_NAME'=> $arFBUser["last_name"],
  63. 'OATOKEN' => $this->entityOAuth->getToken(),
  64. 'OATOKEN_EXPIRES' => $this->entityOAuth->getAccessTokenExpires(),
  65. );
  66. if(!$short && isset($arFBUser['picture']['data']['url']) && !$arFBUser['picture']['data']['is_silhouette'])
  67. {
  68. $picture_url = CFacebookInterface::GRAPH_URL.'/'.$arFBUser['id'].'/picture?type=large';
  69. $temp_path = CFile::GetTempName('', 'picture.jpg');
  70. $ob = new \Bitrix\Main\Web\HttpClient(array(
  71. "redirect" => true
  72. ));
  73. $ob->download($picture_url, $temp_path);
  74. $arPic = CFile::MakeFileArray($temp_path);
  75. if($arPic)
  76. {
  77. $arFields["PERSONAL_PHOTO"] = $arPic;
  78. }
  79. }
  80. if(isset($arFBUser['birthday']))
  81. {
  82. if($date = MakeTimeStamp($arFBUser['birthday'], "MM/DD/YYYY"))
  83. {
  84. $arFields["PERSONAL_BIRTHDAY"] = ConvertTimeStamp($date);
  85. }
  86. }
  87. if(isset($arFBUser['gender']) && $arFBUser['gender'] != '')
  88. {
  89. if($arFBUser['gender'] == 'male')
  90. {
  91. $arFields["PERSONAL_GENDER"] = 'M';
  92. }
  93. elseif($arFBUser['gender'] == 'female')
  94. {
  95. $arFields["PERSONAL_GENDER"] = 'F';
  96. }
  97. }
  98. $arFields["PERSONAL_WWW"] = $this->getProfileUrl($arFBUser['id']);
  99. if(strlen(SITE_ID) > 0)
  100. {
  101. $arFields["SITE_ID"] = SITE_ID;
  102. }
  103. return $arFields;
  104. }
  105. public function Authorize()
  106. {
  107. global $APPLICATION;
  108. $APPLICATION->RestartBuffer();
  109. $authError = SOCSERV_AUTHORISATION_ERROR;
  110. if(
  111. isset($_REQUEST["code"]) && $_REQUEST["code"] <> ''
  112. && CSocServAuthManager::CheckUniqueKey()
  113. )
  114. {
  115. if(IsModuleInstalled('bitrix24') && defined('BX24_HOST_NAME'))
  116. {
  117. $redirect_uri = self::CONTROLLER_URL."/redirect.php?redirect_to=".urlencode(CSocServUtil::GetCurUrl('auth_service_id='.self::ID, array("code")));
  118. }
  119. else
  120. {
  121. $redirect_uri = CSocServUtil::GetCurUrl('auth_service_id='.self::ID, array("code"));
  122. }
  123. $this->entityOAuth = $this->getEntityOAuth($_REQUEST['code']);
  124. if($this->entityOAuth->GetAccessToken($redirect_uri) !== false)
  125. {
  126. $arFBUser = $this->entityOAuth->GetCurrentUser();
  127. if(is_array($arFBUser) && isset($arFBUser["id"]))
  128. {
  129. $arFields = self::prepareUser($arFBUser);
  130. $authError = $this->AuthorizeUser($arFields);
  131. }
  132. }
  133. }
  134. $bSuccess = $authError === true;
  135. $aRemove = array("logout", "auth_service_error", "auth_service_id", "code", "error_reason", "error", "error_description", "check_key", "current_fieldset");
  136. if($bSuccess)
  137. {
  138. CSocServUtil::checkOAuthProxyParams();
  139. $url = ($GLOBALS["APPLICATION"]->GetCurDir() == "/login/") ? "" : $GLOBALS["APPLICATION"]->GetCurDir();
  140. if(isset($_REQUEST['backurl']))
  141. {
  142. $parseUrl = parse_url($_REQUEST['backurl']);
  143. $urlPath = $parseUrl["path"];
  144. $arUrlQuery = explode('&', $parseUrl["query"]);
  145. foreach($arUrlQuery as $key => $value)
  146. {
  147. foreach($aRemove as $param)
  148. {
  149. if(strpos($value, $param."=") === 0)
  150. {
  151. unset($arUrlQuery[$key]);
  152. break;
  153. }
  154. }
  155. }
  156. $url = (!empty($arUrlQuery)) ? $urlPath.'?'.implode("&", $arUrlQuery) : $urlPath;
  157. }
  158. }
  159. if($authError === SOCSERV_REGISTRATION_DENY)
  160. {
  161. $url = (preg_match("/\?/", $url)) ? $url.'&' : $url.'?';
  162. $url .= 'auth_service_id='.self::ID.'&auth_service_error='.$authError;
  163. }
  164. elseif($bSuccess !== true)
  165. {
  166. $url = (isset($urlPath)) ? $urlPath.'?auth_service_id='.self::ID.'&auth_service_error='.$authError : $GLOBALS['APPLICATION']->GetCurPageParam(('auth_service_id='.self::ID.'&auth_service_error='.$authError), $aRemove);
  167. }
  168. if(CModule::IncludeModule("socialnetwork") && strpos($url, "current_fieldset=") === false)
  169. {
  170. $url .= ((strpos($url, "?") === false) ? '?' : '&')."current_fieldset=SOCSERV";
  171. }
  172. ?>
  173. <script type="text/javascript">
  174. if(window.opener)
  175. window.opener.location = '<?=CUtil::JSEscape($url)?>';
  176. window.close();
  177. </script>
  178. <?
  179. die();
  180. }
  181. public function getFriendsList($limit, &$next)
  182. {
  183. $fb = new CFacebookInterface();
  184. if(IsModuleInstalled('bitrix24') && defined('BX24_HOST_NAME'))
  185. {
  186. $redirect_uri = self::CONTROLLER_URL."/redirect.php?redirect_to=".urlencode(CSocServUtil::GetCurUrl('auth_service_id='.self::ID, array("code")));
  187. }
  188. else
  189. {
  190. $redirect_uri = CSocServUtil::GetCurUrl('auth_service_id='.self::ID, array("code"));
  191. }
  192. if($fb->GetAccessToken($redirect_uri) !== false)
  193. {
  194. $res = $fb->GetCurrentUserFriends($limit, $next);
  195. if(is_array($res))
  196. {
  197. foreach($res['data'] as $key => $value)
  198. {
  199. $res['data'][$key]['uid'] = $value['id'];
  200. $res['data'][$key]['url'] = $this->getProfileUrl($value['id']);
  201. if(is_array($value['picture']))
  202. {
  203. if(!$value['picture']['data']['is_silhouette'])
  204. {
  205. $res['data'][$key]['picture'] = CFacebookInterface::GRAPH_URL.'/'.$value['id'].'/picture?type=large';
  206. }
  207. else
  208. {
  209. $res['data'][$key]['picture'] = '';
  210. }
  211. //$res['data'][$key]['picture'] = $value['picture']['data']['url'];
  212. }
  213. }
  214. return $res['data'];
  215. }
  216. }
  217. return false;
  218. }
  219. public function sendMessage($uid, $message)
  220. {
  221. $fb = new CFacebookInterface();
  222. if(IsModuleInstalled('bitrix24') && defined('BX24_HOST_NAME'))
  223. {
  224. $redirect_uri = self::CONTROLLER_URL."/redirect.php?redirect_to=".urlencode(CSocServUtil::GetCurUrl('auth_service_id='.self::ID, array("code")));
  225. }
  226. else
  227. {
  228. $redirect_uri = CSocServUtil::GetCurUrl('auth_service_id='.self::ID, array("code"));
  229. }
  230. if($fb->GetAccessToken($redirect_uri) !== false)
  231. {
  232. $res = $fb->sendMessage($uid, $message);
  233. }
  234. return $res;
  235. }
  236. public function getMessages($uid)
  237. {
  238. $fb = new CFacebookInterface();
  239. if(IsModuleInstalled('bitrix24') && defined('BX24_HOST_NAME'))
  240. {
  241. $redirect_uri = self::CONTROLLER_URL."/redirect.php?redirect_to=".urlencode(CSocServUtil::GetCurUrl('auth_service_id='.self::ID, array("code")));
  242. }
  243. else
  244. {
  245. $redirect_uri = CSocServUtil::GetCurUrl('auth_service_id='.self::ID, array("code"));
  246. }
  247. if($fb->GetAccessToken($redirect_uri) !== false)
  248. {
  249. $res = $fb->getMessages($uid);
  250. }
  251. return $res;
  252. }
  253. public function getProfileUrl($uid)
  254. {
  255. return "http://www.facebook.com/".$uid;
  256. }
  257. public static function SendUserFeed($userId, $message, $messageId)
  258. {
  259. $fb = new CFacebookInterface();
  260. return $fb->SendFeed($userId, $message, $messageId);
  261. }
  262. }
  263. class CFacebookInterface extends CSocServOAuthTransport
  264. {
  265. const SERVICE_ID = "Facebook";
  266. const AUTH_URL = "https://www.facebook.com/dialog/oauth";
  267. const GRAPH_URL = "https://graph.facebook.com";
  268. protected $userId = false;
  269. protected $scope = "email,publish_actions";
  270. public function __construct($appID = false, $appSecret = false, $code=false)
  271. {
  272. if($appID === false)
  273. {
  274. $appID = trim(CSocServFacebook::GetOption("facebook_appid"));
  275. }
  276. if($appSecret === false)
  277. {
  278. $appSecret = trim(CSocServFacebook::GetOption("facebook_appsecret"));
  279. }
  280. parent::__construct($appID, $appSecret, $code);
  281. }
  282. public function GetAuthUrl($redirect_uri)
  283. {
  284. return self::AUTH_URL."?client_id=".$this->appID."&redirect_uri=".urlencode($redirect_uri)."&scope=".$this->getScope()."&display=popup";
  285. }
  286. public function GetAccessToken($redirect_uri)
  287. {
  288. $token = $this->getStorageTokens();
  289. if(is_array($token))
  290. {
  291. $this->access_token = $token["OATOKEN"];
  292. $this->accessTokenExpires = $token["OATOKEN_EXPIRES"];
  293. if($this->checkAccessToken())
  294. {
  295. return true;
  296. }
  297. }
  298. if($this->code === false)
  299. {
  300. return false;
  301. }
  302. $result = CHTTP::sGetHeader(self::GRAPH_URL.'/oauth/access_token?client_id='.$this->appID.'&client_secret='.$this->appSecret.'&redirect_uri='.urlencode($redirect_uri).'&code='.urlencode($this->code), array(), $this->httpTimeout);
  303. $arResult = array();
  304. $arResultLongLive = array();
  305. parse_str($result, $arResult);
  306. if(isset($arResult["access_token"]) && $arResult["access_token"] <> '')
  307. {
  308. $result = CHTTP::sGetHeader(self::GRAPH_URL."/oauth/access_token?grant_type=fb_exchange_token&client_id=".$this->appID."&client_secret=".$this->appSecret."&fb_exchange_token=".$arResult["access_token"], array(), $this->httpTimeout);
  309. parse_str($result, $arResultLongLive);
  310. if(isset($arResultLongLive["access_token"]) && $arResultLongLive["access_token"] <> '')
  311. {
  312. $arResult["access_token"] = $arResultLongLive["access_token"];
  313. $arResult["expires"] = $arResultLongLive["expires"];
  314. $_SESSION["OAUTH_DATA"] = array(
  315. "OATOKEN" => $arResultLongLive["access_token"],
  316. "OATOKEN_EXPIRES" => time() + $arResultLongLive['expires'],
  317. );
  318. }
  319. $this->access_token = $arResult["access_token"];
  320. $this->accessTokenExpires = time() + $arResult["expires"];
  321. return true;
  322. }
  323. return false;
  324. }
  325. public function GetCurrentUser()
  326. {
  327. if($this->access_token === false)
  328. return false;
  329. $result = CHTTP::sGetHeader(self::GRAPH_URL.'/me?access_token='.$this->access_token."&fields=picture,id,name,first_name,last_name,gender,birthday,email", array(), $this->httpTimeout);
  330. if(!defined("BX_UTF"))
  331. $result = CharsetConverter::ConvertCharset($result, "utf-8", LANG_CHARSET);
  332. return CUtil::JsObjectToPhp($result);
  333. }
  334. public function GetAppInfo()
  335. {
  336. if($this->access_token === false)
  337. return false;
  338. $h = new \Bitrix\Main\Web\HttpClient();
  339. $h->setTimeout($this->httpTimeout);
  340. $result = $h->get(self::GRAPH_URL.'/debug_token?input_token='.$this->access_token.'&access_token='.$this->appID."|".$this->appSecret);
  341. $result = \Bitrix\Main\Web\Json::decode($result);
  342. if($result["data"]["app_id"])
  343. {
  344. $result["id"] = $result["data"]["app_id"];
  345. }
  346. return $result;
  347. }
  348. public function GetCurrentUserFriends($limit, &$next)
  349. {
  350. if($this->access_token === false)
  351. return false;
  352. if(empty($next))
  353. {
  354. $url = self::GRAPH_URL.'/me/friends?access_token='.$this->access_token."&fields=picture,id,name,first_name,last_name,gender,birthday,email";
  355. if($limit > 0)
  356. {
  357. $url .= "&limit=".intval($limit)."&offset=".intval($next);
  358. }
  359. }
  360. else
  361. {
  362. $url = $next;
  363. }
  364. $result = CHTTP::sGetHeader($url, array(), $this->httpTimeout);
  365. if(!defined("BX_UTF"))
  366. $result = CharsetConverter::ConvertCharset($result, "utf-8", LANG_CHARSET);
  367. $result = CUtil::JsObjectToPhp($result);
  368. if(is_array($result['paging']) && !empty($result['paging']['next']))
  369. {
  370. $next = $result['paging']['next'];
  371. }
  372. else
  373. {
  374. $next = '';
  375. }
  376. return $result;
  377. }
  378. public function SendFeed($socServUserId, $message, $messageId)
  379. {
  380. $isSetOauthKeys = true;
  381. if(!$this->access_token || !$this->userId)
  382. $isSetOauthKeys = self::SetOauthKeys($socServUserId);
  383. if($isSetOauthKeys === false)
  384. {
  385. CSocServMessage::Delete($messageId);
  386. return false;
  387. }
  388. $message = CharsetConverter::ConvertCharset($message, LANG_CHARSET, "utf-8");
  389. $arPost = array("access_token" => $this->access_token, "message"=> $message);
  390. $result = @CHTTP::sPostHeader($this::GRAPH_URL."/".$this->userId."/feed", $arPost, array(), $this->httpTimeout);
  391. if($result !== false)
  392. {
  393. if(!defined("BX_UTF"))
  394. $result = CharsetConverter::ConvertCharset($result, "utf-8", LANG_CHARSET);
  395. return CUtil::JsObjectToPhp($result);
  396. }
  397. else
  398. return false;
  399. }
  400. public function sendMessage($uid, $message)
  401. {
  402. if($this->access_token === false)
  403. return false;
  404. $url = self::GRAPH_URL.'/'.$uid.'/apprequests';
  405. $message = CharsetConverter::ConvertCharset($message, LANG_CHARSET, "utf-8");
  406. $arPost = array("access_token" => $this->access_token, "message"=> $message);
  407. $ob = new \Bitrix\Main\Web\HttpClient();
  408. return $ob->post($url, $arPost);
  409. }
  410. public function getMessages($uid)
  411. {
  412. if($this->access_token === false)
  413. return false;
  414. $url = self::GRAPH_URL.'/'.$uid.'/apprequests?access_token='.$this->access_token;
  415. $ob = new \Bitrix\Main\Web\HttpClient();
  416. return $ob->get($url);
  417. }
  418. private function SetOauthKeys($socServUserId)
  419. {
  420. $dbSocservUser = CSocServAuthDB::GetList(array(), array('ID' => $socServUserId), false, false, array("OATOKEN", "XML_ID"));
  421. while($arOauth = $dbSocservUser->Fetch())
  422. {
  423. $this->access_token = $arOauth["OATOKEN"];
  424. $this->userId = $arOauth["XML_ID"];
  425. }
  426. if(!$this->access_token || !$this->userId)
  427. return false;
  428. return true;
  429. }
  430. }
  431. ?>