BxIntercomModule.php 9.9 KB

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