1
0

BxFaceBookConnectModule.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. <?php defined('BX_DOL') or die('hack attempt');
  2. /**
  3. * Copyright (c) UNA, Inc - https://una.io
  4. * MIT License - https://opensource.org/licenses/MIT
  5. *
  6. * @defgroup FacebookConnect Facebook Connect
  7. * @ingroup UnaModules
  8. *
  9. * @{
  10. */
  11. require_once(BX_DIRECTORY_PATH_MODULES . 'boonex/facebook_connect/plugins/graph-sdk/src/Facebook/autoload.php');
  12. class BxFaceBookConnectModule extends BxBaseModConnectModule
  13. {
  14. protected $oFacebook;
  15. protected $sLastError;
  16. /**
  17. * Class constructor ;
  18. *
  19. * @param : $aModule (array) - contain some information about this module;
  20. * [ id ] - (integer) module's id ;
  21. * [ title ] - (string) module's title ;
  22. * [ vendor ] - (string) module's vendor ;
  23. * [ path ] - (string) path to this module ;
  24. * [ uri ] - (string) this module's URI ;
  25. * [ class_prefix ] - (string) this module's php classes file prefix ;
  26. * [ db_prefix ] - (string) this module's Db tables prefix ;
  27. * [ date ] - (string) this module's date installation ;
  28. */
  29. function __construct(&$aModule)
  30. {
  31. parent::__construct($aModule);
  32. // Create our Application instance.
  33. $this -> oFacebook = null;
  34. if ($this -> _oConfig -> mApiID && $this -> _oConfig -> mApiSecret) {
  35. if (!isset($_SESSION))
  36. session_start();
  37. try {
  38. $this -> oFacebook = @new Facebook\Facebook(array(
  39. 'app_id' => $this -> _oConfig -> mApiID,
  40. 'app_secret' => $this -> _oConfig -> mApiSecret,
  41. 'default_graph_version' => 'v2.4',
  42. ));
  43. }
  44. catch (Exception $e) {
  45. $this->_setLastError($e->getMessage());
  46. }
  47. }
  48. }
  49. /**
  50. * Facebook login callback url;
  51. *
  52. * @return (text) - html presentation data;
  53. */
  54. function actionLoginCallback()
  55. {
  56. if (isLogged()) {
  57. header ('Location:' . $this -> _oConfig -> sDefaultRedirectUrl);
  58. exit;
  59. }
  60. require_once(BX_DIRECTORY_PATH_INC . 'design.inc.php');
  61. bx_import('BxDolLanguages');
  62. if (!$this -> _oConfig -> mApiID || !$this -> _oConfig -> mApiSecret)
  63. $this->_setLastError(_t('_bx_facebook_profile_error_api_keys'));
  64. if ($sError = $this->_setAccessToken())
  65. $this->_setLastError($sError);
  66. if (!$this->_getLastError()) {
  67. //we already logged in facebook
  68. try {
  69. $oResponse = $this -> oFacebook -> get('/me?fields=' . $this -> _oConfig -> sFaceBookFields);
  70. $aFacebookProfileInfo = $oResponse -> getDecodedBody();
  71. $aFacebookProfileInfo['nick_name'] = $aFacebookProfileInfo['name'];
  72. } catch (Facebook\Exceptions\FacebookResponseException $e) {
  73. $this->_setLastError($e->getMessage());
  74. } catch (Facebook\Exceptions\FacebookSDKException $e) {
  75. $this->_setLastError($e->getMessage());
  76. }
  77. //process profile info
  78. if($aFacebookProfileInfo) {
  79. // try define user id
  80. $iProfileId = $this -> _oDb
  81. -> getProfileId($aFacebookProfileInfo['id']);
  82. if ($iProfileId) {
  83. $this -> setLogged($iProfileId);
  84. }
  85. else {
  86. // process profile's nickname
  87. $aFacebookProfileInfo['nick_name'] = $this
  88. -> _proccesNickName($aFacebookProfileInfo['first_name']);
  89. // try to get profile's image
  90. if ($oFacebookProfileImageResponse = $this -> oFacebook -> get('/me/picture?type=large&redirect=false')) {
  91. $aFacebookProfileImage = $oFacebookProfileImageResponse -> getDecodedBody();
  92. $aFacebookProfileInfo['picture'] = isset($aFacebookProfileImage['data']['url']) && !$aFacebookProfileImage['data']['is_silhouette']
  93. ? $aFacebookProfileImage['data']['url']
  94. : '';
  95. }
  96. // create new profile
  97. $this -> _createProfile($aFacebookProfileInfo);
  98. }
  99. } else {
  100. // FB profile info is not defined;
  101. $this->_setLastError(_t('_sys_connect_profile_error_info'));
  102. }
  103. }
  104. $this -> _oTemplate -> dislayPageError();
  105. }
  106. /**
  107. * Generare facebook login form;
  108. *
  109. * @return (text) - html presentation data;
  110. */
  111. function actionLoginForm()
  112. {
  113. if (isLogged()) {
  114. header ('Location:' . $this -> _oConfig -> sDefaultRedirectUrl);
  115. exit;
  116. }
  117. if (!$this -> _oConfig -> mApiID || !$this -> _oConfig -> mApiSecret) {
  118. require_once(BX_DIRECTORY_PATH_INC . 'design.inc.php');
  119. bx_import('BxDolLanguages');
  120. $this->_setLastError(_t('_bx_facebook_profile_error_api_keys'));
  121. }
  122. else {
  123. $oFacebookRedirectLoginHelper = $this -> oFacebook -> getRedirectLoginHelper();
  124. //redirect to facebook login form
  125. $sLoginUrl = $oFacebookRedirectLoginHelper->getLoginUrl(
  126. $this -> _oConfig -> aFaceBookReqParams['redirect_uri'],
  127. explode(',', $this -> _oConfig -> aFaceBookReqParams['scope'])
  128. );
  129. header('location: ' . $sLoginUrl);
  130. exit;
  131. }
  132. $this -> _oTemplate -> dislayPageError();
  133. }
  134. function serviceLastError($bShowEmpty = true)
  135. {
  136. return $this->sLastError ? MsgBox($this->sLastError) : ($bShowEmpty ? MsgBox(_t('_Empty')): '');
  137. }
  138. /**
  139. * Make friends
  140. *
  141. * @param $iProfileId integer
  142. * @return void
  143. */
  144. protected function _makeFriends($iProfileId)
  145. {
  146. if (!$this->_oConfig->bAutoFriends)
  147. return;
  148. $oConnFrinds = BxDolConnection::getObjectInstance('sys_profiles_friends');
  149. if (!$oConnFrinds)
  150. return;
  151. try {
  152. //get friends from facebook
  153. $oFriendsResponse = $this -> oFacebook -> get('/me/friends?limit=50');
  154. } catch(Facebook\Exceptions\FacebookResponseException $e) {
  155. return;
  156. } catch(Facebook\Exceptions\FacebookSDKException $e) {
  157. return;
  158. }
  159. // paginate through the result
  160. $oPagesEdge = $oFriendsResponse->getGraphEdge();
  161. do {
  162. foreach ($oPagesEdge as $oPage) {
  163. $aFriend = $oPage->asArray();
  164. if (!($iLocalProfileId = $this->_oDb->getProfileId($aFriend['id'])))
  165. continue;
  166. $oConnFrinds->actionAdd($iProfileId, $iLocalProfileId);
  167. $oConnFrinds->actionAdd($iLocalProfileId, $iProfileId);
  168. }
  169. } while ($oPagesEdge = $this->oFacebook->next($oPagesEdge));
  170. }
  171. /**
  172. * @param $aProfileInfo - remote profile info
  173. * @param $sAlternativeName - suffix to add to NickName to make it unique
  174. * @return profile array info, ready for the local database
  175. */
  176. protected function _convertRemoteFields($aProfileInfo, $sAlternativeName = '')
  177. {
  178. // define user's country and city
  179. $aLocation = array();
  180. if (isset($aProfileInfo['location']['name']))
  181. $aLocation = $aProfileInfo['location']['name'];
  182. elseif (isset($aProfileInfo['hometown']['name']))
  183. $aLocation = $aProfileInfo['hometown']['name'];
  184. if($aLocation) {
  185. $aCountryInfo = explode(',', $aLocation);
  186. $sCountry = $this -> _oDb -> getCountryCode( trim($aCountryInfo[1]) );
  187. $sCity = trim($aCountryInfo[0]);
  188. //set default country name, especially for American brothers
  189. if($sCity && !$sCountry) {
  190. $sCountry = $this -> _oConfig -> sDefaultCountryCode;
  191. }
  192. }
  193. // fill array with all needed values
  194. $sGender = '';
  195. if (isset($aProfileInfo['gender']) && ('male' == $aProfileInfo['gender'] || 'female' == $aProfileInfo['gender']))
  196. $sGender = ('male' == $aProfileInfo['gender'] ? 1 : 2);
  197. $sBirthday = '';
  198. if (isset($aProfileInfo['birthday']) && preg_match('/(\d{2})\/(\d{2})\/(\d{2})/', $aProfileInfo['birthday'], $aMatch))
  199. $aProfileInfo['birthday'] = $aMatch[3] . '-' . $aMatch[1] . '-' . $aMatch[2];
  200. $aProfileFields = array(
  201. 'name' => $aProfileInfo['nick_name'] . $sAlternativeName,
  202. 'email' => isset($aProfileInfo['email']) ? $aProfileInfo['email'] : '',
  203. 'gender' => $sGender,
  204. 'birthday' => $sBirthday,
  205. 'fullname' => (isset($aProfileInfo['first_name']) ? $aProfileInfo['first_name'] : '') . (isset($aProfileInfo['last_name']) ? ' ' . $aProfileInfo['last_name'] : ''),
  206. 'description' => clear_xss(isset($aProfileInfo['bio']) ? $aProfileInfo['bio'] : ''),
  207. 'interests' => clear_xss(isset($aProfileInfo['interests']) ? $aProfileInfo['interests'] : ''),
  208. 'religion' => clear_xss(isset($aProfileInfo['religion']) ? $aProfileInfo['religion'] : ''),
  209. 'country' => isset($sCountry) ? $sCountry : '',
  210. 'city' => isset($sCity) ? $sCity : '',
  211. 'picture' => $aProfileInfo['picture'],
  212. 'allow_view_to' => getParam('bx_facebook_connect_privacy'),
  213. );
  214. return $aProfileFields;
  215. }
  216. /**
  217. * Function will clear all unnecessary sybmols from profile's nickname;
  218. *
  219. * @param : $sProfileName (string) - profile's nickname;
  220. * @return : (string) - cleared nickname;
  221. */
  222. protected function _proccesNickName($sProfileName)
  223. {
  224. $sProfileName = preg_replace("/^http:\/\/|^https:\/\/|\/$/", '', $sProfileName);
  225. $sProfileName = str_replace('/', '_', $sProfileName);
  226. $sProfileName = str_replace('.', '-', $sProfileName);
  227. return $sProfileName;
  228. }
  229. protected function _setAccessToken()
  230. {
  231. $oFacebookRedirectLoginHelper = $this -> oFacebook -> getRedirectLoginHelper();
  232. try {
  233. $sAccessToken = $oFacebookRedirectLoginHelper->getAccessToken();
  234. } catch(Facebook\Exceptions\FacebookResponseException $e) {
  235. // When Graph returns an error
  236. return $e->getMessage();
  237. } catch(Facebook\Exceptions\FacebookSDKException $e) {
  238. // When validation fails or other local issues
  239. return $e->getMessage();
  240. }
  241. if (!isset($sAccessToken))
  242. return $oFacebookRedirectLoginHelper->getErrorDescription() ? $oFacebookRedirectLoginHelper->getErrorDescription() : (bx_get('error_message') ? rawurldecode(bx_get('error_message')) : _t('_error occured'));
  243. $this -> oFacebook -> setDefaultAccessToken($sAccessToken);
  244. return '';
  245. }
  246. protected function _setLastError($s)
  247. {
  248. $this->sLastError = $s;
  249. }
  250. protected function _getLastError()
  251. {
  252. return $this->sLastError;
  253. }
  254. }
  255. /** @} */