BxIntercomModule.php 12 KB

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