BxIntercomModule.php 12 KB

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