BxIntercomModule.php 10 KB

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