BxFaceBookConnectModule.php 11 KB

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