BxFaceBookConnectModule.php 11 KB

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