BxIntercomModule.php 10 KB

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