BxBaseModConnectModule.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  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 BaseConnect Base classes for OAuth connect modules
  7. * @ingroup UnaModules
  8. *
  9. * @{
  10. */
  11. class BxBaseModConnectModule extends BxBaseModGeneralModule
  12. {
  13. function __construct(&$aModule)
  14. {
  15. parent::__construct($aModule);
  16. }
  17. public function serviceGetSafeServices()
  18. {
  19. return array();
  20. }
  21. public function serviceGetProfilesModules ()
  22. {
  23. $aModules = array();
  24. $a = BxDolService::call('system', 'get_profiles_modules', array(), 'TemplServiceProfiles');
  25. foreach ($a as &$aModule)
  26. $aModules[$aModule['name']] = $aModule['title'];
  27. return $aModules;
  28. }
  29. public function serviceGetPrivacyGroups ()
  30. {
  31. $oPrivacyQuery = new BxDolPrivacyQuery();
  32. $a = $oPrivacyQuery->getGroupsBy(array('type' => 'active'));
  33. $aGroups = array();
  34. foreach ($a as $r) {
  35. if (!(int)$r['active'])
  36. continue;
  37. $aGroups[$r['id']] = _t($r['title']);
  38. }
  39. return $aGroups;
  40. }
  41. /**
  42. * Logged profile
  43. *
  44. * @param $iProfileId integer
  45. * @param $sPassword string
  46. * @param $sCallbackUrl
  47. * @param $bRedirect boolean
  48. * @return void
  49. */
  50. function setLogged($iProfileId, $sCallbackUrl = '', $bRedirect = true, $bRememberMe = false)
  51. {
  52. $oProfile = BxDolProfile::getInstance($iProfileId);
  53. bx_login($oProfile->getAccountId(), $bRememberMe);
  54. if ($bRedirect) {
  55. //set redirect from the session if it was added
  56. $oSession = BxDolSession::getInstance();
  57. $sSessionKey = $this->_oConfig->getName() . '_relocate';
  58. if ($oSession->isValue($sSessionKey))
  59. $sCallbackUrl = $sCallbackUrl ? $sCallbackUrl : $oSession->getValue($sSessionKey);
  60. $sCallbackUrl = $sCallbackUrl ? $sCallbackUrl : $this -> _oConfig -> sDefaultRedirectUrl;
  61. if($this->_bIsApi)
  62. return [bx_api_get_block('redirect', ['uri' => bx_api_get_relative_url($sCallbackUrl)])];
  63. header('Location: ' . $sCallbackUrl);
  64. /*
  65. // another way to redirect with "Please wait" message
  66. BxDolTemplate::getInstance()->setPageNameIndex (BX_PAGE_TRANSITION);
  67. BxDolTemplate::getInstance()->setPageHeader (_t('_Please Wait'));
  68. BxDolTemplate::getInstance()->setPageContent ('page_main_code', MsgBox(_t('_Please Wait')));
  69. BxDolTemplate::getInstance()->setPageContent ('url_relocate', bx_html_attribute($sCallbackUrl, BX_ESCAPE_STR_QUOTE));
  70. BxDolTemplate::getInstance()->getPageCode();
  71. */
  72. exit;
  73. }
  74. }
  75. /**
  76. * Create new profile;
  77. *
  78. * @param : $aProfileInfo (array) - remote profile's information;
  79. *
  80. * @param : $sAlternativeName (string) - profiles alternative nickname;
  81. */
  82. function _createProfile($aProfileInfo, $sAlternativeName = '')
  83. {
  84. $mixed = $this->_createProfileRaw($aProfileInfo, $sAlternativeName);
  85. /**
  86. * @hooks
  87. * @hookdef hook-bx_base_connect-profile_created '{module_name}', 'profile_created' - hook after a profile was created
  88. * - $unit_name - module name
  89. * - $action - equals `profile_created`
  90. * - $object_id - not used
  91. * - $sender_id - not used
  92. * - $extra_params - array of additional params with the following array keys:
  93. * - `override_result` - [string] or [array] by ref, result of profile creation, can be overridden in hook processing. If `string` then show error, if `array` with `join_page_redirect` key then show Create Account page, if `array` with `profile_id` key then redirect to profile page
  94. * - `remote_profile_info` - [array] array with remote profile info
  95. * @hook @ref hook-bx_base_connect-profile_created
  96. */
  97. bx_alert($this->getName(), 'profile_created', 0, 0, [
  98. 'override_result' => &$mixed,
  99. 'remote_profile_info' => $aProfileInfo
  100. ]);
  101. // display error
  102. if (is_string($mixed)) {
  103. if($this->_bIsApi)
  104. return [bx_api_get_msg($mixed)];
  105. $this->_oTemplate->getPage(_t($this->_oConfig->sDefaultTitleLangKey), DesignBoxContent(_t($this->_oConfig->sDefaultTitleLangKey), MsgBox($mixed)));
  106. exit;
  107. }
  108. // display join page
  109. if (is_array($mixed) && isset($mixed['join_page_redirect'])) {
  110. if($this->_bIsApi)
  111. return []; //--- Isn't currently supported for API.
  112. $this->_getJoinPage($mixed['profile_fields'], $mixed['remote_profile_info']['id']);
  113. exit;
  114. }
  115. // continue profile creation
  116. if (is_array($mixed) && isset($mixed['profile_id'])) {
  117. $iProfileId = (int)$mixed['profile_id'];
  118. $sRedirectUrl = $this->_getRedirectUrl($iProfileId, $mixed['existing_profile']);
  119. if($this->_bIsApi)
  120. return [bx_api_get_block('redirect', ['uri' => bx_api_get_relative_url($sRedirectUrl)])];
  121. //redirect to other page
  122. header('location:' . $sRedirectUrl);
  123. exit;
  124. }
  125. if($this->_bIsApi)
  126. return [bx_api_get_msg(_t('_Error Occured'))];
  127. $this->_oTemplate->getPage( _t($this->_oConfig->sDefaultTitleLangKey), MsgBox(_t('_Error Occured')) );
  128. exit;
  129. }
  130. /**
  131. * @param $aProfileInfo - remote profile info
  132. * @param $sAlternativeName - suffix to add to NickName to make it unique
  133. * @return profile array info, ready for the local database
  134. */
  135. protected function _convertRemoteFields($aProfileInfo, $sAlternativeName = '')
  136. {
  137. }
  138. /**
  139. * Create new profile;
  140. *
  141. * @param : $aProfileInfo (array) - remote profile's information;
  142. *
  143. * @param : $sAlternativeName (string) - profiles alternative nickname;
  144. * @return : error string or error or request invite form or profile info array on success
  145. */
  146. function _createProfileRaw($aProfileInfo, $sAlternativeName = '', $isAutoFriends = true, $isSetLoggedIn = true)
  147. {
  148. // join by invite only
  149. if (BxDolRequest::serviceExists('bx_invites', 'account_add_form_check') && $sCode = BxDolService::call('bx_invites', 'account_add_form_check'))
  150. return $sCode;
  151. // convert fields to unique format
  152. $aFieldsProfile = $aFieldsAccount = $this->_convertRemoteFields($aProfileInfo, $sAlternativeName);
  153. /**
  154. * @hooks
  155. * @hookdef hook-bx_base_connect-fields_converted '{module_name}', 'fields_converted' - hook before a profile was created, which allows to modify account and/or profile fields before creation
  156. * - $unit_name - module name
  157. * - $action - equals `fields_converted`
  158. * - $object_id - not used
  159. * - $sender_id - not used
  160. * - $extra_params - array of additional params with the following array keys:
  161. * - `override_profile_fields` - [array] by ref, profile fields, can be overridden in hook processing
  162. * - `override_account_fields` - [array] by ref, account fields, can be overridden in hook processing
  163. * - `remote_profile_info` - [array] array with remote profile info
  164. * @hook @ref hook-bx_base_connect-fields_converted
  165. */
  166. bx_alert($this->getName(), 'fields_converted', 0, 0, [
  167. 'override_profile_fields' => &$aFieldsProfile,
  168. 'override_account_fields' => &$aFieldsAccount,
  169. 'remote_profile_info' => $aProfileInfo
  170. ]);
  171. if (empty($aFieldsProfile['email']))
  172. return _t('_Incorrect Email');
  173. // prepare fields for particular module
  174. $aFieldsAccount = BxDolService::call('system', 'prepare_fields', array($aFieldsAccount));
  175. $aFieldsProfile = BxDolService::call($this->_oConfig->sProfilesModule, 'prepare_fields', array($aFieldsProfile));
  176. // check fields existence in Account
  177. $oFormHelperAccount = BxDolService::call('system', 'forms_helper');
  178. $oFormAccount = $oFormHelperAccount->getObjectFormAdd();
  179. foreach ($aFieldsAccount as $sKey => $mValue) {
  180. if (!$oFormAccount->isFieldExist($sKey))
  181. unset($aFieldsAccount[$sKey]);
  182. }
  183. // check fields existence in Profile
  184. if ('system' != $this->_oConfig->sProfilesModule && $oFormHelperProfile = BxDolService::call($this->_oConfig->sProfilesModule, 'forms_helper')) {
  185. $oFormProfile = $oFormHelperProfile->getObjectFormEdit();
  186. foreach ($aFieldsProfile as $sKey => $mValue) {
  187. if (!$oFormProfile->isFieldExist($sKey))
  188. unset($aFieldsProfile[$sKey]);
  189. }
  190. }
  191. // antispam check
  192. $sErrorMsg = '';
  193. $bSetPendingApproval = false;
  194. /**
  195. * @hooks
  196. * @hookdef hook-account-check_join 'account', 'check_join' - hook to check email address for spam
  197. * - $unit_name - equals `account`
  198. * - $action - equals `check_join`
  199. * - $object_id - not used
  200. * - $sender_id - not used
  201. * - $extra_params - array of additional params with the following array keys:
  202. * - `error_msg` - [string] by ref, error message, can be overridden in hook processing
  203. * - `email` - [string] email address to check
  204. * - `approve` - [boolean] by ref, pending approval status for created profile, can be overridden in hook processing
  205. * @hook @ref hook-account-check_join
  206. */
  207. bx_alert('account', 'check_join', 0, false, [
  208. 'error_msg' => &$sErrorMsg,
  209. 'email' => $aFieldsAccount['email'],
  210. 'approve' => &$bSetPendingApproval
  211. ]);
  212. if ($sErrorMsg)
  213. return $sErrorMsg;
  214. // check if user with the same email already exists
  215. $oExistingAccount = $this->_getExistingAccount($aProfileInfo, $aFieldsAccount, $aFieldsProfile);
  216. // check redirect page
  217. if ('join' == $this->_oConfig->sRedirectPage && !$oExistingAccount)
  218. return array('remote_profile_info' => $aProfileInfo, 'profile_fields' => $aFieldsAccount, 'join_page_redirect' => true);
  219. // create new profile
  220. if ($oExistingAccount) {
  221. if (!($oExistingProfile = BxDolProfile::getInstanceByAccount($oExistingAccount->id(), true)))
  222. return _t('_sys_txt_error_account_creation');
  223. $iProfileId = $oExistingProfile->id();
  224. $this->setLogged($iProfileId);
  225. }
  226. else {
  227. // create account
  228. $aFieldsAccount['password'] = $this->_genPwd($aProfileInfo, $aFieldsAccount, $aFieldsProfile);
  229. if (!($iAccountId = $oFormAccount->insert($aFieldsAccount)))
  230. return _t('_sys_txt_error_account_creation');
  231. $isSetPendingApproval = $this->_isSetPendingApprovalAccount($aProfileInfo, $aFieldsAccount, $aFieldsProfile);
  232. $iAccountProfileId = $oFormHelperAccount->onAccountCreated ($iAccountId, $isSetPendingApproval, BX_PROFILE_ACTION_EXTERNAL);
  233. // create profile
  234. if (isset($oFormProfile) && $oFormProfile) {
  235. $aFieldsProfile['author'] = $iAccountProfileId;
  236. $aFieldsProfile['picture'] = $this->_processImage($aFieldsProfile, $iAccountProfileId, $oFormHelperProfile);
  237. $_POST['picture'] = $aFieldsProfile['picture']; // set POST variable to correctly process images in processFiles method in form object
  238. if (!($iContentId = $oFormProfile->insert($aFieldsProfile)))
  239. return _t('_sys_txt_error_account_creation');
  240. $isSetPendingApprovalProfile = $this->_isSetPendingApprovalProfile($aProfileInfo, $oFormHelperProfile, $aFieldsAccount, $aFieldsProfile);
  241. $oFormHelperProfile->setAutoApproval($isSetPendingApprovalProfile);
  242. if ($sErrorMsg = $oFormHelperProfile->onDataAddAfter ($iAccountId, $iContentId))
  243. return $sErrorMsg;
  244. $oProfile = BxDolProfile::getInstanceByAccount($iAccountId, true);
  245. $iProfileId = $oProfile->id();
  246. }
  247. else {
  248. $iProfileId = $iAccountProfileId;
  249. }
  250. $oAccount = BxDolAccount::getInstance($iAccountId);
  251. if ($oAccount)
  252. $oAccount->updateEmailConfirmed($this->_oConfig->isAlwaysConfirmEmail);
  253. // send email with password
  254. if ($this->_oConfig->bSendPasswordGenerated)
  255. sendMailTemplate($this->_oConfig->sEmailTemplatePasswordGenerated, $iAccountId, $iProfileId, array('password' => $aFieldsAccount['password']), BX_EMAIL_SYSTEM);
  256. }
  257. // remember remote profile id for created member
  258. $this ->_oDb->saveRemoteId($iProfileId, $aProfileInfo['id']);
  259. // auto-friend members if they are already friends on remote site
  260. if ($isAutoFriends && method_exists($this, '_makeFriends'))
  261. $this->_makeFriends($iProfileId);
  262. return array('remote_profile_info' => $aProfileInfo, 'profile_id' => $iProfileId, 'existing_profile' => $oExistingAccount ? true : false);
  263. }
  264. protected function _processImage($aFieldsProfile, $iAccountProfileId, $oFormHelperProfile)
  265. {
  266. if (!isset($aFieldsProfile['picture']) || !$aFieldsProfile['picture'])
  267. return 0;
  268. if (!($oStorage = $oFormHelperProfile->getObjectStorage()))
  269. return 0;
  270. if (!($iFileId = $oStorage->storeFileFromUrl($aFieldsProfile['picture'], false, $iAccountProfileId)))
  271. return 0;
  272. return $iFileId;
  273. }
  274. /**
  275. * Get join page
  276. *
  277. * @param $aProfileFields array
  278. * @param $iRemoteProfileId remote profile id
  279. * @return void
  280. */
  281. function _getJoinPage($aProfileFields, $iRemoteProfileId)
  282. {
  283. bx_import('BxDolSession');
  284. $oSession = BxDolSession::getInstance();
  285. $oSession->setValue($this->_oConfig->sSessionUid, $iRemoteProfileId);
  286. $oPage = BxDolPage::getObjectInstanceByURI('create-account');
  287. BxBaseAccountForms::$PROFILE_FIELDS = $aProfileFields;
  288. $this->_oTemplate->getPage(false, $oPage->getCode());
  289. }
  290. /**
  291. * get redirect URL
  292. *
  293. * @param $iProfileId integer - profile ID
  294. * @return string redirect URL
  295. */
  296. function _getRedirectUrl($iProfileId, $isExistingProfile = false)
  297. {
  298. $sRedirectUrl = $this->_oConfig->sDefaultRedirectUrl;
  299. switch($this->_oConfig->sRedirectPage) {
  300. case 'index':
  301. $sRedirectUrl = BX_DOL_URL_ROOT;
  302. break;
  303. case 'settings':
  304. if (!$isExistingProfile) {
  305. $sRedirectUrl = bx_absolute_url(BxDolPermalinks::getInstance()->permalink('page.php?i=account-settings-email'));
  306. break;
  307. }
  308. case 'dashboard':
  309. default:
  310. $sRedirectUrl = bx_absolute_url(BxDolPermalinks::getInstance()->permalink('page.php?i=dashboard'));
  311. break;
  312. }
  313. return $sRedirectUrl;
  314. }
  315. protected function _redirect($sUrl, $iStatus = 302)
  316. {
  317. header("Location:{$sUrl}", true, $iStatus);
  318. exit;
  319. }
  320. protected function _genToken($bReturn = false)
  321. {
  322. $oSession = BxDolSession::getInstance();
  323. $sPrefix = $this->getName();
  324. $iCsrfTokenLifetime = 3600;
  325. if ($oSession->getValue($sPrefix . '_token') === false || (time() - (int)$oSession->getValue($sPrefix . '_token_time') > $iCsrfTokenLifetime)) {
  326. $sToken = genRndPwd(20, false);
  327. $oSession->setValue($sPrefix . '_token', $sToken);
  328. $oSession->setValue($sPrefix . '_token_time', time());
  329. }
  330. else {
  331. $sToken = $oSession->getValue($sPrefix . '_token');
  332. }
  333. return $sToken;
  334. }
  335. protected function _getToken()
  336. {
  337. $oSession = BxDolSession::getInstance();
  338. return $oSession->getValue($this->getName() . '_token');
  339. }
  340. protected function _getExistingAccount($aProfileInfo, &$aFieldsAccount, &$aFieldsProfile)
  341. {
  342. return BxDolAccount::getInstance($aFieldsAccount['email']);
  343. }
  344. protected function _genPwd($aProfileInfo, &$aFieldsAccount, &$aFieldsProfile)
  345. {
  346. return genRndPwd();
  347. }
  348. protected function _isSetPendingApprovalAccount($aProfileInfo, &$aFieldsAccount, &$aFieldsProfile)
  349. {
  350. return $this->_oConfig->isAlwaysAutoApprove ? false : !(bool)getParam('sys_account_autoapproval');
  351. }
  352. protected function _isSetPendingApprovalProfile($aProfileInfo, $oFormHelperProfile, &$aFieldsAccount, &$aFieldsProfile)
  353. {
  354. return $oFormHelperProfile->isAutoApproval() ? true : $this->_oConfig->isAlwaysAutoApprove;
  355. }
  356. // fo using in some selected modules only
  357. protected function _actionHandle()
  358. {
  359. require_once(BX_DIRECTORY_PATH_INC . 'design.inc.php');
  360. // check token
  361. if ($this->_getToken() != bx_get('state')) {
  362. $this->_oTemplate->getPage(_t('_Error'), MsgBox(_t('_sys_connect_state_invalid')));
  363. return;
  364. }
  365. // check code
  366. $sCode = bx_get('code');
  367. if (!$sCode) {
  368. $sErrorDescription = bx_get('error_description') ? bx_get('error_description') : _t('_error occured');
  369. $this->_oTemplate->getPage(_t('_Error'), MsgBox($sErrorDescription));
  370. return;
  371. }
  372. // make request for token
  373. $s = bx_file_get_contents($this->_oConfig->sApiUrl . 'token', array(
  374. 'client_id' => $this->_oConfig->sApiID,
  375. 'client_secret' => $this->_oConfig->sApiSecret,
  376. 'grant_type' => 'authorization_code',
  377. 'code' => $sCode,
  378. 'redirect_uri' => $this->_oConfig->sPageHandle,
  379. ), 'post');
  380. // handle error
  381. if (!$s || NULL === ($aResponse = json_decode($s, true)) || !isset($aResponse['access_token']) || isset($aResponse['error'])) {
  382. $sErrorDescription = isset($aResponse['error_description']) ? $aResponse['error_description'] : _t('_error occured');
  383. $this->_oTemplate->getPage(_t('_Error'), MsgBox($sErrorDescription));
  384. return;
  385. }
  386. // get the data, especially access_token
  387. $sAccessToken = $aResponse['access_token'];
  388. $sExpiresIn = $aResponse['expires_in'];
  389. $sExpiresAt = new \DateTime('+' . $sExpiresIn . ' seconds');
  390. $sRefreshToken = $aResponse['refresh_token'];
  391. $oSession = BxDolSession::getInstance();
  392. $oSession->setValue($this->getName() . '_access_token', $sAccessToken);
  393. // request info about profile
  394. $s = bx_file_get_contents($this->_oConfig->sApiUrl . 'api/me', array(), 'get', array(
  395. 'Authorization: Bearer ' . $sAccessToken,
  396. ));
  397. // handle error
  398. if (!$s || NULL === ($aResponse = json_decode($s, true)) || !$aResponse || isset($aResponse['error'])) {
  399. $sErrorDescription = isset($aResponse['error_description']) ? $aResponse['error_description'] : _t('_error occured');
  400. $this->_oTemplate->getPage(_t('_Error'), MsgBox($sErrorDescription));
  401. return;
  402. }
  403. $aRemoteProfileInfo = $aResponse;
  404. if ($aRemoteProfileInfo) {
  405. // check if user logged in before
  406. $iLocalProfileId = $this->_oDb->getProfileId($aRemoteProfileInfo['id']);
  407. if ($iLocalProfileId && $oProfile = BxDolProfile::getInstance($iLocalProfileId)) {
  408. // user already exists
  409. $this->setLogged($oProfile ->id());
  410. }
  411. else {
  412. // register new user
  413. $this->_createProfile($aRemoteProfileInfo);
  414. }
  415. }
  416. else {
  417. $this->_oTemplate->getPage(_t('_Error'), MsgBox(_t('_sys_connect_profile_error_info')));
  418. }
  419. }
  420. }
  421. /** @} */