BxLinkedinModule.php 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  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 LinkedInConnect LinkedIn Connect
  7. * @ingroup UnaModules
  8. *
  9. * @{
  10. */
  11. class BxLinkedinModule extends BxBaseModConnectModule
  12. {
  13. function __construct(&$aModule)
  14. {
  15. parent::__construct($aModule);
  16. }
  17. /**
  18. * Redirect to remote site login form
  19. *
  20. * @return n/a - redirect or HTML page in case of error
  21. */
  22. function actionStart()
  23. {
  24. if (isLogged())
  25. $this->_redirect ($this -> _oConfig -> sDefaultRedirectUrl);
  26. if (!$this->_oConfig->sApiID || !$this->_oConfig->sApiSecret) {
  27. require_once(BX_DIRECTORY_PATH_INC . 'design.inc.php');
  28. bx_import('BxDolLanguages');
  29. $sCode = MsgBox( _t('_bx_linkedin_profile_error_api_keys') );
  30. $this->_oTemplate->getPage(_t('_bx_linkedin'), $sCode);
  31. }
  32. else {
  33. // define redirect URL to the remote site
  34. $sUrl = bx_append_url_params($this->_oConfig->sOauthUrl . '/authorization', array(
  35. 'response_type' => 'code',
  36. 'client_id' => $this->_oConfig->sApiID,
  37. 'redirect_uri' => $this->_oConfig->sPageHandle,
  38. 'scope' => $this->_oConfig->sScope,
  39. 'state' => $this->_genToken(),
  40. ));
  41. $this->_redirect($sUrl);
  42. }
  43. }
  44. function actionHandle()
  45. {
  46. require_once(BX_DIRECTORY_PATH_INC . 'design.inc.php');
  47. // check CSRF token
  48. if ($this->_getToken() != bx_get('state')) {
  49. $this->_oTemplate->getPage(_t('_Error'), MsgBox(_t('_sys_connect_state_invalid')));
  50. return;
  51. }
  52. // check code
  53. $sCode = bx_get('code');
  54. if (!$sCode || bx_get('error')) {
  55. $sErrorDescription = bx_get('error_description') ? bx_get('error_description') : _t('_error occured');
  56. $this->_oTemplate->getPage(_t('_Error'), MsgBox($sErrorDescription));
  57. return;
  58. }
  59. // make request for token
  60. $s = bx_file_get_contents($this->_oConfig->sOauthUrl . '/accessToken', array(
  61. 'client_id' => $this->_oConfig->sApiID,
  62. 'client_secret' => $this->_oConfig->sApiSecret,
  63. 'grant_type' => 'authorization_code',
  64. 'code' => $sCode,
  65. 'redirect_uri' => $this->_oConfig->sPageHandle,
  66. ), 'post', array ('Content-Type: application/x-www-form-urlencoded'));
  67. // handle error
  68. if (!$s || NULL === ($aResponse = json_decode($s, true)) || !isset($aResponse['access_token']) || isset($aResponse['error'])) {
  69. $sErrorDescription = isset($aResponse['error_description']) ? $aResponse['error_description'] : _t('_error occured');
  70. $this->_oTemplate->getPage(_t('_Error'), MsgBox($sErrorDescription));
  71. return;
  72. }
  73. // get the data, especially access_token
  74. $sAccessToken = $aResponse['access_token'];
  75. $sExpiresIn = $aResponse['expires_in'];
  76. $sExpiresAt = new \DateTime('+' . $sExpiresIn . ' seconds');
  77. // request info about profile
  78. $s = bx_file_get_contents($this->_oConfig->sApiUrl . '/me?projection=(' . $this->_oConfig->sFields . ')', array(), 'get', array(
  79. 'Authorization: Bearer ' . $sAccessToken,
  80. ));
  81. // handle error
  82. if (!$s || NULL === ($aResponse = json_decode($s, true)) || !$aResponse || (isset($aResponse['status']) && ($aResponse['status'] < 200 || $aResponse['status'] > 299))) {
  83. $sErrorDescription = isset($aResponse['message']) ? $aResponse['message'] : _t('_error occured');
  84. $this->_oTemplate->getPage(_t('_Error'), MsgBox($sErrorDescription));
  85. return;
  86. }
  87. // request email
  88. $s = bx_file_get_contents($this->_oConfig->sApiUrl . '/emailAddress?q=members&projection=(elements*(handle~))', array(), 'get', array(
  89. 'Authorization: Bearer ' . $sAccessToken,
  90. ));
  91. // handle error
  92. if (!$s || NULL === ($aResponseEmail = json_decode($s, true)) || !$aResponseEmail || (isset($aResponseEmail['status']) && ($aResponseEmail['status'] < 200 || $aResponseEmail['status'] > 299))) {
  93. $sErrorDescription = isset($aResponseEmail['message']) ? $aResponseEmail['message'] : _t('_error occured');
  94. $this->_oTemplate->getPage(_t('_Error'), MsgBox($sErrorDescription));
  95. return;
  96. }
  97. $aRemoteProfileInfo = array_merge($aResponse, $aResponseEmail);
  98. if ($aRemoteProfileInfo) {
  99. // check if user logged in before
  100. $iLocalProfileId = $this->_oDb->getProfileId($aRemoteProfileInfo['id']);
  101. if ($iLocalProfileId && $oProfile = BxDolProfile::getInstance($iLocalProfileId)) {
  102. // user already exists
  103. $this->setLogged($oProfile ->id());
  104. }
  105. else {
  106. // register new user
  107. $this->_createProfile($aRemoteProfileInfo);
  108. }
  109. }
  110. else {
  111. $this->_oTemplate->getPage(_t('_Error'), MsgBox(_t('_sys_connect_profile_error_info')));
  112. }
  113. }
  114. /**
  115. * @param $aProfileInfo - remote profile info
  116. * @param $sAlternativeName - suffix to add to NickName to make it unique
  117. * @return profile array info, ready for the local database
  118. */
  119. protected function _convertRemoteFields($aProfileInfo, $sAlternativeName = '')
  120. {
  121. $aProfileFields = $aProfileInfo;
  122. $aProfileFields['name'] = $this->_getLocalizedValue($aProfileInfo['firstName']);
  123. $aProfileFields['fullname'] = $this->_getLocalizedValue($aProfileInfo['firstName']) . ' ' . (isset($aProfileInfo['lastName']) ? $this->_getLocalizedValue($aProfileInfo['lastName']) : '');
  124. $aProfileFields['email'] = isset($aProfileInfo['elements']) ? $this->_getEmail($aProfileInfo['elements']) : '';
  125. $aProfileFields['picture'] = isset($aProfileInfo['profilePicture']) ? $this->_getImageUrl($aProfileInfo['profilePicture']) : '';
  126. $aProfileFields['allow_view_to'] = getParam('bx_linkedin_privacy');
  127. return $aProfileFields;
  128. }
  129. protected function _getLocalizedValue($a)
  130. {
  131. $sLocale = isset($a['preferredLocale']) ? $a['preferredLocale']['language'] . '_' . $a['preferredLocale']['country'] : false;
  132. if (isset($a['localized']) && isset($a['localized'][$sLocale]))
  133. return $a['localized'][$sLocale];
  134. return false;
  135. }
  136. protected function _getEmail($a)
  137. {
  138. $r = array_pop($a);
  139. if (!isset($r['handle~']) || !isset($r['handle~']['emailAddress']))
  140. return false;
  141. return $r['handle~']['emailAddress'];
  142. }
  143. protected function _getImageUrl($a)
  144. {
  145. if (!isset($a['displayImage~']))
  146. return false;
  147. $aBiggestImage = false;
  148. foreach ($a['displayImage~']['elements'] as $r) {
  149. if (empty($r['identifiers']) || !isset($r['data']) || !isset($r['data']['com.linkedin.digitalmedia.mediaartifact.StillImage']) || !isset($r['data']['com.linkedin.digitalmedia.mediaartifact.StillImage']['storageSize']))
  150. continue;
  151. if (!$aBiggestImage || $r['data']['com.linkedin.digitalmedia.mediaartifact.StillImage']['storageSize']['width'] > $aBiggestImage['width']) {
  152. foreach ($r['identifiers'] as $rr) {
  153. if ('EXTERNAL_URL' == $rr['identifierType']) {
  154. $aBiggestImage = array(
  155. 'width' => $r['data']['com.linkedin.digitalmedia.mediaartifact.StillImage']['storageSize']['width'],
  156. 'url' => $rr['identifier'],
  157. );
  158. break;
  159. }
  160. }
  161. }
  162. }
  163. if (!$aBiggestImage)
  164. return false;
  165. return $aBiggestImage['url'];
  166. }
  167. }
  168. /** @} */