1
0

BxIntercomModule.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  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 Intercom Intercom integration module
  7. * @ingroup UnaModules
  8. *
  9. * @{
  10. */
  11. class BxIntercomModule extends BxDolModule
  12. {
  13. protected $sHostnameAPI = 'https://api.intercom.io';
  14. function __construct(&$aModule)
  15. {
  16. parent::__construct($aModule);
  17. }
  18. public function serviceIntegrationCode ()
  19. {
  20. $sAppId = getParam('bx_intercom_option_app_id');
  21. if (!$sAppId)
  22. return '';
  23. $aSettings = array(
  24. 'app_id' => $sAppId,
  25. 'hide_default_launcher' => ('on' == getParam('bx_intercom_option_hide_launcher') || 'messenger' == bx_get('i')),
  26. 'alignment' => getParam('bx_intercom_option_alignment'),
  27. 'horizontal_padding' => getParam('bx_intercom_option_horizontal_padding'),
  28. 'vertical_padding' => getParam('bx_intercom_option_vertical_padding'),
  29. );
  30. if (isLogged() && ($oProfile = BxDolProfile::getInstance()) && ($oAccountObject = $oProfile->getAccountObject())) {
  31. $aInfo = $oAccountObject->getInfo();
  32. $aSettings['user_id'] = $oAccountObject->id();
  33. $aSettings['name'] = $oProfile->getDisplayName();
  34. $aSettings['email'] = $oAccountObject->getEmail();
  35. $aSettings['created_at'] = $aInfo['added'];
  36. }
  37. bx_alert('bx_intercom', 'integration', 0, 0, array('settings' => &$aSettings));
  38. $sSettings = json_encode($aSettings);
  39. return <<<EOS
  40. <!-- BEGIN Intercom integration -->
  41. <script>
  42. window.intercomSettings = $sSettings;
  43. </script>
  44. <script>(function(){var w=window;var ic=w.Intercom;if(typeof ic==="function"){ic('reattach_activator');ic('update',intercomSettings);}else{var d=document;var i=function(){i.c(arguments)};i.q=[];i.c=function(args){i.q.push(args)};w.Intercom=i;function l(){var s=d.createElement('script');s.type='text/javascript';s.async=true;s.src='https://widget.intercom.io/widget/{$sAppId}';var x=d.getElementsByTagName('script')[0];x.parentNode.insertBefore(s,x);}if(w.attachEvent){w.attachEvent('onload',l);}else{w.addEventListener('load',l,false);}}})()</script>
  45. <!-- END Intercom integration -->
  46. EOS;
  47. }
  48. /**
  49. * remove user from intercom by email or account id
  50. */
  51. public function serviceRemoveAccount($mixed)
  52. {
  53. if (!$mixed)
  54. return false;
  55. if ($mixed && !(int)$mixed) {
  56. $sId = BxDolAccount::getID($mixed);
  57. } else {
  58. $sId = (int)$mixed;
  59. }
  60. $s = $this->_request('/users?user_id=' . $sId, 'DELETE', array(), $sErrorCurl);
  61. if ($sErrorJson = $this->_checkForErrors($s, $sErrorCurl))
  62. return false;
  63. return true;
  64. }
  65. /**
  66. * update user by email or account id
  67. */
  68. public function serviceUpdateAccount($sEmail)
  69. {
  70. if (!$sEmail || !($oAccount = BxDolAccount::getInstance($sEmail)))
  71. return false;
  72. $aUserInfo = $this->_prepareUser($oAccount);
  73. $s = $this->_request('/users', 'POST', $aUserInfo, $sErrorCurl);
  74. if ($sErrorJson = $this->_checkForErrors($s, $sErrorCurl))
  75. return false;
  76. return true;
  77. }
  78. /**
  79. * remove user from intercom by email or account id
  80. */
  81. public function actionAccountRemove($sEmail)
  82. {
  83. if (!isAdmin())
  84. die('{}');
  85. if (!$this->serviceRemoveAccount($sEmail))
  86. die(json_encode(array('error' => true, 'message' => "Delete failed")));
  87. echo json_encode(array('message' => "User was successfully deleted"));
  88. }
  89. /**
  90. * update user by email or account id
  91. */
  92. public function actionAccountUpdate($sEmail)
  93. {
  94. if (!isAdmin())
  95. die('{}');
  96. if (!$this->serviceUpdateAccount($sEmail))
  97. die(json_encode(array('error' => true, 'message' => "Update failed")));
  98. echo json_encode(array('message' => "User was successfully updated"));
  99. }
  100. /**
  101. * Add members in bulk from local database to Intercom
  102. */
  103. public function actionBulkAdd($iLimit = 5000)
  104. {
  105. if (!isAdmin())
  106. die('{}');
  107. set_time_limit(3600);
  108. $aIds = $this->_oDb->getInitialUsers($iLimit);
  109. $aChunks = array_chunk($aIds, 50);
  110. $iTotal = count($aIds);
  111. $iCounter = 0;
  112. foreach ($aChunks as $aIds) {
  113. $aUsers = array();
  114. foreach ($aIds as $iAccountId) {
  115. if (!($oAccount = BxDolAccount::getInstance($iAccountId)))
  116. continue;
  117. if (!($aUserInfo = $this->_prepareUser($oAccount)))
  118. continue;
  119. $aUsers[] = $aUserInfo;
  120. }
  121. $s = $this->_request('/users/bulk', 'POST', array('users' => $aUsers), $sErrorCurl);
  122. if (trim($s) && $sErrorJson = $this->_checkForErrors($s, $sErrorCurl))
  123. die($sErrorJson);
  124. $iCounter += count($aUsers);
  125. header('X-Users-Processed: ' . $iCounter . '/' . $iTotal);
  126. flush();
  127. sleep(1);
  128. }
  129. echo json_encode(array('message' => "{$iCounter} users were successfully added"));
  130. }
  131. /**
  132. * Test query to return number of users registered in intercom
  133. */
  134. public function actionNum()
  135. {
  136. if (!isAdmin())
  137. die('{}');
  138. $s = $this->_request('/users', 'GET', array(), $sErrorCurl);
  139. if ($sErrorJson = $this->_checkForErrors($s, $sErrorCurl))
  140. die($sErrorJson);
  141. $a = json_decode($s);
  142. echo json_encode(array(
  143. 'type' => $a->type,
  144. 'total_count' => $a->total_count,
  145. ));
  146. }
  147. protected function _prepareUser($oAccount)
  148. {
  149. $oProfile = BxDolProfile::getInstanceByAccount($oAccount->id());
  150. if (!$oProfile)
  151. return false;
  152. $aInfoProfile = $oProfile->getInfo();
  153. $aInfoAccount = $oAccount->getInfo();
  154. $aInfoSession = $this->_oDb->getSessionRowByAccountId($oAccount->id());
  155. $aProfilesIds = $oAccount->getProfilesIds();
  156. // membership
  157. $aMembership = BxDolAcl::getInstance()->getMemberMembershipInfo($oProfile->id());
  158. // profiles
  159. $sProfiles = '';
  160. foreach ($aProfilesIds as $iId) {
  161. if (!($o = BxDolProfile::getInstance($iId)))
  162. continue;
  163. $sProfiles .= $o->getDisplayName() . ', ';
  164. }
  165. $sProfiles = trim($sProfiles, ', ');
  166. return array (
  167. 'user_id' => $oAccount->id(),
  168. 'name' => $oProfile->getDisplayName(),
  169. 'email' => $oAccount->getEmail(),
  170. 'unsubscribed_from_emails' => !$aInfoAccount['receive_news'],
  171. 'signed_up_at' => $aInfoAccount['added'],
  172. //'last_seen_ip' => ?,
  173. 'last_request_at' => isset($aInfoSession['date']) ? $aInfoSession['date'] : $aInfoAccount['logged'],
  174. 'custom_attributes' => array (
  175. 'link' => $oProfile->getUrl(),
  176. 'email_confirmed' => $aInfoAccount['email_confirmed'] ? 'yes' : 'no',
  177. 'email_receive_news' => $aInfoAccount['receive_news'] ? 'yes' : 'no',
  178. 'email_receive_updates' => $aInfoAccount['receive_updates'] ? 'yes' : 'no',
  179. 'membership' => _t($aMembership['name']) . (isset($aMembership['date_expires']) && $aMembership['date_expires'] ? ' (expires:' . bx_time_utc($aMembership['date_expires']) . ')' : ''),
  180. 'status' => $aInfoProfile['status'],
  181. 'type' => $aInfoProfile['type'],
  182. 'all profiles' => $sProfiles,
  183. ),
  184. );
  185. }
  186. /**
  187. * @return json error object on error or empty string on success
  188. */
  189. protected function _checkForErrors($s, $sErrorCurl, $sReturnType = 'json')
  190. {
  191. if (!$s)
  192. return $this->_returnErrors(array('error' => 'curl error: ' . $sErrorCurl), $sReturnType);
  193. $a = json_decode($s);
  194. if (null === $a)
  195. return $this->_returnErrors(array('error' => 'json decode failed:' . htmlspecialchars($s)), $sReturnType);
  196. if (0 === strncmp('error', $a->type, 5)) {
  197. $sError = '';
  198. foreach ($a->errors as $o)
  199. $sError .= $o->code . ": " . $o->message . "\n";
  200. return $this->_returnErrors(array('error' => $sError), $sReturnType);
  201. }
  202. return '';
  203. }
  204. protected function _returnErrors($mixed, $sReturnType = 'json')
  205. {
  206. switch ($sReturnType) {
  207. case 'array':
  208. return $mixed;
  209. case 'json':
  210. default:
  211. return json_encode($mixed);
  212. }
  213. }
  214. /**
  215. * Perform JSON request to the API endpoint and get JSON response
  216. * @return false on error
  217. */
  218. protected function _request($sURI, $sMethod = 'GET', $aData = array(), &$sError)
  219. {
  220. $sAppId = getParam('bx_intercom_option_app_id');
  221. $sApiKey = getParam('bx_intercom_option_api_key');
  222. if (!$sAppId || !$sApiKey) {
  223. $sError = "No App ID or API Key";
  224. return false;
  225. }
  226. $r = curl_init();
  227. $aHeaders = array(
  228. 'Accept: application/json',
  229. );
  230. curl_setopt($r, CURLOPT_USERPWD, $sApiKey . ":");
  231. curl_setopt($r, CURLOPT_TIMEOUT, 10);
  232. curl_setopt($r, CURLOPT_URL, $this->sHostnameAPI . $sURI);
  233. curl_setopt($r, CURLOPT_HEADER, 0);
  234. curl_setopt($r, CURLOPT_RETURNTRANSFER, 1);
  235. curl_setopt($r, CURLOPT_FOLLOWLOCATION, 1);
  236. if ('POST' == $sMethod) {
  237. $sDataJson = json_encode($aData);
  238. curl_setopt($r, CURLOPT_POST, true);
  239. curl_setopt($r, CURLOPT_POSTFIELDS, $sDataJson);
  240. $aHeaders = array_merge($aHeaders, array(
  241. 'Content-Type: application/json',
  242. 'Content-Length: ' . strlen($sDataJson)
  243. ));
  244. } elseif ('DELETE' == $sMethod) {
  245. curl_setopt($r, CURLOPT_CUSTOMREQUEST, "DELETE");
  246. }
  247. curl_setopt($r, CURLOPT_HTTPHEADER, $aHeaders);
  248. $sResult = curl_exec($r);
  249. if (false === $sResult) {
  250. $sError = curl_error ($r);
  251. curl_close($r);
  252. return false;
  253. }
  254. curl_close($r);
  255. return $sResult;
  256. }
  257. }
  258. /** @} */