1
0

BxBaseModConnectModule.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  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 is 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. 'error_msg_ref' => &$sErrorMsg,
  210. 'email' => $aFieldsAccount['email'],
  211. 'approve' => &$bSetPendingApproval,
  212. 'approve_ref' => &$bSetPendingApproval
  213. ]);
  214. if ($sErrorMsg)
  215. return $sErrorMsg;
  216. // check if user with the same email already exists
  217. $oExistingAccount = $this->_getExistingAccount($aProfileInfo, $aFieldsAccount, $aFieldsProfile);
  218. // check redirect page
  219. if ('join' == $this->_oConfig->sRedirectPage && !$oExistingAccount)
  220. return array('remote_profile_info' => $aProfileInfo, 'profile_fields' => $aFieldsAccount, 'join_page_redirect' => true);
  221. // create new profile
  222. if ($oExistingAccount) {
  223. if (!($oExistingProfile = BxDolProfile::getInstanceByAccount($oExistingAccount->id(), true)))
  224. return _t('_sys_txt_error_account_creation');
  225. $iProfileId = $oExistingProfile->id();
  226. $this->setLogged($iProfileId);
  227. }
  228. else {
  229. // create account
  230. $aFieldsAccount['password'] = $this->_genPwd($aProfileInfo, $aFieldsAccount, $aFieldsProfile);
  231. if (!($iAccountId = $oFormAccount->insert($aFieldsAccount)))
  232. return _t('_sys_txt_error_account_creation');
  233. $isSetPendingApproval = $this->_isSetPendingApprovalAccount($aProfileInfo, $aFieldsAccount, $aFieldsProfile);
  234. $iAccountProfileId = $oFormHelperAccount->onAccountCreated ($iAccountId, $isSetPendingApproval, BX_PROFILE_ACTION_EXTERNAL);
  235. // create profile
  236. if (isset($oFormProfile) && $oFormProfile) {
  237. $aFieldsProfile['author'] = $iAccountProfileId;
  238. $aFieldsProfile['picture'] = $this->_processImage($aFieldsProfile, $iAccountProfileId, $oFormHelperProfile);
  239. $_POST['picture'] = $aFieldsProfile['picture']; // set POST variable to correctly process images in processFiles method in form object
  240. if (!($iContentId = $oFormProfile->insert($aFieldsProfile)))
  241. return _t('_sys_txt_error_account_creation');
  242. $isSetPendingApprovalProfile = $this->_isSetPendingApprovalProfile($aProfileInfo, $oFormHelperProfile, $aFieldsAccount, $aFieldsProfile);
  243. $oFormHelperProfile->setAutoApproval($isSetPendingApprovalProfile);
  244. if ($sErrorMsg = $oFormHelperProfile->onDataAddAfter ($iAccountId, $iContentId))
  245. return $sErrorMsg;
  246. $oProfile = BxDolProfile::getInstanceByAccount($iAccountId, true);
  247. $iProfileId = $oProfile->id();
  248. }
  249. else {
  250. $iProfileId = $iAccountProfileId;
  251. }
  252. $oAccount = BxDolAccount::getInstance($iAccountId);
  253. if ($oAccount)
  254. $oAccount->updateEmailConfirmed($this->_oConfig->isAlwaysConfirmEmail);
  255. // send email with password
  256. if ($this->_oConfig->bSendPasswordGenerated)
  257. sendMailTemplate($this->_oConfig->sEmailTemplatePasswordGenerated, $iAccountId, $iProfileId, array('password' => $aFieldsAccount['password']), BX_EMAIL_SYSTEM);
  258. }
  259. // remember remote profile id for created member
  260. $this ->_oDb->saveRemoteId($iProfileId, $aProfileInfo['id']);
  261. // auto-friend members if they are already friends on remote site
  262. if ($isAutoFriends && method_exists($this, '_makeFriends'))
  263. $this->_makeFriends($iProfileId);
  264. return array('remote_profile_info' => $aProfileInfo, 'profile_id' => $iProfileId, 'existing_profile' => $oExistingAccount ? true : false);
  265. }
  266. protected function _processImage($aFieldsProfile, $iAccountProfileId, $oFormHelperProfile)
  267. {
  268. if (!isset($aFieldsProfile['picture']) || !$aFieldsProfile['picture'])
  269. return 0;
  270. if (!($oStorage = $oFormHelperProfile->getObjectStorage()))
  271. return 0;
  272. if (!($iFileId = $oStorage->storeFileFromUrl($aFieldsProfile['picture'], false, $iAccountProfileId)))
  273. return 0;
  274. return $iFileId;
  275. }
  276. /**
  277. * Get join page
  278. *
  279. * @param $aProfileFields array
  280. * @param $iRemoteProfileId remote profile id
  281. * @return void
  282. */
  283. function _getJoinPage($aProfileFields, $iRemoteProfileId)
  284. {
  285. bx_import('BxDolSession');
  286. $oSession = BxDolSession::getInstance();
  287. $oSession->setValue($this->_oConfig->sSessionUid, $iRemoteProfileId);
  288. $oPage = BxDolPage::getObjectInstanceByURI('create-account');
  289. BxBaseAccountForms::$PROFILE_FIELDS = $aProfileFields;
  290. $this->_oTemplate->getPage(false, $oPage->getCode());
  291. }
  292. /**
  293. * get redirect URL
  294. *
  295. * @param $iProfileId integer - profile ID
  296. * @return string redirect URL
  297. */
  298. function _getRedirectUrl($iProfileId, $isExistingProfile = false)
  299. {
  300. $sRedirectUrl = $this->_oConfig->sDefaultRedirectUrl;
  301. switch($this->_oConfig->sRedirectPage) {
  302. case 'index':
  303. $sRedirectUrl = BX_DOL_URL_ROOT;
  304. break;
  305. case 'settings':
  306. if (!$isExistingProfile) {
  307. $sRedirectUrl = bx_absolute_url(BxDolPermalinks::getInstance()->permalink('page.php?i=account-settings-email'));
  308. break;
  309. }
  310. case 'dashboard':
  311. default:
  312. $sRedirectUrl = bx_absolute_url(BxDolPermalinks::getInstance()->permalink('page.php?i=dashboard'));
  313. break;
  314. }
  315. return $sRedirectUrl;
  316. }
  317. protected function _redirect($sUrl, $iStatus = 302)
  318. {
  319. header("Location:{$sUrl}", true, $iStatus);
  320. exit;
  321. }
  322. protected function _genToken($bReturn = false)
  323. {
  324. $oSession = BxDolSession::getInstance();
  325. $sPrefix = $this->getName();
  326. $iCsrfTokenLifetime = 3600;
  327. if ($oSession->getValue($sPrefix . '_token') === false || (time() - (int)$oSession->getValue($sPrefix . '_token_time') > $iCsrfTokenLifetime)) {
  328. $sToken = genRndPwd(20, false);
  329. $oSession->setValue($sPrefix . '_token', $sToken);
  330. $oSession->setValue($sPrefix . '_token_time', time());
  331. }
  332. else {
  333. $sToken = $oSession->getValue($sPrefix . '_token');
  334. }
  335. return $sToken;
  336. }
  337. protected function _getToken()
  338. {
  339. $oSession = BxDolSession::getInstance();
  340. return $oSession->getValue($this->getName() . '_token');
  341. }
  342. protected function _getExistingAccount($aProfileInfo, &$aFieldsAccount, &$aFieldsProfile)
  343. {
  344. return BxDolAccount::getInstance($aFieldsAccount['email']);
  345. }
  346. protected function _genPwd($aProfileInfo, &$aFieldsAccount, &$aFieldsProfile)
  347. {
  348. return genRndPwd();
  349. }
  350. protected function _isSetPendingApprovalAccount($aProfileInfo, &$aFieldsAccount, &$aFieldsProfile)
  351. {
  352. return $this->_oConfig->isAlwaysAutoApprove ? false : !(bool)getParam('sys_account_autoapproval');
  353. }
  354. protected function _isSetPendingApprovalProfile($aProfileInfo, $oFormHelperProfile, &$aFieldsAccount, &$aFieldsProfile)
  355. {
  356. return $oFormHelperProfile->isAutoApproval() ? true : $this->_oConfig->isAlwaysAutoApprove;
  357. }
  358. // fo using in some selected modules only
  359. protected function _actionHandle()
  360. {
  361. require_once(BX_DIRECTORY_PATH_INC . 'design.inc.php');
  362. // check token
  363. if ($this->_getToken() != bx_get('state')) {
  364. $this->_oTemplate->getPage(_t('_Error'), MsgBox(_t('_sys_connect_state_invalid')));
  365. return;
  366. }
  367. // check code
  368. $sCode = bx_get('code');
  369. if (!$sCode) {
  370. $sErrorDescription = bx_get('error_description') ? bx_get('error_description') : _t('_error occured');
  371. $this->_oTemplate->getPage(_t('_Error'), MsgBox($sErrorDescription));
  372. return;
  373. }
  374. // make request for token
  375. $s = bx_file_get_contents($this->_oConfig->sApiUrl . 'token', array(
  376. 'client_id' => $this->_oConfig->sApiID,
  377. 'client_secret' => $this->_oConfig->sApiSecret,
  378. 'grant_type' => 'authorization_code',
  379. 'code' => $sCode,
  380. 'redirect_uri' => $this->_oConfig->sPageHandle,
  381. ), 'post');
  382. // handle error
  383. if (!$s || NULL === ($aResponse = json_decode($s, true)) || !isset($aResponse['access_token']) || isset($aResponse['error'])) {
  384. $sErrorDescription = isset($aResponse['error_description']) ? $aResponse['error_description'] : _t('_error occured');
  385. $this->_oTemplate->getPage(_t('_Error'), MsgBox($sErrorDescription));
  386. return;
  387. }
  388. // get the data, especially access_token
  389. $sAccessToken = $aResponse['access_token'];
  390. $sExpiresIn = $aResponse['expires_in'];
  391. $sExpiresAt = new \DateTime('+' . $sExpiresIn . ' seconds');
  392. $sRefreshToken = $aResponse['refresh_token'];
  393. $oSession = BxDolSession::getInstance();
  394. $oSession->setValue($this->getName() . '_access_token', $sAccessToken);
  395. // request info about profile
  396. $s = bx_file_get_contents($this->_oConfig->sApiUrl . 'api/me', array(), 'get', array(
  397. 'Authorization: Bearer ' . $sAccessToken,
  398. ));
  399. // handle error
  400. if (!$s || NULL === ($aResponse = json_decode($s, true)) || !$aResponse || isset($aResponse['error'])) {
  401. $sErrorDescription = isset($aResponse['error_description']) ? $aResponse['error_description'] : _t('_error occured');
  402. $this->_oTemplate->getPage(_t('_Error'), MsgBox($sErrorDescription));
  403. return;
  404. }
  405. $aRemoteProfileInfo = $aResponse;
  406. if ($aRemoteProfileInfo) {
  407. // check if user logged in before
  408. $iLocalProfileId = $this->_oDb->getProfileId($aRemoteProfileInfo['id']);
  409. if ($iLocalProfileId && $oProfile = BxDolProfile::getInstance($iLocalProfileId)) {
  410. // user already exists
  411. $this->setLogged($oProfile ->id());
  412. }
  413. else {
  414. // register new user
  415. $this->_createProfile($aRemoteProfileInfo);
  416. }
  417. }
  418. else {
  419. $this->_oTemplate->getPage(_t('_Error'), MsgBox(_t('_sys_connect_profile_error_info')));
  420. }
  421. }
  422. /**
  423. * Make friends (for using in some selected modules only)
  424. *
  425. * @param $iProfileId integer
  426. * @return void
  427. */
  428. protected function __makeFriends($iProfileId)
  429. {
  430. if (!$this->_oConfig->bAutoFriends)
  431. return;
  432. $oConnFrinds = BxDolConnection::getObjectInstance('sys_profiles_friends');
  433. if (!$oConnFrinds)
  434. return;
  435. // request info about profile
  436. if (!($iRemoteProfileId = $this->_oDb->getRemoteProfileId($iProfileId)))
  437. return;
  438. $oSession = BxDolSession::getInstance();
  439. if (!($sAccessToken = $oSession->getValue($this->getName() . '_access_token')))
  440. return;
  441. $s = bx_file_get_contents($this->_oConfig->sApiUrl . 'api/friends?id=' . $iRemoteProfileId, array(), 'get', array(
  442. 'Authorization: Bearer ' . $sAccessToken,
  443. ));
  444. // handle error
  445. if (!$s || NULL === ($aResponse = json_decode($s, true)) || !$aResponse || isset($aResponse['error']) || !isset($aResponse['friends'])) {
  446. $sErrorDescription = isset($aResponse['error_description']) ? $aResponse['error_description'] : _t('_error occured');
  447. return;
  448. }
  449. // add friends & followers
  450. foreach ($aResponse['friends'] as $key => $value) {
  451. $iRemoteProfileId = is_array($value) ? $key : $value;
  452. if (!($iLocalProfileId = $this->_oDb->getProfileId($iRemoteProfileId)))
  453. continue;
  454. $oConnFrinds->actionAdd($iProfileId, $iLocalProfileId);
  455. $oConnFrinds->actionAdd($iLocalProfileId, $iProfileId);
  456. }
  457. }
  458. }
  459. /** @} */