BxBaseServiceAccount.php 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941
  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 UnaBaseView UNA Base Representation Classes
  7. * @{
  8. */
  9. /**
  10. * System service for creating system profile functionality.
  11. */
  12. class BxBaseServiceAccount extends BxDol
  13. {
  14. protected $_oAccountForms;
  15. protected $_oAccountQuery;
  16. public function __construct()
  17. {
  18. parent::__construct();
  19. $this->_oAccountForms = new BxTemplAccountForms();
  20. $this->_oAccountQuery = BxDolAccountQuery::getInstance();
  21. }
  22. /**
  23. * @page service Service Calls
  24. * @section bx_system_general System Services
  25. * @subsection bx_system_general-account Account
  26. * @subsubsection bx_system_general-create_account_form create_account_form
  27. *
  28. * @code bx_srv('system', 'create_account_form', [], 'TemplServiceAccount'); @endcode
  29. * @code {{~system:create_account_form:TemplServiceAccount[{"no_login_text":true, "no_auth_buttons":true}]~}} @endcode
  30. *
  31. * Join form.
  32. * @param $aParams array of additional params, such as:
  33. * - no_login_text
  34. * - no_auth_buttons
  35. *
  36. * @see BxBaseServiceAccount::serviceGetCreatePostForm
  37. */
  38. /**
  39. * @ref bx_system_general-create_account_form "create_account_form"
  40. */
  41. public function serviceCreateAccountForm ($aParams = array())
  42. {
  43. $bApi = bx_is_api();
  44. if (isLogged() && 'create-account' == bx_get('i')) {
  45. if (!$bApi) {
  46. header('Location: ' . BX_DOL_URL_ROOT);
  47. exit;
  48. }
  49. else
  50. return [
  51. ['id' => 2, 'type' => 'redirect', 'data' => ['uri' => '/']],
  52. ];
  53. }
  54. if($bApi) {
  55. $mixedResult = $this->_oAccountForms->createAccountForm($aParams);
  56. if(is_array($mixedResult))
  57. return [bx_api_get_block('form', $mixedResult, [
  58. 'ext' => [
  59. 'request' => ['url' => '/api.php?r=system/create_account_form/TemplServiceAccount', 'immutable' => true]
  60. ]
  61. ])];
  62. else if($mixedResult === true){
  63. $sRedirectUrl = BxDolForm::getSubmittedValue('relocate','post');
  64. if(empty($sRedirectUrl)){
  65. if (!getParam('sys_account_auto_profile_creation')){
  66. $aModulesProfile = bx_srv('system', 'get_modules_by_type', ['profile']);
  67. $sDefaultProfileType = getParam('sys_account_default_profile_type');
  68. if(count($aModulesProfile) == 1)
  69. $sProfileModule = $aModulesProfile[0]['name'];
  70. else if(!empty($sDefaultProfileType))
  71. $sProfileModule = $sDefaultProfileType;
  72. $sRedirectUrl = !empty($sProfileModule) ? bx_api_get_relative_url(BxDolPermalinks::getInstance()->permalink(BxDolService::call($sProfileModule, 'profile_create_url', array(false)))) : '/';
  73. }
  74. else{
  75. $sRedirectUrl = '/';
  76. }
  77. }
  78. else{
  79. $parts = parse_url($sRedirectUrl);
  80. parse_str($parts['query'], $query);
  81. unset($query['_q']);
  82. $parts['query'] = http_build_query($query);
  83. $sRedirectUrl = $parts['path'] . (!empty($parts['query']) ? '?' . $parts['query'] : '');
  84. }
  85. return [
  86. bx_api_get_block('redirect', ['uri' => $sRedirectUrl]),
  87. //bx_api_get_block('login', ['session' => BxDolSession::getInstance()->getId()], ['id' => 2]),
  88. ];
  89. }
  90. else
  91. return [bx_api_get_msg($mixedResult)];
  92. }
  93. $oPemalink = BxDolPermalinks::getInstance();
  94. if (isset($_SERVER['HTTP_REFERER']) && 0 === mb_stripos($_SERVER['HTTP_REFERER'], BX_DOL_URL_ROOT)) { // remember referrer
  95. $sJoinReferrer = $_SERVER['HTTP_REFERER'];
  96. $aNoRelocatePages = array('forgot-password', 'login', 'create-account', 'logout');
  97. foreach ($aNoRelocatePages as $s) {
  98. if (false !== mb_stripos($sJoinReferrer, $s)) {
  99. $sJoinReferrer = '';
  100. break;
  101. }
  102. }
  103. if ($sJoinReferrer)
  104. BxDolSession::getInstance()->setValue('join-referrer', $sJoinReferrer);
  105. }
  106. $aTmplVarsAuth = [];
  107. if(!isset($aParams['no_auth_buttons']) || false === (bool)$aParams['no_auth_buttons'])
  108. $aTmplVarsAuth['content'] = BxDolService::call('system', 'member_auth_code', array(), 'TemplServiceLogin');
  109. $aTmplVarsForm = [];
  110. if(!(bool)getParam('sys_account_disable_join_form'))
  111. $aTmplVarsForm['content'] = $this->_oAccountForms->createAccountForm($aParams);
  112. $aTmplVarsLogin = [];
  113. if(!isset($aParams['no_login_text']) || false === (bool)$aParams['no_login_text'])
  114. $aTmplVarsLogin['url'] = bx_absolute_url($oPemalink->permalink('page.php?i=login'));
  115. return BxDolTemplate::getInstance()->parseHtmlByName('block_join.html', [
  116. 'bx_if:show_auth' => [
  117. 'condition' => !empty($aTmplVarsAuth),
  118. 'content' => $aTmplVarsAuth
  119. ],
  120. 'bx_if:show_form' => [
  121. 'condition' => !empty($aTmplVarsForm),
  122. 'content' => $aTmplVarsForm,
  123. ],
  124. 'bx_if:show_login' => [
  125. 'condition' => !empty($aTmplVarsLogin),
  126. 'content' => $aTmplVarsLogin
  127. ],
  128. 'agreement' => _t('_sys_form_account_input_agreement_value', bx_absolute_url($oPemalink->permalink('page.php?i=terms')), bx_absolute_url($oPemalink->permalink('page.php?i=privacy'))),
  129. ]);
  130. }
  131. public function serviceAccountSettingsEmail ($iAccountId = false)
  132. {
  133. if (false === $iAccountId)
  134. $iAccountId = getLoggedId();
  135. $bApi = bx_is_api();
  136. $mixedResult =$this->_oAccountForms->editAccountEmailSettingsForm($iAccountId);
  137. if($bApi) {
  138. if(is_array($mixedResult)){
  139. if (isset($mixedResult['form'] )){
  140. return [
  141. bx_api_get_msg($mixedResult['msg']),
  142. bx_api_get_block('form', $mixedResult['form'], [
  143. 'ext' => [
  144. 'request' => ['url' => '/api.php?r=system/account_settings_email/TemplServiceAccount', 'immutable' => true]
  145. ]
  146. ])];
  147. }
  148. else{
  149. return [bx_api_get_block('form', $mixedResult, [
  150. 'ext' => [
  151. 'request' => ['url' => '/api.php?r=system/account_settings_email/TemplServiceAccount', 'immutable' => true]
  152. ]
  153. ])];
  154. }
  155. }
  156. else
  157. return [bx_api_get_msg($mixedResult)];
  158. }
  159. return $mixedResult;
  160. }
  161. public function serviceAccountSettingsPassword ($iAccountId = false)
  162. {
  163. if (false === $iAccountId)
  164. $iAccountId = getLoggedId();
  165. $bApi = bx_is_api();
  166. $mixedResult =$this->_oAccountForms->editAccountPasswordSettingsForm($iAccountId);
  167. if($bApi) {
  168. if(is_array($mixedResult)){
  169. if (isset($mixedResult['form'] )){
  170. return [
  171. bx_api_get_msg($mixedResult['msg']),
  172. bx_api_get_block('form', $mixedResult['form'], [
  173. 'ext' => [
  174. 'request' => ['url' => '/api.php?r=system/account_settings_password/TemplServiceAccount', 'immutable' => true]
  175. ]
  176. ])];
  177. }
  178. else{
  179. return [bx_api_get_block('form', $mixedResult, [
  180. 'ext' => [
  181. 'request' => ['url' => '/api.php?r=system/account_settings_password/TemplServiceAccount', 'immutable' => true]
  182. ]
  183. ])];
  184. }
  185. }
  186. else
  187. return [bx_api_get_msg($mixedResult)];
  188. }
  189. return $mixedResult;
  190. }
  191. public function serviceAccountSettingsInfo ($iAccountId = false)
  192. {
  193. if (false === $iAccountId)
  194. $iAccountId = getLoggedId();
  195. $bApi = bx_is_api();
  196. $mixedResult =$this->_oAccountForms->editAccountInfoForm($iAccountId);
  197. if($bApi) {
  198. if(is_array($mixedResult)){
  199. if (isset($mixedResult['form'] )){
  200. return [
  201. bx_api_get_msg($mixedResult['msg']),
  202. bx_api_get_block('form', $mixedResult['form'], [
  203. 'ext' => [
  204. 'request' => ['url' => '/api.php?r=system/account_settings_info/TemplServiceAccount', 'immutable' => true]
  205. ]
  206. ])];
  207. }
  208. else{
  209. return [bx_api_get_block('form', $mixedResult, [
  210. 'ext' => [
  211. 'request' => ['url' => '/api.php?r=system/account_settings_info/TemplServiceAccount', 'immutable' => true]
  212. ]
  213. ])];
  214. }
  215. }
  216. else
  217. return [bx_api_get_msg($mixedResult)];
  218. }
  219. return $mixedResult;
  220. }
  221. public function serviceAccountSettingsDelAccount ($iAccountId = false)
  222. {
  223. if (!$iAccountId)
  224. $iAccountId = bx_process_input(bx_get('id'), BX_DATA_INT);
  225. if (!$iAccountId)
  226. $iAccountId = getLoggedId();
  227. $bApi = bx_is_api();
  228. $mixedResult = $this->_oAccountForms->deleteAccountForm($iAccountId);
  229. if($bApi) {
  230. if(is_array($mixedResult)){
  231. if (isset($mixedResult['form'] )){
  232. return [
  233. bx_api_get_msg($mixedResult['msg']),
  234. bx_api_get_block('form', $mixedResult['form'], [
  235. 'ext' => [
  236. 'request' => ['url' => '/api.php?r=system/account_settings_del_account/TemplServiceAccount', 'immutable' => true]
  237. ]
  238. ])];
  239. }
  240. else{
  241. return [bx_api_get_block('form', $mixedResult, [
  242. 'ext' => [
  243. 'request' => ['url' => '/api.php?r=system/account_settings_del_account/TemplServiceAccount', 'immutable' => true]
  244. ]
  245. ])];
  246. }
  247. }
  248. else if(is_string($mixedResult))
  249. return [
  250. bx_api_get_msg($mixedResult)
  251. ];
  252. else
  253. return [
  254. ['id' => 2, 'type' => 'redirect', 'data' => ['uri' => '/']],
  255. ];
  256. }
  257. return $mixedResult;
  258. }
  259. public function serviceAccountDelete($iId, $bWithContent = false)
  260. {
  261. if(($oAccount = BxDolAccount::getInstance($iId)) !== false)
  262. return $oAccount->delete($bWithContent);
  263. return false;
  264. }
  265. /**
  266. * Display unsubscribe from newsletters form
  267. */
  268. public function serviceUnsubscribeNews()
  269. {
  270. return $this->_unsubscribeForm('sys_unsubscribe_news');
  271. }
  272. /**
  273. * Display unsubscribe from notifications form
  274. */
  275. public function serviceUnsubscribeNotifications()
  276. {
  277. return $this->_unsubscribeForm('sys_unsubscribe_updates');
  278. }
  279. /**
  280. * Display confirmation statuses list
  281. */
  282. public function serviceGetConfirmationTypes()
  283. {
  284. $aResult = array();
  285. $aChoices = array(BX_ACCOUNT_CONFIRMATION_NONE, BX_ACCOUNT_CONFIRMATION_EMAIL, BX_ACCOUNT_CONFIRMATION_PHONE, BX_ACCOUNT_CONFIRMATION_EMAIL_PHONE, BX_ACCOUNT_CONFIRMATION_EMAIL_OR_PHONE);
  286. foreach($aChoices as $sChoice)
  287. $aResult[$sChoice] = _t('_sys_acc_confirmation_type_' . $sChoice);
  288. return $aResult;
  289. }
  290. protected function _unsubscribeForm($sDisplay)
  291. {
  292. $iAccountId = bx_process_input(bx_get('id'));
  293. $sCode = bx_process_input(bx_get('code'));
  294. // validate input params
  295. $oAccount = BxDolAccount::getInstance($iAccountId);
  296. if (!$oAccount)
  297. return MsgBox(_t('_sys_txt_unsubscribe_wrong_link'));
  298. if ($sCode != $oAccount->getEmailHash())
  299. return MsgBox(_t('_sys_txt_unsubscribe_wrong_link'));
  300. $oForm = BxDolForm::getObjectInstance('sys_unsubscribe', $sDisplay);
  301. if (!$oForm)
  302. return MsgBox(_t('_sys_txt_unsubscribe_error_occured'));
  303. // show form
  304. $aAccountInfo = $oAccount->getInfo();
  305. $aAccountInfo['code'] = $sCode;
  306. $oForm->initChecker($aAccountInfo);
  307. if ($oForm->isSubmittedAndValid()) {
  308. if (!$oForm->update($oAccount->id()))
  309. return MsgBox(_t('_sys_txt_unsubscribe_error_occured'));
  310. return MsgBox(_t('_sys_txt_unsubscribe_email_settings_update_success'));
  311. }
  312. return '<div class="bx-def-padding-bottom">' . _t("_sys_txt_unsubscribe_info", $aAccountInfo['email']) . '</div>' . $oForm->getCode();
  313. }
  314. /**
  315. * Display email confirmation form, if confirmation code is provided then try to confirm profile
  316. */
  317. public function serviceEmailConfirmation($sMsg = false)
  318. {
  319. $bApi = bx_is_api();
  320. // if user is logged in and email is confirmed then just display a message
  321. if (isLogged() && !bx_get('code')) {
  322. $oAccount = BxDolAccount::getInstance();
  323. if ($oAccount->isConfirmedEmail())
  324. return $bApi ? [bx_api_get_msg(_t("_sys_txt_confirm_email_already_confirmed"))] : MsgBox(_t("_sys_txt_confirm_email_already_confirmed"));
  325. }
  326. // if confirmation code is provided in the URL - perform email confirmation right away
  327. if (bx_get('code') !== false)
  328. return $this->confirmEmail(bx_process_input(bx_get('code')));
  329. // if user requested to resend verification letter then send letter and display message
  330. if (bx_process_input(bx_get('resend')) && isLogged()) {
  331. $oAccount = BxDolAccount::getInstance();
  332. if ($oAccount->sendConfirmationEmail())
  333. $sMsg = _t('_sys_txt_confirm_email_sent');
  334. else
  335. $sMsg = _t('_sys_txt_confirm_email_sent_failed');
  336. return $bApi ? [bx_api_get_msg($sMsg)] : MsgBox($sMsg);
  337. }
  338. // show and process code verification form
  339. $oForm = BxDolForm::getObjectInstance('sys_confirm_email', 'sys_confirm_email');
  340. if (!$oForm)
  341. return $bApi ? [bx_api_get_msg(_t("_sys_txt_confirm_email_error_occured"))] : MsgBox(_t("_sys_txt_confirm_email_error_occured"));
  342. $oForm->initChecker();
  343. if ($oForm->isSubmittedAndValid()) {
  344. $oKey = BxDolKey::getInstance();
  345. if (!$oKey){
  346. return $bApi ? [bx_api_get_msg(_t("_sys_txt_confirm_email_error_occured"))] : MsgBox(_t("_sys_txt_confirm_email_error_occured"));
  347. }
  348. else{
  349. $oRv = $this->confirmEmail(trim($oForm->getCleanValue('code')));
  350. if (!$bApi)
  351. return $oRv;
  352. return $oRv;
  353. }
  354. }
  355. if ($bApi){
  356. return [bx_api_get_block('form', $oForm->getCodeAPI(), [
  357. 'ext' => [
  358. 'request' => ['url' => '/api.php?r=system/email_confirmation/TemplServiceAccount', 'immutable' => true]
  359. ]
  360. ])];
  361. }
  362. return '<div class="bx-def-padding-sec-bottom">' . _t("_sys_txt_confirm_email_desc") . '</div>' . $oForm->getCode();
  363. }
  364. /**
  365. * Display phone confirmation forms, if confirmation code is provided then try to confirm profile
  366. */
  367. public function servicePhoneConfirmation($sMsg = false)
  368. {
  369. // if user is logged in and phone is confirmed then just display a message
  370. if (isLogged()) {
  371. $oAccount = BxDolAccount::getInstance();
  372. if ($oAccount->isConfirmedPhone())
  373. return MsgBox(_t("_sys_txt_confirm_phone_already_confirmed"));
  374. $iStep = 1;
  375. $a = $oAccount->getInfo();
  376. $sPhoneNumber = $a['phone'];
  377. $oSession = BxDolSession::getInstance();
  378. if ($sPhoneNumber != "" && $oSession->isValue(BX_ACCOUNT_SESSION_KEY_FOR_PHONE_ACTIVATEION_CODE))
  379. $iStep = 2;
  380. if (bx_get('step'))
  381. $iStep = (int)bx_get('step');
  382. // show and process phone set form
  383. if ($iStep == 1){
  384. $oForm = BxDolForm::getObjectInstance('sys_confirm_phone', 'sys_confirm_phone_set_phone');
  385. if (!$oForm)
  386. return MsgBox(_t("_sys_txt_confirm_phone_set_phone_error_occured"));
  387. $oForm->initChecker(['phone' => $sPhoneNumber]);
  388. if ($oForm->isSubmittedAndValid()) {
  389. $sPhoneNumber = trim($oForm->getCleanValue('phone'));
  390. $oAccount->updatePhone($sPhoneNumber);
  391. $sActivationCode = rand(1000, 9999);
  392. $sActivationText =_t('_sys_txt_confirm_phone_sms_text', $sActivationCode);
  393. $mixedResult = null;
  394. /**
  395. * @hooks
  396. * @hookdef hook-account-before_confirm_phone_send_sms 'account', 'before_confirm_phone_send_sms' - hook in confirm phone
  397. * - $unit_name - equals `account`
  398. * - $action - equals `before_confirm_phone_send_sms`
  399. * - $object_id - account id
  400. * - $sender_id - logged profile_id
  401. * - $extra_params - array of additional params with the following array keys:
  402. * - `phone_number` - [string] by ref, phone number to send sms, can be overridden in hook processing
  403. * - `sms_text` - [string] by ref, text for sms, can be overridden in hook processing
  404. * - `override_result` - [mixed] by ref, can be object, can be overridden in hook processing
  405. * @hook @ref hook-account-before_confirm_phone_send_sms
  406. */
  407. bx_alert('account', 'before_confirm_phone_send_sms', $oAccount->id(), bx_get_logged_profile_id(), [
  408. 'phone_number' => &$sPhoneNumber,
  409. 'sms_text' => &$sActivationText,
  410. 'override_result' => &$mixedResult
  411. ]);
  412. if ($mixedResult === null && ($oSms = BxDolSms::getObjectInstance()) !== false && !$oSms->send($sPhoneNumber, $sActivationText))
  413. return MsgBox(_t("_sys_txt_confirm_phone_send_sms_error_occured"));
  414. $oSession->setValue(BX_ACCOUNT_SESSION_KEY_FOR_PHONE_ACTIVATEION_CODE, $sActivationCode);
  415. header('Location: ' . bx_absolute_url(BxDolPermalinks::getInstance()->permalink('page.php?i=confirm-phone')));
  416. }
  417. return '<div class="bx-def-padding-sec-bottom">' . _t("_sys_txt_confirm_phone_set_phone_desc_set_phone") . '</div>' .$oForm->getCode();
  418. }
  419. if ($iStep == 2){
  420. $oForm = BxDolForm::getObjectInstance('sys_confirm_phone', 'sys_confirm_phone_confirmation');
  421. if (!$oForm)
  422. return MsgBox(_t("_sys_txt_confirm_phone_set_phone_confirmation_occured"));
  423. $oForm->initChecker();
  424. if ($oForm->isSubmittedAndValid()) {
  425. $oAccount->updatePhoneConfirmed(true);
  426. $oSession->unsetValue(BX_ACCOUNT_SESSION_KEY_FOR_PHONE_ACTIVATEION_CODE);
  427. return MsgBox(_t("_sys_txt_confirm_phone_confirm_success"));
  428. }
  429. return '<div class="bx-def-padding-sec-bottom">' . _t("_sys_txt_confirm_phone_set_phone_desc_phone_confirmation") . '</div>' .$oForm->getCode();
  430. }
  431. }
  432. }
  433. /**
  434. * Perform email confirmation
  435. */
  436. public function confirmEmail($sKey)
  437. {
  438. $bApi = bx_is_api();
  439. $mixedAccountId = $this->_confirmEmail($sKey);
  440. if(is_string($mixedAccountId) && !is_numeric($mixedAccountId))
  441. return $bApi ? [bx_api_get_msg($mixedAccountId)] : MsgBox($mixedAccountId);
  442. if(($oSockets = BxDolSockets::getInstance()) && $oSockets->isEnabled())
  443. $oSockets->sendEvent('sys_account', $mixedAccountId, 'confirmed', '');
  444. // redirect with success message
  445. $sUrl = getParam('sys_redirect_after_email_confirmation');
  446. /**
  447. * @hooks
  448. * @hookdef hook-account-after_email_confirmation 'account', 'after_email_confirmation' - hook after email confirmed
  449. * - $unit_name - equals `account`
  450. * - $action - equals `after_email_confirmation`
  451. * - $object_id - account id
  452. * - $sender_id - not used
  453. * - $extra_params - array of additional params with the following array keys:
  454. * - `override_result` - [string] by ref, url for redirect after email confirmed, can be overridden in hook processing
  455. * @hook @ref hook-account-after_email_confirmation
  456. */
  457. bx_alert('account', 'after_email_confirmation', $mixedAccountId, false, ['override_result' => &$sUrl]);
  458. if ($bApi){
  459. return [bx_api_get_block('redirect', ['uri' => bx_api_get_relative_url(BxDolPermalinks::getInstance()->permalink($sUrl)), 'timeout' => 1000])];
  460. }
  461. $oTemplate = BxDolTemplate::getInstance();
  462. $oTemplate->setPageNameIndex (BX_PAGE_TRANSITION);
  463. $oTemplate->setPageHeader (_t('_sys_txt_confirm_email_success'));
  464. $oTemplate->setPageContent ('page_main_code', MsgBox(_t('_sys_txt_confirm_email_success')));
  465. $oTemplate->setPageContent ('url_relocate', bx_absolute_url(BxDolPermalinks::getInstance()->permalink($sUrl)));
  466. BxDolTemplate::getInstance()->getPageCode();
  467. exit;
  468. }
  469. public function serviceConfirmEmail($sKey)
  470. {
  471. $mixedAccountId = $this->_confirmEmail($sKey);
  472. if(is_string($mixedAccountId) && !is_numeric($mixedAccountId))
  473. return $bApi ? [bx_api_get_msg($mixedAccountId)] : MsgBox($mixedAccountId);
  474. if(($oSockets = BxDolSockets::getInstance()) && $oSockets->isEnabled()){
  475. $oSockets->sendEvent('sys_account', $mixedAccountId, 'confirmed', '');
  476. }
  477. bx_alert('account', 'after_email_confirmation', $mixedAccountId, false, ['override_result' => &$sUrl]);
  478. return true;
  479. }
  480. public function serviceGetOptionsResetPasswordRedirect()
  481. {
  482. $aResult = array();
  483. $aChoices = array('home', 'profile', 'profile_edit', 'custom');
  484. foreach($aChoices as $sChoice)
  485. $aResult[] = array('key' => $sChoice, 'value' => _t('_adm_stg_cpt_option_value_sys_account_reset_password_redirect_' . $sChoice));
  486. return $aResult;
  487. }
  488. public function serviceGetOptionsSwitchToProfileRedirect()
  489. {
  490. $aResult = array();
  491. $aChoices = array('back', 'home', 'profile', 'custom');
  492. foreach($aChoices as $sChoice)
  493. $aResult[] = array('key' => $sChoice, 'value' => _t('_adm_stg_cpt_option_value_sys_account_switch_to_profile_redirect_' . $sChoice));
  494. return $aResult;
  495. }
  496. public function serviceGetOptionsPruningInterval()
  497. {
  498. $aResult = array();
  499. $aChoices = array('no_login_delete', 'no_login_suspend', 'no_confirm_delete', 'no_profile_delete');
  500. foreach($aChoices as $sChoice)
  501. $aResult[] = array('key' => $sChoice, 'value' => _t('_adm_stg_cpt_option_value_sys_account_pruning_' . $sChoice));
  502. return $aResult;
  503. }
  504. /**
  505. * @page service Service Calls
  506. * @section bx_system_general System Services
  507. * @subsection bx_system_general-account Account
  508. * @subsubsection bx_system_general-forgot_password forgot_password
  509. *
  510. * @code bx_srv('system', 'forgot_password', [], 'TemplServiceAccount'); @endcode
  511. * @code {{~system:forgot_password:TemplServiceAccount~}} @endcode
  512. *
  513. * Display forgot password form,
  514. * if reset password key is provided then reset password
  515. *
  516. * @see BxBaseServiceAccount::serviceForgotPassword
  517. */
  518. /**
  519. * @ref bx_system_general-forgot_password "forgot_password"
  520. */
  521. public function serviceForgotPassword()
  522. {
  523. $bApi = bx_is_api();
  524. if (isLogged() && 'forgot-password' == bx_get('i')) {
  525. if (!$bApi) {
  526. header('Location: ' . BX_DOL_URL_ROOT);
  527. exit;
  528. }
  529. else
  530. return [
  531. ['id' => 2, 'type' => 'redirect', 'data' => ['uri' => '/']],
  532. ];
  533. }
  534. if (bx_get('key') !== false)
  535. return $this->resetPassword();
  536. $oForm = BxDolForm::getObjectInstance('sys_forgot_password', 'sys_forgot_password');
  537. if (!$oForm)
  538. return '';
  539. $bNeedCheckEmailAndPhone = true;
  540. $sCaptionKey = "_sys_txt_forgot_pasword_by_both_desc";
  541. if (BxDolAccount::isNeedConfirmPhone()){
  542. if (!BxDolAccount::isNeedConfirmEmail()){
  543. unset($oForm->aInputs['email']);
  544. $sCaptionKey = "_sys_txt_forgot_pasword_by_phone_desc";
  545. $oForm->aInputs['phone']['checker']['func'] = 'PhoneExist';
  546. $bNeedCheckEmailAndPhone = false;
  547. }
  548. }
  549. else{
  550. unset($oForm->aInputs['phone']);
  551. $sCaptionKey = "_sys_txt_forgot_pasword_desc";
  552. $oForm->aInputs['email']['checker']['func'] = 'EmailExist';
  553. $bNeedCheckEmailAndPhone = false;
  554. }
  555. if ((BxDolAccount::isNeedConfirmPhone() && BxDolAccount::isNeedConfirmEmail())){
  556. if (isset($oForm->aInputs['phone']))
  557. $oForm->aInputs['phone']['required'] = false;
  558. if (isset($oForm->aInputs['email']))
  559. $oForm->aInputs['email']['required'] = false;
  560. }
  561. $oForm->initChecker();
  562. $bShowErrorEmptyBoth = false;
  563. if ($oForm->isSubmitted() && $bNeedCheckEmailAndPhone && $oForm->getCleanValue('phone') == '' && $oForm->getCleanValue('email') == ''){
  564. $bShowErrorEmptyBoth = true;
  565. $oForm->setValid(false);
  566. }
  567. $sResultMsg = '';
  568. if ($oForm->isSubmittedAndValid()) {
  569. $sEmail = $oForm->getCleanValue('email');
  570. $sPhone = $oForm->getCleanValue('phone');
  571. if (isset($oForm->aInputs['email']) && $sEmail != '') {
  572. $oAccount = BxDolAccount::getInstance($this->_oAccountQuery->getIdByEmail($sEmail));
  573. if($oAccount && $oAccount->sendResetPasswordEmail())
  574. $sResultMsg = MsgBox(_t("_sys_txt_forgot_pasword_check_email"));
  575. else
  576. $sResultMsg = MsgBox(_t("_sys_txt_forgot_pasword_email_send_failed"));
  577. $sForm = '';
  578. }
  579. if (isset($oForm->aInputs['phone']) && $sPhone != '') {
  580. $iAccountId = $this->_oAccountQuery->getIdByPhone($sPhone);
  581. $aAccountInfo = $this->_oAccountQuery->getInfoById($iAccountId);
  582. $sKey = bx_get_reset_password_key($aAccountInfo['email']);
  583. $sForgotPasswordUrl = bx_get_reset_password_link_by_key($sKey);
  584. $sSmsText = _t('_sys_txt_forgot_pasword_sms_text', $sForgotPasswordUrl);
  585. $mixedOverrideResult = null;
  586. /**
  587. * @hooks
  588. * @hookdef hook-account-before_forgot_password_send_sms 'account', 'before_forgot_password_send_sms' - hook in $oAccount->isConfirmed check
  589. * - $unit_name - equals `account`
  590. * - $action - equals `before_forgot_password_send_sms`
  591. * - $object_id - account id
  592. * - $sender_id - not used
  593. * - $extra_params - array of additional params with the following array keys:
  594. * - `phone_number` - [string] by ref, phone number to send sms, can be overridden in hook processing
  595. * - `sms_text` - [string] by ref, text for sms, can be overridden in hook processing
  596. * - `override_result` - [mixed] by ref, can be object, can be overridden in hook processing
  597. * @hook @ref hook-account-before_forgot_password_send_sms
  598. */
  599. bx_alert('account', 'before_forgot_password_send_sms', $aAccountInfo['id'], false, [
  600. 'phone_number' => &$sPhone,
  601. 'sms_text' => &$sSmsText,
  602. 'override_result' => &$mixedOverrideResult
  603. ]);
  604. if ($mixedOverrideResult === null) {
  605. if(($oSms = BxDolSms::getObjectInstance()) !== false && $oSms->send($sPhone, $sSmsText))
  606. $sResultMsg = MsgBox(_t("_sys_txt_forgot_pasword_check_phone"));
  607. else
  608. $sResultMsg = MsgBox(_t("_sys_txt_forgot_pasword_error_occured"));
  609. }
  610. $sForm = '';
  611. }
  612. if($bApi) {
  613. return [
  614. bx_api_get_msg(strip_tags($sResultMsg)),
  615. ];
  616. }
  617. }
  618. else {
  619. $sResultMsg = _t($sCaptionKey);
  620. $sForm = $oForm->getCode();
  621. if($bApi) {
  622. return [
  623. bx_api_get_msg($sResultMsg, ['ext' => ['msg_type' => 'caption']]),
  624. bx_api_get_block('form', $oForm->getCodeAPI(), [
  625. 'ext' => [
  626. 'request' => ['url' => '/api.php?r=system/forgot_password/TemplServiceAccount', 'immutable' => true]
  627. ]
  628. ])];
  629. }
  630. }
  631. return '<div class="bx-def-padding-sec-bottom">' . $sResultMsg . '</div>' . $sForm . ($bShowErrorEmptyBoth ? '<div class="bx-form-warn">' . _t("_sys_form_forgot_password_phone_and_email_empty_error") . '</div>' : '');
  632. }
  633. /**
  634. * @page service Service Calls
  635. * @section bx_system_general System Services
  636. * @subsection bx_system_general-account Account
  637. * @subsubsection bx_system_general-switch_profile switch_profile
  638. *
  639. * @code bx_srv('system', 'switch_profile', [123], 'TemplServiceAccount'); @endcode
  640. * @code {{~system:switch_profile:TemplServiceAccount:[123]~}} @endcode
  641. *
  642. * Switch current user profile.
  643. * User can switch between profiles if multiple profiles are created.
  644. * Also it's possible to switch to Organization profile if user is admin of Organization,
  645. * or other module which can `actAsProfile`.
  646. * Admin can switch to any prifile by default
  647. *
  648. * @param $iSwitchToProfileId profile ID to switch to
  649. * @return true on success or error message otherwise, so make sue to make strict (===) comparision
  650. *
  651. * @see BxBaseServiceAccount::serviceSwitchProfile
  652. */
  653. /**
  654. * @ref bx_system_general-switch_profile "switch_profile"
  655. */
  656. public function serviceSwitchProfile($iSwitchToProfileId)
  657. {
  658. $oProfile = BxDolProfile::getInstance($iSwitchToProfileId);
  659. if (!$oProfile) {
  660. return _t('_sys_txt_error_occured');
  661. }
  662. $iViewerAccountId = getLoggedId();
  663. $iSwitchToAccountId = $oProfile->getAccountId();
  664. $iViewerProfileId = bx_get_logged_profile_id();
  665. $aCheck = checkActionModule($iViewerProfileId, 'switch to any profile', 'system', false);
  666. $bAllowSwitchToAnyProfile = $aCheck[CHECK_ACTION_RESULT] === CHECK_ACTION_RESULT_ALLOWED;
  667. $bCanSwitch = ($iSwitchToAccountId == $iViewerAccountId || $bAllowSwitchToAnyProfile);
  668. /**
  669. * @hooks
  670. * @hookdef hook-account-check_switch_context 'account', 'check_switch_context' - hook on switch profile_id
  671. * - $unit_name - equals `account`
  672. * - $action - equals `check_switch_context`
  673. * - $object_id - account id
  674. * - $sender_id - viewer profile_id
  675. * - $extra_params - array of additional params with the following array keys:
  676. * - `switch_to_profile` - [int] profile_id to switch
  677. * - `viewer_account` - [int] viewer's profile_id, can be overridden in hook processing
  678. * - `override_result` - [bool] by ref, true if allow switch profile, otherwise false, can be overridden in hook processing
  679. * @hook @ref hook-account-check_switch_context
  680. */
  681. bx_alert('account', 'check_switch_context', $iSwitchToAccountId, $iViewerProfileId, array('switch_to_profile' => $iSwitchToProfileId, 'viewer_account' => $iViewerAccountId, 'override_result' => &$bCanSwitch));
  682. if (!$bCanSwitch) {
  683. return isset($aCheck[CHECK_ACTION_MESSAGE]) ? $aCheck[CHECK_ACTION_MESSAGE] : _t('_sys_txt_error_occured');
  684. }
  685. $oAccount = BxDolAccount::getInstance();
  686. if (!$oAccount->updateProfileContext($iSwitchToProfileId)) {
  687. return _t('_sys_txt_error_occured');
  688. }
  689. checkActionModule($iViewerProfileId, 'switch to any profile', 'system', true);
  690. if (bx_is_api()){
  691. return BxDolProfile::getDataForPage($iSwitchToProfileId);
  692. }
  693. return true;
  694. }
  695. /**
  696. * Reset password procedure
  697. */
  698. public function resetPassword()
  699. {
  700. $bApi = bx_is_api();
  701. $sKey = bx_process_input(bx_get('key'));
  702. $oForm = BxDolForm::getObjectInstance('sys_forgot_password', 'sys_forgot_password_reset');
  703. if(!empty($sKey) && isset($oForm->aInputs['key']))
  704. $oForm->aInputs['key']['value'] = $sKey;
  705. $oForm->initChecker();
  706. if($oForm->isSubmittedAndValid()) {
  707. $sErrorUrl = bx_absolute_url(BxDolPermalinks::getInstance()->permalink('page.php?i=forgot-password'));
  708. // check if key exists
  709. $oKey = BxDolKey::getInstance();
  710. $sKey = $oForm->getCleanValue('key');
  711. if(!$oKey || !$oKey->isKeyExists($sKey))
  712. return $bApi ? bx_api_get_msg(_t('_sys_txt_reset_pasword_error_invalid_key', $sErrorUrl)) : MsgBox(_t('_sys_txt_reset_pasword_error_invalid_key', $sErrorUrl));
  713. // check if key data exists
  714. $aKeyData = $oKey->getKeyData($sKey);
  715. if(empty($aKeyData['email']))
  716. return $bApi ? [bx_api_get_msg(_t('_sys_txt_reset_pasword_error_invalid_key', $sErrorUrl))] : MsgBox(_t('_sys_txt_reset_pasword_error_invalid_key', $sErrorUrl));
  717. // check if account with such email exists
  718. $iAccountId = $this->_oAccountQuery->getIdByEmail($aKeyData['email']);
  719. if(empty($iAccountId))
  720. return $bApi ? [bx_api_get_msg(_t('_sys_txt_reset_pasword_error_not_found', $sErrorUrl))] : MsgBox(_t('_sys_txt_reset_pasword_error_not_found', $sErrorUrl));;
  721. $sPassword = $oForm->getCleanValue('password');
  722. $oAccount = BxDolAccount::getInstance($iAccountId);
  723. if (!$oAccount || !$oAccount->updatePassword($sPassword))
  724. return $bApi ?[ bx_api_get_msg(_t('_sys_txt_reset_pasword_error_occured', $sErrorUrl))] : MsgBox(_t('_sys_txt_reset_pasword_error_occured', $sErrorUrl));
  725. $this->_oAccountQuery->unlockAccount($iAccountId);
  726. $oKey->removeKey($sKey);
  727. return $bApi ? [bx_api_get_msg(_t('_sys_txt_reset_pasword_success', $sErrorUrl))] : MsgBox(_t('_sys_txt_reset_pasword_success'), 3) . bx_srv('system', 'login_form_only', array('', bx_get_reset_password_redirect($iAccountId)), 'TemplServiceLogin');
  728. }
  729. $sTitleReset = _t('_sys_page_title_forgot_password_reset');
  730. BxDolTemplate::getInstance()->setPageHeader($sTitleReset);
  731. if(($oPage = BxDolPage::getObjectInstanceByURI()) !== false)
  732. $oPage->setTitle($sTitleReset);
  733. if($bApi) {
  734. return [
  735. bx_api_get_block('form', $oForm->getCodeAPI(), [
  736. 'ext' => [
  737. 'request' => ['url' => '/api.php?r=system/forgot_password/TemplServiceAccount', 'immutable' => true]
  738. ]
  739. ])];
  740. }
  741. return $oForm->getCode();
  742. }
  743. /**
  744. * Generate new password.
  745. */
  746. public function generateUserNewPwd($iAccountId)
  747. {
  748. $sPassword = genRndPwd(8, false);
  749. $sSalt = genRndSalt();
  750. $sPasswordHash = encryptUserPwd($sPassword, $sSalt);
  751. $this->_oAccountQuery->logPassword($iAccountId);
  752. $this->_oAccountQuery->updatePassword($sPasswordHash, $sSalt, $iAccountId);
  753. /**
  754. * @hooks
  755. * @hookdef hook-account-edited 'account', 'edited' - hook on account edited
  756. * - $unit_name - equals `account`
  757. * - $action - equals `edited`
  758. * - $object_id - account id
  759. * - $sender_id - account id
  760. * - $extra_params - array of additional params with the following array keys:
  761. * - `action` - [string] can be forgot_password/change_password or $sDisplayName (display name for current form)
  762. * @hook @ref hook-account-edited
  763. */
  764. bx_alert('account', 'edited', $iAccountId, $iAccountId, [
  765. 'action' => 'forgot_password'
  766. ]);
  767. return $sPassword;
  768. }
  769. protected function _confirmEmail($sKey)
  770. {
  771. // check if key exists
  772. $oKey = BxDolKey::getInstance();
  773. if (!$oKey || !$oKey->isKeyExists($sKey))
  774. return _t("_sys_txt_confirm_email_error_occured");
  775. // check if key data exists
  776. $aData = $oKey->getKeyData($sKey);
  777. if (!isset($aData['account_id']))
  778. return _t("_sys_txt_confirm_email_error_occured");
  779. // check if account exists
  780. $oAccount = BxDolAccount::getInstance($aData['account_id']);
  781. if (!$oAccount)
  782. return _t("_sys_txt_confirm_email_error_occured");
  783. // remove key
  784. $oKey->removeKey($sKey);
  785. // confirm email
  786. if (!$oAccount->updateEmailConfirmed(true))
  787. return _t("_sys_txt_confirm_email_error_occured");
  788. // login to user's account automatically
  789. bx_login($aData['account_id'], bx_is_remember_me());
  790. return (int)$aData['account_id'];
  791. }
  792. }
  793. /** @} */