Index: trunk/core/units/users/users_event_handler.php =================================================================== diff -u -N --- trunk/core/units/users/users_event_handler.php (revision 8842) +++ trunk/core/units/users/users_event_handler.php (revision 0) @@ -1,1330 +0,0 @@ - Array('self' => 'view'), // because setting to logged in user only - 'OnUpdateRootPassword' => Array('self' => true), // because setting to logged in user only - - // front - 'OnRefreshForm' => Array('self' => true), - - 'OnForgotPassword' => Array('self' => true), - 'OnResetPassword' => Array('self' => true), - 'OnResetPasswordConfirmed' => Array('self' => true), - - 'OnSubscribeQuery' => Array('self' => true), - 'OnSubscribeUser' => Array('self' => true), - - 'OnRecommend' => Array('self' => true), - - 'OnItemBuild' => Array('self' => true), - ); - - $this->permMapping = array_merge($this->permMapping, $permissions); - } - - /** - * Shows only admins when required - * - * @param kEvent $event - */ - function SetCustomQuery(&$event) - { - $object =& $event->getObject(); - /* @var $object kDBList */ - - if ($event->Special == 'admins') { - $object->addFilter('primary_filter', 'ug.GroupId = 11'); - } - - if ($event->Special == 'regular') { - $object->addFilter('primary_filter', 'ug.GroupId <> 11'); - } - - if (!$this->Application->IsAdmin()) { - $object->addFilter('status_filter', '%1$s.Status = '.STATUS_ACTIVE); - } - } - - - /** - * Checks permissions of user - * - * @param kEvent $event - */ - function CheckPermission(&$event) - { - if ($event->Name == 'OnLogin' || $event->Name == 'OnLogout') { - // permission is checked in OnLogin event directly - return true; - } - - if (!$this->Application->IsAdmin()) { - $user_id = $this->Application->RecallVar('user_id'); - $items_info = $this->Application->GetVar($event->getPrefixSpecial(true)); - - if ($event->Name == 'OnCreate' && $user_id == -2) { - // "Guest" can create new users - return true; - } - - if ($event->Name == 'OnUpdate' && $user_id > 0) { - $user_dummy =& $this->Application->recallObject($event->Prefix.'.-item', null, Array('skip_autoload' => true)); - foreach ($items_info as $id => $field_values) { - if ($id != $user_id) { - // registered users can update their record only - return false; - } - - $user_dummy->Load($id); - $status_field = array_shift($this->Application->getUnitOption($event->Prefix, 'StatusField')); - - if ($user_dummy->GetDBField($status_field) != STATUS_ACTIVE) { - // not active user is not allowed to update his record (he could not activate himself manually) - return false; - } - - if (isset($field_values[$status_field]) && $user_dummy->GetDBField($status_field) != $field_values[$status_field]) { - // user can't change status by himself - return false; - } - } - return true; - } - - if ($event->Name == 'OnUpdate' && $user_id <= 0) { - // guests are not allowed to update their record, because they don't have it :) - return false; - } - } - - return parent::CheckPermission($event); - } - - function OnSessionExpire() - { - $this->Application->resetCounters('UserSession'); - - if ($this->Application->IsAdmin()) { - $this->Application->Redirect('index', Array('expired' => 1), '', 'index.php'); - } - - if ($this->Application->GetVar('admin') == 1) { - $session_admin =& $this->Application->recallObject('Session.admin'); - /* @var $session_admin Session */ - - if (!$session_admin->LoggedIn()) { - // front-end session created from admin session & both expired - $this->Application->DeleteVar('admin'); - $this->Application->Redirect('index', Array('expired' => 1), '', 'admin/index.php'); - } - } - - $get = $this->Application->HttpQuery->getRedirectParams(); - $t = $this->Application->GetVar('t'); - $get['js_redirect'] = $this->Application->ConfigValue('UseJSRedirect'); - $this->Application->Redirect($t ? $t : 'index', $get); - } - - /** - * Checks user data and logs it in if allowed - * - * @param kEvent $event - */ - function OnLogin(&$event) - { - // persistent session data after login is not refreshed, because redirect will follow in any case - $prefix_special = $this->Application->IsAdmin() ? 'u.current' : 'u'; // "u" used on front not to change theme - $object =& $this->Application->recallObject($prefix_special, null, Array('skip_autoload' => true)); - $password = $this->Application->GetVar('password'); - - $invalid_pseudo = $this->Application->IsAdmin() ? 'la_invalid_password' : 'lu_invalid_password'; - - if(!$password) - { - $object->SetError('ValidateLogin', 'invalid_password', $invalid_pseudo); - $event->status = erFAIL; - return false; - } - - $email_as_login = $this->Application->ConfigValue('Email_As_Login'); - list($login_field, $submit_field) = $email_as_login && !$this->Application->IsAdmin() ? Array('Email', 'email') : Array('Login', 'login'); - $login_value = $this->Application->GetVar($submit_field); - - // process "Save Username" checkbox - if ($this->Application->IsAdmin()) { - $save_username = $this->Application->GetVar('cb_save_username') ? $login_value : ''; - $this->Application->Session->SetCookie('save_username', $save_username, adodb_mktime() + 31104000); // 1 year expiration - $this->Application->SetVar('save_username', $save_username); // cookie will be set on next refresh, but refresh won't occur if login error present, so duplicate cookie in HTTPQuery - } - - $super_admin = ($login_value == 'super-root') && $this->verifySuperAdmin(); - if ($this->Application->IsAdmin() && ($login_value == 'root') || ($super_admin && $login_value == 'super-root')) { - // logging in "root" (admin only) - - $login_value = 'root'; - - $root_password = $this->Application->ConfigValue('RootPass'); - $password_formatter =& $this->Application->recallObject('kPasswordFormatter'); - $test = $password_formatter->EncryptPassword($password, 'b38'); - if ($root_password != $test) { - $object->SetError('ValidateLogin', 'invalid_password', $invalid_pseudo); - $event->status = erFAIL; - return false; - } - elseif ($this->checkLoginPermission($login_value)) { - $user_id = -1; - $object->Load($user_id); - $object->SetDBField('Login', $login_value); - - $session =& $this->Application->recallObject('Session'); - $session->SetField('PortalUserId', $user_id); -// $session->SetField('GroupList', implode(',', $groups) ); - $this->Application->SetVar('u.current_id', $user_id); - $this->Application->StoreVar('user_id', $user_id); - - if ($super_admin) { - $this->Application->StoreVar('super_admin', 1); - } - - $this->processLoginRedirect($event, $password); - return true; - } - else { - $object->SetError('ValidateLogin', 'invalid_license', 'la_invalid_license'); - $event->status = erFAIL; - return false; - } - } - - /*$sql = 'SELECT PortalUserId FROM '.$object->TableName.' WHERE (%s = %s) AND (Password = MD5(%s))'; - $user_id = $this->Conn->GetOne( sprintf($sql, $login_field, $this->Conn->qstr($login_value), $this->Conn->qstr($password) ) );*/ - - $sql = 'SELECT PortalUserId FROM '.$object->TableName.' WHERE (Email = %1$s OR Login = %1$s) AND (Password = MD5(%2$s))'; - $user_id = $this->Conn->GetOne( sprintf($sql, $this->Conn->qstr($login_value), $this->Conn->qstr($password) ) ); - - if ($user_id) { - $object->Load($user_id); - if ($object->GetDBField('Status') == STATUS_ACTIVE) { - $groups = $object->getMembershipGroups(true); - if(!$groups) $groups = Array(); - array_push($groups, $this->Application->ConfigValue('User_LoggedInGroup') ); - $this->Application->StoreVar( 'UserGroups', implode(',', $groups) ); - - if ($this->checkLoginPermission($login_value)) { - $session =& $this->Application->recallObject('Session'); - $session->SetField('PortalUserId', $user_id); - $session->SetField('GroupList', implode(',', $groups) ); - $this->Application->SetVar('u.current_id', $user_id); - $this->Application->StoreVar('user_id', $user_id); - - $this_login = (int)$object->getPersistantVar('ThisLogin'); - $object->setPersistantVar('LastLogin', $this_login); - $object->setPersistantVar('ThisLogin', adodb_mktime()); - } - else { - $object->Load(-2); - $object->SetError('ValidateLogin', 'no_permission', 'lu_no_permissions'); - $event->status = erFAIL; - } - - $this->processLoginRedirect($event, $password); - } - else { - $event->redirect = $this->Application->GetVar('pending_disabled_template'); - } - } - else - { - $object->SetID(-2); - $object->SetError('ValidateLogin', 'invalid_password', $invalid_pseudo); - $event->status = erFAIL; - } - - $event->SetRedirectParam('pass', 'all'); - } - - /** - * Checks that user is allowed to use super admin mode - * - * @return bool - */ - function verifySuperAdmin() - { - $sa_mode = ipMatch(defined('SA_IP') ? SA_IP : ''); - return $sa_mode || $this->Application->isDebugMode(); - } - - /** - * Enter description here... - * - * @param string $user_name - * @return bool - */ - function checkLoginPermission($user_name) - { - $ret = true; - if ($this->Application->IsAdmin()) { - $modules_helper =& $this->Application->recallObject('ModulesHelper'); - if ($user_name != 'root') { - // root is virtual user, so allow him to login to admin in any case - $ret = $this->Application->CheckPermission('ADMIN', 1); - } - $ret = $ret && $modules_helper->checkLogin(); - } - else { - $ret = $this->Application->CheckPermission('LOGIN', 1); - } - return $ret; - } - - /** - * Process all required data and redirect logged-in user - * - * @param kEvent $event - */ - function processLoginRedirect(&$event, $password) - { - $prefix_special = $this->Application->IsAdmin() ? 'u.current' : 'u'; // "u" used on front not to change theme - $object =& $this->Application->recallObject($prefix_special, null, Array('skip_autoload' => true)); - - $next_template = $this->Application->GetVar('next_template'); - if ($next_template == '_ses_redirect') { - $location = $this->Application->BaseURL().$this->Application->RecallVar($next_template); - if( $this->Application->isDebugMode() && constOn('DBG_REDIRECT') ) - { - $this->Application->Debugger->appendTrace(); - echo "Debug output above!!! Proceed to redirect: $location
"; - } - else { - header('Location: '.$location); - } - - $session =& $this->Application->recallObject('Session'); - $session->SaveData(); - exit; - } - - if ($next_template) { - $event->redirect = $next_template; - } - - if ($this->Application->ConfigValue('UseJSRedirect')) { - $event->SetRedirectParam('js_redirect', 1); - } - - $sync_manager =& $this->Application->recallObjectP('UsersSyncronizeManager', null, Array(), 'InPortalSyncronize'); - $sync_manager->performAction('LoginUser', $object->GetDBField('Login'), $password); - $this->Application->resetCounters('UserSession'); - } - - /** - * Called when user logs in using old in-portal - * - * @param kEvent $event - */ - function OnInpLogin(&$event) - { - $sync_manager =& $this->Application->recallObjectP('UsersSyncronizeManager', null, Array(), 'InPortalSyncronize'); - $sync_manager->performAction('LoginUser', $event->getEventParam('user'), $event->getEventParam('pass') ); - - if ($event->redirect && is_string($event->redirect)) { - // some real template specified instead of true - $this->Application->Redirect($event->redirect, $event->redirect_params); - } - } - - /** - * Called when user logs in using old in-portal - * - * @param kEvent $event - */ - function OnInpLogout(&$event) - { - $sync_manager =& $this->Application->recallObjectP('UsersSyncronizeManager', null, Array(), 'InPortalSyncronize'); - $sync_manager->performAction('LogoutUser'); - } - - function OnLogout(&$event) - { - $sync_manager =& $this->Application->recallObjectP('UsersSyncronizeManager', null, Array(), 'InPortalSyncronize'); - $sync_manager->performAction('LogoutUser'); - - $session =& $this->Application->recallObject('Session'); - $session->SetField('PortalUserId', -2); - $this->Application->SetVar('u.current_id', -2); - $this->Application->StoreVar('user_id', -2); - $object =& $this->Application->recallObject('u.current', null, Array('skip_autoload' => true)); - $object->Load(-2); - - $this->Application->DestroySession(); - - $group_list = $this->Application->ConfigValue('User_GuestGroup').','.$this->Application->ConfigValue('User_LoggedInGroup'); - $session->SetField('GroupList', $group_list); - $this->Application->StoreVar('UserGroups', $group_list); - - if ($this->Application->ConfigValue('UseJSRedirect')) { - $event->SetRedirectParam('js_redirect', 1); - } - - $this->Application->resetCounters('UserSession'); - $event->SetRedirectParam('pass', 'all'); - } - - /** - * Prefill states dropdown with correct values - * - * @param kEvent $event - * @access public - */ - function OnPrepareStates(&$event) - { - $cs_helper =& $this->Application->recallObject('CountryStatesHelper'); - $cs_helper->PopulateStates($event, 'State', 'Country'); - - $object =& $event->getObject(); - - if( $object->isRequired('Country') && $cs_helper->CountryHasStates( $object->GetDBField('Country') ) ) $object->setRequired('State', true); - $object->setLogin(); - } - - /** - * Redirects user after succesfull registration to confirmation template (on Front only) - * - * @param kEvent $event - */ - function OnAfterItemCreate(&$event) - { - $is_subscriber = $this->Application->GetVar('IsSubscriber'); - if(!$is_subscriber) - { - $object =& $event->getObject(); - - $ug_table = TABLE_PREFIX.'UserGroup'; - if ($object->mode == 't') { - $ug_table = $this->Application->GetTempName($ug_table, 'prefix:'.$event->Prefix); - } - - $sql = 'UPDATE '.$ug_table.' - SET PrimaryGroup = 0 - WHERE PortalUserId = '.$object->GetDBField('PortalUserId'); - $this->Conn->Query($sql); - - // set primary group to user - if ($this->Application->IsAdmin() && $this->Application->GetVar('user_group')) { - // while in admin you can set any group for new users - $group_id = $this->Application->GetVar('user_group'); - } - else { - $group_id = $this->Application->ConfigValue('User_NewGroup'); - } - - $sql = 'REPLACE INTO '.$ug_table.'(PortalUserId,GroupId,PrimaryGroup) VALUES (%s,%s,1)'; - $this->Conn->Query( sprintf($sql, $object->GetID(), $group_id) ); - } - } - - /** - * Login user if possible, if not then redirect to corresponding template - * - * @param kEvent $event - */ - function autoLoginUser(&$event) - { - $object =& $event->getObject(); - $this->Application->SetVar('u.current_id', $object->GetID() ); - - if($object->GetDBField('Status') == STATUS_ACTIVE && !$this->Application->ConfigValue('User_Password_Auto')) - { - $email_as_login = $this->Application->ConfigValue('Email_As_Login'); - list($login_field, $submit_field) = $email_as_login ? Array('Email', 'email') : Array('Login', 'login'); - - $this->Application->SetVar($submit_field, $object->GetDBField($login_field) ); - $this->Application->SetVar('password', $object->GetDBField('Password_plain') ); - - $event->CallSubEvent('OnLogin'); - } - } - - - /** - * When creating user & user with such email exists then force to use OnUpdate insted of ? - * - * @param kEvent $event - */ - function OnSubstituteSubscriber(&$event) - { - $ret = false; - $object =& $event->getObject( Array('skip_autoload' => true) ); - $items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) ); - if($items_info) - { - list($id, $field_values) = each($items_info); - $user_email = isset($field_values['Email']) ? $field_values['Email'] : false; - if($user_email) - { - // check if is subscriber - $verify_user =& $this->Application->recallObject('u.verify', null, Array('skip_autoload' => true) ); - $verify_user->Load($user_email, 'Email'); - if( $verify_user->isLoaded() && $verify_user->isSubscriberOnly() ) - { - $items_info = Array( $verify_user->GetDBField('PortalUserId') => $field_values ); - $this->Application->SetVar($event->getPrefixSpecial(true), $items_info); - $ret = true; - } - } - } - - if( isset($event->MasterEvent) ) - { - $event->MasterEvent->setEventParam('is_subscriber_only', $ret); - } - else - { - $event->setEventParam('is_subscriber_only', $ret); - } - } - - - /** - * Enter description here... - * - * @param kEvent $event - * @return bool - */ - function isSubscriberOnly(&$event) - { - $event->CallSubEvent('OnSubstituteSubscriber'); - $is_subscriber = false; - if( $event->getEventParam('is_subscriber_only') ) - { - $is_subscriber = true; - $object =& $event->getObject( Array('skip_autoload' => true) ); - $this->OnUpdate($event); - if($event->status == erSUCCESS) - { - $this->OnAfterItemCreate($event); - $object->SendEmailEvents(); - if( !$this->Application->IsAdmin() && ($event->status == erSUCCESS) && $event->redirect) $this->autoLoginUser($event); - } - } - return $is_subscriber; - } - - /** - * Creates new user - * - * @param kEvent $event - */ - function OnCreate(&$event) - { - if( !$this->Application->IsAdmin() ) $this->setUserStatus($event); - - if( !$this->isSubscriberOnly($event) ) - { - $cs_helper =& $this->Application->recallObject('CountryStatesHelper'); - $cs_helper->CheckStateField($event, 'State', 'Country'); - - $object =& $event->getObject( Array('skip_autoload' => true) ); - /* @var $object kDBItem */ - if ($this->Application->ConfigValue('User_Password_Auto')) { - $pass = makepassword4(rand(5,8)); - $object->SetField('Password', $pass); - $object->SetField('VerifyPassword', $pass); - $this->Application->SetVar('user_password',$pass); - } - parent::OnCreate($event); - - $this->Application->SetVar('u.current_id', $object->getID() ); // for affil:OnRegisterAffiliate after hook - - $this->setNextTemplate($event); - - if( !$this->Application->IsAdmin() && ($event->status == erSUCCESS) && $event->redirect) - { - $object->SendEmailEvents(); - $this->autoLoginUser($event); - } - } - } - - /** - * Set's new user status based on config options - * - * @param kEvent $event - */ - function setUserStatus(&$event) - { - $object =& $event->getObject( Array('skip_autoload' => true) ); - - $new_users_allowed = $this->Application->ConfigValue('User_Allow_New'); - // 1 - Instant, 2 - Not Allowed, 3 - Pending - - switch ($new_users_allowed) - { - case 1: // Instant - $object->SetDBField('Status', 1); - $next_template = $this->Application->GetVar('registration_confirm_template'); - if($next_template) $event->redirect = $next_template; - break; - - case 3: // Pending - $next_template = $this->Application->GetVar('registration_confirm_pending_template'); - if($next_template) $event->redirect = $next_template; - $object->SetDBField('Status', 2); - break; - - case 2: // Not Allowed - $object->SetDBField('Status', 0); - break; - } - - /*if ($object->GetDBField('PaidMember') == 1) { - $this->Application->HandleEvent($add_to_cart, 'ord:OnAddToCart'); - $event->redirect = 'in-commerce/checkout/shop_cart'; - } */ - - } - - - - - /** - * Set's new unique resource id to user - * - * @param kEvent $event - */ - function OnBeforeItemCreate(&$event) - { - $email_as_login = $this->Application->ConfigValue('Email_As_Login'); - $object =& $event->getObject(); - if ($email_as_login) { - $object->Fields['Email']['error_msgs']['unique'] = $this->Application->Phrase('lu_user_and_email_already_exist'); - } - - } - - /** - * Set's new unique resource id to user - * - * @param kEvent $event - */ - function OnAfterItemValidate(&$event) - { - $object =& $event->getObject(); - $resource_id = $object->GetDBField('ResourceId'); - if (!$resource_id) - { - $object->SetDBField('ResourceId', $this->Application->NextResourceId() ); - } - } - - - /** - * Enter description here... - * - * @param kEvent $event - */ - function OnRecommend(&$event) - { - $friend_email = $this->Application->GetVar('friend_email'); - $friend_name = $this->Application->GetVar('friend_email'); - - // used for error reporting only -> rewrite code + theme (by Alex) - $object =& $this->Application->recallObject('u', null, Array('skip_autoload' => true)); // TODO: change theme too - /* @var $object UsersItem */ - - if (preg_match("/^[_a-zA-Z0-9-\.]+@[a-zA-Z0-9-\.]+\.[a-z]{2,4}$/", $friend_email)) - { - $send_params = array(); - $send_params['to_email']=$friend_email; - $send_params['to_name']=$friend_name; - - $user_id = $this->Application->RecallVar('user_id'); - $email_event =& $this->Application->EmailEventUser('SITE.SUGGEST', $user_id, $send_params); - - if ($email_event->status == erSUCCESS){ - $event->redirect_params = array('opener' => 's', 'pass' => 'all'); - $event->redirect = $this->Application->GetVar('template_success'); - } - else { -// $event->redirect_params = array('opener' => 's', 'pass' => 'all'); -// $event->redirect = $this->Application->GetVar('template_fail'); - - $object->SetError('Email', 'send_error', 'lu_email_send_error'); - $event->status = erFAIL; - } - } - else { - $object->SetError('Email', 'invalid_email', 'lu_InvalidEmail'); - $event->status = erFAIL; - } - } - - /** - * Saves address changes and mades no redirect - * - * @param kEvent $event - */ - function OnUpdateAddress(&$event) - { - $object =& $event->getObject( Array('skip_autoload' => true) ); - - $items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) ); - if($items_info) - { - list($id,$field_values) = each($items_info); - if($id > 0) $object->Load($id); - $object->SetFieldsFromHash($field_values); - $object->setID($id); - $object->Validate(); - } - - $event->redirect = false; - } - - /** - * Validate subscriber's email & store it to session -> redirect to confirmation template - * - * @param kEvent $event - */ - function OnSubscribeQuery(&$event) - { - $user_email = $this->Application->GetVar('subscriber_email'); - if (preg_match("/^[_a-zA-Z0-9-\.]+@[a-zA-Z0-9-\.]+\.[a-z]{2,4}$/", $user_email)) { - - $object =& $this->Application->recallObject($this->Prefix.'.subscriber', null, Array('skip_autoload' => true)); - /* @var $object UsersItem */ - - $this->Application->StoreVar('SubscriberEmail', $user_email); - - $object->Load($user_email, 'Email'); - if ($object->isLoaded()) { - $group_info = $this->GetGroupInfo($object->GetID()); - $event->redirect = $this->Application->GetVar($group_info ? 'unsubscribe_template' : 'subscribe_template'); - } - else { - $event->redirect = $this->Application->GetVar('subscribe_template'); - $this->Application->StoreVar('SubscriberEmail', $user_email); - } - } - else { - // used for error reporting only -> rewrite code + theme (by Alex) - $object =& $this->Application->recallObject('u', null, Array('skip_autoload' => true)); // TODO: change theme too - /* @var $object UsersItem */ - - $object->SetError('SubscribeEmail', 'invalid_email', 'lu_InvalidEmail'); - $event->status = erFAIL; - } - } - - /** - * Subscribe/Unsubscribe user based on email stored in previous step - * - * @param kEvent $event - */ - function OnSubscribeUser(&$event) - { - $object = &$this->Application->recallObject($this->Prefix.'.subscriber', null, Array('skip_autoload' => true)); - /* @var $object UsersItem */ - - $user_email = $this->Application->RecallVar('SubscriberEmail'); - if (preg_match("/^[_a-zA-Z0-9-\.]+@[a-zA-Z0-9-\.]+\.[a-z]{2,4}$/", $user_email)) { - $this->RemoveRequiredFields($object); - $object->Load($user_email, 'Email'); - - if ($object->isLoaded()) { - $group_info = $this->GetGroupInfo($object->GetID()); - - if ($group_info){ - if ($event->getEventParam('no_unsubscribe')) return; - - if ($group_info['PrimaryGroup']){ - // delete user - $object->Delete(); - } - else { - $this->RemoveSubscriberGroup($object->GetID()); - } - - $event->redirect = $this->Application->GetVar('unsubscribe_ok_template'); - } - else { - $this->AddSubscriberGroup($object->GetID(), 0); - $event->redirect = $this->Application->GetVar('subscribe_ok_template'); - } - } - else { - $object->SetField('Email', $user_email); - $object->SetField('Login', $user_email); - $object->SetDBField('dob', 1); - $object->SetDBField('dob_date', 1); - $object->SetDBField('dob_time', 1); - $ip = getenv('HTTP_X_FORWARDED_FOR')?getenv('HTTP_X_FORWARDED_FOR'):getenv('REMOTE_ADDR'); - $object->SetDBField('ip', $ip); - - $this->Application->SetVar('IsSubscriber', 1); - - if ($object->Create()) { - $this->AddSubscriberGroup($object->GetID(), 1); - $event->redirect = $this->Application->GetVar('subscribe_ok_template'); - } - - $this->Application->SetVar('IsSubscriber', 0); - } - } - } - - function AddSubscriberGroup($user_id, $is_primary){ - - $group_id = $this->Application->ConfigValue('User_SubscriberGroup'); - $sql = 'INSERT INTO '.TABLE_PREFIX.'UserGroup(PortalUserId,GroupId,PrimaryGroup) VALUES (%s,%s,'.$is_primary.')'; - $this->Conn->Query( sprintf($sql, $user_id, $group_id) ); - $this->Application->EmailEventAdmin('USER.SUBSCRIBE', $user_id); - $this->Application->EmailEventUser('USER.SUBSCRIBE', $user_id); - - } - - function RemoveSubscriberGroup($user_id){ - - $group_id = $this->Application->ConfigValue('User_SubscriberGroup'); - $sql = 'DELETE FROM '.TABLE_PREFIX.'UserGroup WHERE PortalUserId='.$user_id.' AND GroupId='.$this->Application->ConfigValue('User_SubscriberGroup'); - $this->Conn->Query($sql); - $this->Application->EmailEventAdmin('USER.UNSUBSCRIBE', $user_id); - $this->Application->EmailEventUser('USER.UNSUBSCRIBE', $user_id); - - } - - /** - * Allows to detect user subscription status (subscribed or not) - * - * @param int $user_id - * @return bool - */ - function GetGroupInfo($user_id) - { - $sql = 'SELECT * - FROM '.TABLE_PREFIX.'UserGroup - WHERE (PortalUserId = '.$user_id.') AND (GroupId = '.$this->Application->ConfigValue('User_SubscriberGroup').')'; - return $this->Conn->GetRow($sql); - } - - function OnForgotPassword(&$event) - { - $user_object =& $this->Application->recallObject('u.forgot', null, Array('skip_autoload' => true)); - /* @var $user_object UsersItem */ - - // used for error reporting only -> rewrite code + theme (by Alex) - $user_current_object =& $this->Application->recallObject('u', null, Array('skip_autoload' => true)); // TODO: change theme too - /* @var $user_current_object UsersItem */ - - $username = $this->Application->GetVar('username'); - $email = $this->Application->GetVar('email'); - $found = false; - $allow_reset = true; - - if (strlen($username)) { - $user_object->Load($username, 'Login'); - if ($user_object->isLoaded()) { - $found = ($user_object->GetDBField("Login")==$username && $user_object->GetDBField("Status")==1) && strlen($user_object->GetDBField("Password")); - } - } - else if(strlen($email)) { - $user_object->Load($email, 'Email'); - if ($user_object->isLoaded()) { - $found = ($user_object->GetDBField("Email")==$email && $user_object->GetDBField("Status")==1) && strlen($user_object->GetDBField("Password")); - } - } - - if ($user_object->isLoaded()) { - $PwResetConfirm = $user_object->GetDBField('PwResetConfirm'); - $PwRequestTime = $user_object->GetDBField('PwRequestTime'); - $PassResetTime = $user_object->GetDBField('PassResetTime'); - //$MinPwResetDelay = $user_object->GetDBField('MinPwResetDelay'); - $MinPwResetDelay = $this->Application->ConfigValue('Users_AllowReset'); - - $allow_reset = (strlen($PwResetConfirm) ? - adodb_mktime() > $PwRequestTime + $MinPwResetDelay : - adodb_mktime() > $PassResetTime + $MinPwResetDelay); - } - - if ($found && $allow_reset) { - $this->Application->StoreVar('tmp_user_id', $user_object->GetDBField("PortalUserId")); - $this->Application->StoreVar('tmp_email', $user_object->GetDBField("Email")); - $this->Application->EmailEventUser('INCOMMERCEUSER.PSWDC', $user_object->GetDBField("PortalUserId")); - - $event->redirect = $this->Application->GetVar('template_success'); - } - else { - if (!strlen($username) && !strlen($email)) { - $user_current_object->SetError('Login', 'forgotpw_nodata', 'lu_ferror_forgotpw_nodata'); - $user_current_object->SetError('Email', 'forgotpw_nodata', 'lu_ferror_forgotpw_nodata'); - } - else { - if ($allow_reset) { - if (strlen($username)) { - $user_current_object->SetError('Login', 'unknown_username', 'lu_ferror_unknown_username'); - } - if (strlen($email)) { - $user_current_object->SetError('Email', 'unknown_email', 'lu_ferror_unknown_email'); - } - } - else { - if (strlen($username)) { - $user_current_object->SetError('Login', 'reset_denied', 'lu_ferror_reset_denied'); - } - - if (strlen($email)) { - $user_current_object->SetError('Email', 'reset_denied', 'lu_ferror_reset_denied'); - } - } - } - - if($user_current_object->FieldErrors){ - $event->redirect = false; - } - } - } - - /** - * Enter description here... - * - * @param kEvent $event - */ - function OnResetPassword(&$event) - { - $user_object =& $this->Application->recallObject('u.forgot'); - - if($user_object->Load($this->Application->RecallVar('tmp_user_id'))){ - - $this->Application->EmailEventUser('INCOMMERCEUSER.PSWDC', $user_object->GetDBField("PortalUserId")); - $event->redirect = $this->Application->GetVar('template_success'); - - $m_cat_id = $this->Application->findModule('Name', 'In-Commerce', 'RootCat'); - $this->Application->SetVar('m_cat_id', $m_cat_id); - $event->SetRedirectParam('pass', 'm'); - } - } - - function OnResetPasswordConfirmed(&$event) - { - $passed_key = $this->Application->GetVar('user_key'); - - $user_object = &$this->Application->recallObject('u.forgot'); - - // used for error reporting only -> rewrite code + theme (by Alex) - $user_current_object =& $this->Application->recallObject('u', null, Array('skip_autoload' => true));// TODO: change theme too - /* @var $user_current_object UsersItem */ - - if (strlen(trim($passed_key)) == 0) { - $event->redirect_params = array('opener' => 's', 'pass' => 'all'); - $event->redirect = false; - - $user_current_object->SetError('PwResetConfirm', 'code_is_not_valid', 'lu_code_is_not_valid'); - } - - - if($user_object->Load(array('PwResetConfirm'=>$passed_key))) - { - $exp_time = $user_object->GetDBField('PwRequestTime') + 3600; - $user_object->SetDBField("PwResetConfirm", ''); - $user_object->SetDBField("PwRequestTime", 0); - if ( $exp_time > adodb_mktime() ) - { - //$m_var_list_update['codevalidationresult'] = 'lu_resetpw_confirm_text'; - $newpw = makepassword4(); - - $this->Application->StoreVar('password', $newpw); - - $user_object->SetDBField("Password",$newpw); - $user_object->SetDBField("PassResetTime", adodb_mktime()); - $user_object->SetDBField("PwResetConfirm", ''); - $user_object->SetDBField("PwRequestTime", 0); - $user_object->Update(); - - $this->Application->SetVar('ForgottenPassword', $newpw); - - $email_event_user = &$this->Application->EmailEventUser('INCOMMERCEUSER.PSWD', $user_object->GetDBField('PortalUserId')); - $email_event_admin = &$this->Application->EmailEventAdmin('INCOMMERCEUSER.PSWD'); - - $this->Application->DeleteVar('ForgottenPassword'); - - if ($email_event_user->status == erSUCCESS){ - $event->redirect_params = array('opener' => 's', 'pass' => 'all'); - $event->redirect = $this->Application->GetVar('template_success'); - } - - $user_object->SetDBField("Password",md5($newpw)); - $user_object->Update(); - - } else { - $user_current_object->SetError('PwResetConfirm', 'code_expired', 'lu_code_expired'); - $event->redirect = false; - - } - } else { - $user_current_object->SetError('PwResetConfirm', 'code_is_not_valid', 'lu_code_is_not_valid'); - $event->redirect = false; - - } - } - - function OnUpdate(&$event) - { - $cs_helper =& $this->Application->recallObject('CountryStatesHelper'); - $cs_helper->CheckStateField($event, 'State', 'Country'); - - parent::OnUpdate($event); - - $this->setNextTemplate($event); - } - - /** - * Enter description here... - * - * @param kEvent $event - */ - function setNextTemplate(&$event) - { - if( !$this->Application->IsAdmin() ) - { - $event->redirect_params['opener'] = 's'; - $object =& $event->getObject(); - if($object->GetDBField('Status') == STATUS_ACTIVE) - { - $next_template = $this->Application->GetVar('next_template'); - if($next_template) $event->redirect = $next_template; - } - } - } - - /** - * Delete users from groups if their membership is expired - * - * @param kEvent $event - */ - function OnCheckExpiredMembership(&$event) - { - // send pre-expiration reminders: begin - $pre_expiration = adodb_mktime() + $this->Application->ConfigValue('User_MembershipExpirationReminder') * 3600 * 24; - $sql = 'SELECT PortalUserId, GroupId - FROM '.TABLE_PREFIX.'UserGroup - WHERE (MembershipExpires IS NOT NULL) AND (ExpirationReminderSent = 0) AND (MembershipExpires < '.$pre_expiration.')'; - - $skip_clause = $event->getEventParam('skip_clause'); - if ($skip_clause) { - $sql .= ' AND !('.implode(') AND !(', $skip_clause).')'; - } - - $records = $this->Conn->Query($sql); - if ($records) { - $conditions = Array(); - foreach ($records as $record) { - $email_event_user =& $this->Application->EmailEventUser('USER.MEMBERSHIP.EXPIRATION.NOTICE', $record['PortalUserId']); - $email_event_admin =& $this->Application->EmailEventAdmin('USER.MEMBERSHIP.EXPIRATION.NOTICE'); - $conditions[] = '(PortalUserId = '.$record['PortalUserId'].' AND GroupId = '.$record['GroupId'].')'; - } - $sql = 'UPDATE '.TABLE_PREFIX.'UserGroup - SET ExpirationReminderSent = 1 - WHERE '.implode(' OR ', $conditions); - $this->Conn->Query($sql); - } - // send pre-expiration reminders: end - - // remove users from groups with expired membership: begin - $sql = 'SELECT PortalUserId - FROM '.TABLE_PREFIX.'UserGroup - WHERE (MembershipExpires IS NOT NULL) AND (MembershipExpires < '.adodb_mktime().')'; - $user_ids = $this->Conn->GetCol($sql); - if ($user_ids) { - foreach ($user_ids as $id) { - $email_event_user =& $this->Application->EmailEventUser('USER.MEMBERSHIP.EXPIRED', $id); - $email_event_admin =& $this->Application->EmailEventAdmin('USER.MEMBERSHIP.EXPIRED'); - } - } - $sql = 'DELETE FROM '.TABLE_PREFIX.'UserGroup - WHERE (MembershipExpires IS NOT NULL) AND (MembershipExpires < '.adodb_mktime().')'; - $this->Conn->Query($sql); - // remove users from groups with expired membership: end - } - - /** - * Enter description here... - * - * @param kEvent $event - */ - function OnRefreshForm(&$event) - { - $event->redirect = false; - $item_info = $this->Application->GetVar($event->Prefix_Special); - list($id, $fields) = each($item_info); - - $object =& $event->getObject( Array('skip_autoload' => true) ); - $object->setID($id); - $object->IgnoreValidation = true; - $object->SetFieldsFromHash($fields); - } - - /** - * Sets persistant variable - * - * @param kEvent $event - */ - function OnSetPersistantVariable(&$event) - { - $object =& $event->getObject(); - - $field = $this->Application->GetVar('field'); - $value = $this->Application->GetVar('value'); - $object->setPersistantVar($field, $value); - - $force_tab = $this->Application->GetVar('SetTab'); - if ($force_tab) { - $this->Application->StoreVar('force_tab', $force_tab); - } - } - - /** - * Overwritten to return user from order by special .ord - * - * @param kEvent $event - */ - function getPassedID(&$event) - { - switch ($event->Special) { - case 'ord': - $order =& $this->Application->recallObject('ord'); - /* @var $order OrdersItem */ - - $id = $order->GetDBField('PortalUserId'); - break; - - case 'profile': - $id = $this->Application->GetVar('user_id'); - if (!$id) { - // if none user_id given use current user id - $id = $this->Application->RecallVar('user_id'); - } - break; - - default: - $id = parent::getPassedID($event); - break; - } - - return $id; - } - - /** - * Allows to change root password - * - * @param kEvent $event - */ - function OnUpdateRootPassword(&$event) - { - $user_id = $this->Application->RecallVar('user_id'); - if ($user_id != -1) { - // not "root" can't change root's password via this event - return false; - } - - // put salt to user's config - $field_options = $this->Application->getUnitOption($event->Prefix.'.RootPassword', 'Fields'); - $field_options['salt'] = 'b38'; - $this->Application->setUnitOption($event->Prefix.'.RootPassword', 'Fields', $field_options); - - $object =& $event->getObject( Array('skip_autoload' => true) ); - /* @var $object UsersItem */ - - $items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) ); - if ($items_info) { - list ($id, $field_values) = each($items_info); - $this->RemoveRequiredFields($object); - $object->SetDBField('RootPassword', $this->Application->ConfigValue('RootPass')); - $object->SetFieldsFromHash($field_values); - $status = $object->Validate(); - if ($status) { - // validation on, password match too - $fields_hash = Array ( - 'VariableValue' => $object->GetDBField('RootPassword') - ); - $conf_table = $this->Application->getUnitOption('conf', 'TableName'); - $this->Conn->doUpdate($fields_hash, $conf_table, 'VariableName = "RootPass"'); - $event->SetRedirectParam('opener', 'u'); - } - else { - $event->status = erFAIL; - $event->redirect = false; - } - } - } - - /** - * Apply some special processing to - * object beeing recalled before using - * it in other events that call prepareObject - * - * @param Object $object - * @param kEvent $event - * @access protected - */ - function prepareObject(&$object, &$event) - { - parent::prepareObject($object, $event); - - if (!$this->Application->IsAdmin()) { - if ($this->Application->RecallVar('register_captcha_code')) return ; - $captcha_helper =& $this->Application->recallObject('CaptchaHelper'); - /* @var $captcha_helper kCaptchaHelper */ - $this->Application->StoreVar('register_captcha_code', $captcha_helper->GenerateCaptchaCode()); - } - } - - /** - * Apply custom processing to item - * - * @param kEvent $event - */ - function customProcessing(&$event, $type) - { - if ($event->Name == 'OnCreate' && $type == 'before') { - $object =& $event->getObject(); - /* @var $object kDBItem */ - - // if auto password has not been set already - store real one - to be used in email events - if (!$this->Application->GetVar('user_password')) { - $this->Application->SetVar('user_password', $object->GetDirtyField('Password')); - $object->SetDBField('Password_plain', $object->GetDirtyField('Password')); - } - - // Validate captcha image if it's requried - if ($this->Application->ConfigValue('RegistrationCaptcha') && $object->GetDBField('Captcha') != $this->Application->RecallVar('register_captcha_code')) { - $object->SetError('Captcha', 'captcha_error', 'lu_captcha_error'); - $captcha_helper =& $this->Application->recallObject('CaptchaHelper'); - /* @var $captcha_helper kCaptchaHelper */ - $this->Application->StoreVar('register_captcha_code', $captcha_helper->GenerateCaptchaCode()); - } - - } - } - - /** - * Checks, that currently loaded item is allowed for viewing (non permission-based) - * - * @param kEvent $event - * @return bool - */ - function checkItemStatus(&$event) - { - $object =& $event->getObject(); - if (!$object->isLoaded()) { - return true; - } - - $virtual_users = Array (-1, -2); // root, Guest - return ($object->GetDBField('Status') == STATUS_ACTIVE) || in_array($object->GetID(), $virtual_users); - } - - /** - * Sends approved/declined email event on user status change - * - * @param kEvent $event - */ - function OnAfterItemUpdate(&$event) - { - $object =& $event->getObject(); - /* @var $object UsersItem */ - - if (!$this->Application->IsAdmin() || $object->IsTempTable()) { - return ; - } - - $this->sendStatusChangeEvent($object->GetID(), $object->GetOriginalField('Status'), $object->GetDBField('Status')); - } - - /** - * Stores user's original Status before overwriting with data from temp table - * - * @param kEvent $event - */ - function OnBeforeDeleteFromLive(&$event) - { - $user_status = $this->Application->GetVar('user_status'); - if (!$user_status) { - $user_status = Array (); - } - - $user_id = $event->getEventParam('id'); - if ($user_id > 0) { - $user_status[$user_id] = $this->getUserStatus($user_id); - $this->Application->SetVar('user_status', $user_status); - } - } - - /** - * Sends approved/declined email event on user status change (in temp tables during editing) - * - * @param kEvent $event - */ - function OnAfterCopyToLive(&$event) - { - $temp_id = $event->getEventParam('temp_id'); - if ($temp_id == 0) { - // this is new user create, don't send email events - return ; - } - - $new_status = $this->getUserStatus($temp_id); - $user_status = $this->Application->GetVar('user_status'); - - $this->sendStatusChangeEvent($temp_id, $user_status[$temp_id], $new_status); - } - - /** - * Returns user status (active, pending, disabled) based on ID and temp mode setting - * - * @param int $user_id - * @return int - */ - function getUserStatus($user_id) - { - $id_field = $this->Application->getUnitOption($this->Prefix, 'IDField'); - $table_name = $this->Application->getUnitOption($this->Prefix, 'TableName'); - - $sql = 'SELECT Status - FROM '.$table_name.' - WHERE '.$id_field.' = '.$user_id; - return $this->Conn->GetOne($sql); - } - - /** - * Sends approved/declined email event on user status change - * - * @param int $user_id - * @param int $prev_status - * @param int $new_status - */ - function sendStatusChangeEvent($user_id, $prev_status, $new_status) - { - $status_events = Array ( - STATUS_ACTIVE => 'USER.APPROVE', - STATUS_DISABLED => 'USER.DENY', - ); - $email_event = isset($status_events[$new_status]) ? $status_events[$new_status] : false; - - if (($prev_status != $new_status) && $email_event) { - $this->Application->EmailEventUser($email_event, $user_id); - $this->Application->EmailEventAdmin($email_event); - } - } - } - -?> \ No newline at end of file