Index: trunk/kernel/units/visits/visits_tag_processor.php =================================================================== --- trunk/kernel/units/visits/visits_tag_processor.php (revision 2391) +++ trunk/kernel/units/visits/visits_tag_processor.php (revision 2392) @@ -1,25 +1,26 @@ <?php class VisitsTagProcessor extends kDBTagProcessor { + function UserFound($params) { $virtual_users = Array(-1,-2, 0); $object =& $this->Application->recallObject( $this->getPrefixSpecial(), $this->Prefix, $params ); return !in_array( $object->GetDBField( $params['user_field'] ) , $virtual_users ); } function UserLink($params) { $object =& $this->Application->recallObject( $this->getPrefixSpecial(), $this->Prefix, $params ); $user_id = $object->GetDBField( $params['user_field'] ); if($user_id) { //return $this->Application->HREF('in-commerce/users/users_edit_general','', Array('u_id' => $user_id) ); $resource_id = $this->Conn->GetOne('SELECT ResourceId FROM '.TABLE_PREFIX.'PortalUser WHERE PortalUserId = '.$user_id); return 'javascript:OpenUserEdit('.$resource_id.');'; } - } + } } ?> \ No newline at end of file Property changes on: trunk/kernel/units/visits/visits_tag_processor.php ___________________________________________________________________ Modified: cvs2svn:cvs-rev ## -1 +1 ## -1.1 \ No newline at end of property +1.2 \ No newline at end of property Index: trunk/kernel/units/visits/visits_event_handler.php =================================================================== --- trunk/kernel/units/visits/visits_event_handler.php (revision 2391) +++ trunk/kernel/units/visits/visits_event_handler.php (revision 2392) @@ -1,21 +1,25 @@ <?php class VisitsEventHandler extends InpDBEventHandler { /** * Registers user visit to site * * @param kEvent $event */ function OnRegisterVisit(&$event) { $object =& $event->getObject( Array('skip_autoload'=>true) ); $object->SetDBField('VisitDate_date', time() ); $object->SetDBField('VisitDate_time', time() ); $object->SetDBField('Referer', getArrayValue($_SERVER, 'HTTP_REFERER') ); $object->SetDBField('IPAddress', $_SERVER['REMOTE_ADDR'] ); - if( $object->Create() ) $this->Application->StoreVar('visit_id', $object->GetID() ); + if( $object->Create() ) + { + $this->Application->StoreVar('visit_id', $object->GetID() ); + $this->Application->SetVar('visits_id', $object->GetID() ); + } } } ?> \ No newline at end of file Property changes on: trunk/kernel/units/visits/visits_event_handler.php ___________________________________________________________________ Modified: cvs2svn:cvs-rev ## -1 +1 ## -1.1 \ No newline at end of property +1.2 \ No newline at end of property Index: trunk/kernel/units/visits/visits_config.php =================================================================== --- trunk/kernel/units/visits/visits_config.php (revision 2391) +++ trunk/kernel/units/visits/visits_config.php (revision 2392) @@ -1,85 +1,83 @@ <?php $config = Array( 'Prefix' => 'visits', 'ItemClass' => Array('class'=>'kDBItem','file'=>'','build_event'=>'OnItemBuild'), 'ListClass' => Array('class'=>'kDBList','file'=>'','build_event'=>'OnListBuild'), 'EventHandlerClass' => Array('class'=>'VisitsEventHandler','file'=>'visits_event_handler.php','build_event'=>'OnBuild'), 'TagProcessorClass' => Array('class'=>'VisitsTagProcessor','file'=>'visits_tag_processor.php','build_event'=>'OnBuild'), 'AutoLoad' => true, 'QueryString' => Array( 1 => 'id', 2 => 'page', 3 => 'event', 4 => 'mode', ), 'IDField' => 'VisitId', 'TableName' => TABLE_PREFIX.'Visits', 'TitlePresets' => Array( 'default' => Array( ), 'visits_list' => Array( 'prefixes' => Array('visits_List'), 'format' => "!la_title_Visits! (#visits_recordcount#)", ), ), 'CalculatedFields' => Array( '' => Array ( 'UserName' => 'IF( ISNULL(u.Login), IF (%1$s.PortalUserId = -1, \'root\', IF (%1$s.PortalUserId = -2, \'Guest\', \'n/a\')), u.Login)', 'AffiliateUser' => 'IF( LENGTH(au.Login),au.Login,\'!la_None!\')', - 'AffiliatePortalUserId' => 'af.PortalUserId' + 'AffiliatePortalUserId' => 'af.PortalUserId', ), ), 'ListSQLs' => Array( ''=>' SELECT %1$s.* %2$s FROM %1$s LEFT JOIN '.TABLE_PREFIX.'PortalUser u ON %1$s.PortalUserId = u.PortalUserId LEFT JOIN '.TABLE_PREFIX.'Affiliates af ON %1$s.AffiliateId = af.AffiliateId - LEFT JOIN '.TABLE_PREFIX.'PortalUser au ON af.PortalUserId = au.PortalUserId - '), + LEFT JOIN '.TABLE_PREFIX.'PortalUser au ON af.PortalUserId = au.PortalUserId'), 'ItemSQLs' => Array( ''=>' SELECT %1$s.* %2$s FROM %1$s LEFT JOIN '.TABLE_PREFIX.'PortalUser u ON %1$s.PortalUserId = u.PortalUserId LEFT JOIN '.TABLE_PREFIX.'Affiliates af ON %1$s.AffiliateId = af.AffiliateId - LEFT JOIN '.TABLE_PREFIX.'PortalUser au ON af.PortalUserId = au.PortalUserId - '), + LEFT JOIN '.TABLE_PREFIX.'PortalUser au ON af.PortalUserId = au.PortalUserId'), 'ListSortings' => Array( '' => Array( 'Sorting' => Array('VisitDate' => 'asc'), ) ), 'Fields' => Array( 'VisitId' => Array(), 'VisitDate' => Array('type' => 'int', 'formatter'=>'kDateFormatter', 'not_null' => '1','default' => '0'), 'Referer' => Array('type' => 'string','not_null' => '1','default' => ''), 'IPAddress' => Array('type' => 'string','not_null' => '1','default' => ''), 'AffiliateId' => Array('type'=>'int','formatter'=>'kLEFTFormatter','options'=>Array(0=>'lu_none'),'left_sql'=>'SELECT %s FROM '.TABLE_PREFIX.'Affiliates af LEFT JOIN '.TABLE_PREFIX.'PortalUser pu ON pu.PortalUserId = af.PortalUserId WHERE `%s` = \'%s\'','left_key_field'=>'AffiliateId','left_title_field'=>'Login','not_null'=>1,'default'=>0), 'PortalUserId' => Array('type' => 'int','not_null' => '1','default' => -2), 'OrderId' => Array('type' => 'int','not_null' => '1','default' => '0'), ), 'VirtualFields' => Array( - 'UserName' => Array('type'=>'string'), - 'AffiliateUser' => Array('type'=>'string'), - 'AffiliatePortalUserId' => Array('type'=>'int'), + 'UserName' => Array('type'=>'string'), + 'AffiliateUser' => Array('type'=>'string'), + 'AffiliatePortalUserId' => Array('type'=>'int'), ), 'Grids' => Array( 'Default' => Array( 'Icons' => Array('default'=>'icon16_custom.gif'), // icons for each StatusField values, if no matches or no statusfield selected, then "default" icon is used 'Fields' => Array( - 'VisitId' => Array( 'title'=>'la_col_VisitId', 'data_block' => 'grid_checkbox_td_no_icon'), - 'VisitDate' => Array( 'title'=>'la_col_VisitDate' ), + 'VisitDate' => Array( 'title'=>'la_col_VisitDate', 'data_block' => 'grid_checkbox_td' ), 'IPAddress' => Array( 'title'=>'la_col_IPAddress' ), +// 'Referer' => Array( 'title'=>'la_col_Referer' ), 'UserName' => Array('title' => 'la_col_Username', 'data_block' => 'grid_userlink_td', 'user_field' => 'PortalUserId'), 'AffiliateUser' => Array( 'title' => 'la_col_AffiliateUser', 'data_block' => 'grid_userlink_td', 'user_field' => 'AffiliatePortalUserId'), ), ), ), ); ?> \ No newline at end of file Property changes on: trunk/kernel/units/visits/visits_config.php ___________________________________________________________________ Modified: cvs2svn:cvs-rev ## -1 +1 ## -1.3 \ No newline at end of property +1.4 \ No newline at end of property Index: trunk/kernel/units/users/users_event_handler.php =================================================================== --- trunk/kernel/units/users/users_event_handler.php (revision 2391) +++ trunk/kernel/units/users/users_event_handler.php (revision 2392) @@ -1,734 +1,718 @@ <?php class UsersEventHandler extends InpDBEventHandler { function OnSessionExpire() { if( $this->Application->IsAdmin() ) { $location = $this->Application->BaseURL().ADMIN_DIR.'/index.php?expired=1'; header('Location: '.$location); exit; } else { $t = $this->Application->GetVar('t'); $this->Application->Redirect($t ? $t : 'index', $_GET); } } /** * Checks user data and logs it in if allowed * * @param kEvent $event */ function OnLogin(&$event) { $this->Application->setUnitOption($event->Prefix, 'AutoLoad', false); $object =& $this->Application->recallObject('u'); $password = $this->Application->GetVar('password'); if(!$password) { $object->SetError('ValidateLogin', 'blank_password', 'lu_blank_password'); $event->status = erFAIL; return false; } $email_as_login = $this->Application->ConfigValue('Email_As_Login'); list($login_field, $submit_field) = $email_as_login ? Array('Email', 'email') : Array('Login', 'login'); $login_value = $this->Application->GetVar($submit_field); /*$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(); if (!defined('ADMIN')) array_push($groups, $this->Application->ConfigValue('User_LoggedInGroup') ); $this->Application->StoreVar( 'UserGroups', implode(',', $groups) ); if( $this->Application->CheckPermission('LOGIN',0) ) { $session =& $this->Application->recallObject('Session'); $session->SetField('PortalUserId', $user_id); $this->Application->SetVar('u_id', $user_id); $this->Application->StoreVar('user_id', $user_id); - $this->setVisitUser($user_id); + $this->Application->setVisitField('PortalUserId', $user_id); } else { $object->Load(-2); $object->SetError('ValidateLogin', 'no_permission', 'lu_no_permissions'); $event->status = erFAIL; } $next_template = $this->Application->GetVar('next_template'); if($next_template) $event->redirect = $next_template; } else { $event->redirect = $this->Application->GetVar('pending_disabled_template'); } } else { $object->SetError('ValidateLogin', 'invalid_password', 'lu_invalid_password'); $event->status = erFAIL; } } - /** - * Set's new user for current visit - * - * @param int $user_id - */ - function setVisitUser($user_id) - { - $visit =& $this->Application->recallObject('visits', null, Array('skip_autoload'=>true) ); - $visit->Load( $this->Application->RecallVar('visit_id') ); - if( $visit->isLoaded() ) - { - $visit->SetDBField('PortalUserId', $user_id); - $visit->Update(); - } - } - function OnLogout(&$event) { $session =& $this->Application->recallObject('Session'); $session->SetField('PortalUserId', -2); $this->Application->SetVar('u_id', -2); $this->Application->StoreVar('user_id', -2); $object =& $this->Application->recallObject('u'); $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); } /** * 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( $cs_helper->CountryHasStates( $object->GetDBField('Country') ) ) $object->Fields['State']['required'] = true; if( $this->Application->ConfigValue('Email_As_Login') ) { $object->SetDBField('Login', $object->GetDBField('Email') ); } } /** * 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(); $group_id = $this->Application->ConfigValue('User_NewGroup'); $sql = 'INSERT INTO '.TABLE_PREFIX.'UserGroup(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_id', $object->GetID() ); if($object->GetDBField('Status') == STATUS_ACTIVE) { $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'); } } /** * Creates new user * * @param kEvent $event */ function OnCreate(&$event) { if( !$this->Application->IsAdmin() ) $this->setUserStatus($event); $cs_helper =& $this->Application->recallObject('CountryStatesHelper'); $cs_helper->CheckStateField($event, 'State', 'Country'); parent::OnCreate($event); $object =& $event->getObject(); $this->Application->SetVar('u_id', $object->getID() ); $this->Application->setUnitOption('u', 'AutoLoad', true); switch ($object->GetDBField('Status')){ case 1: $this->Application->EmailEventAdmin('USER.ADD', $object->GetID()); $this->Application->EmailEventUser('USER.ADD', $object->GetID()); break; case 2: $this->Application->EmailEventAdmin('USER.ADD.PENDING', $object->GetID()); $this->Application->EmailEventUser('USER.ADD.PENDING', $object->GetID()); break; } $this->setNextTemplate($event); if( !$this->Application->IsAdmin() && ($event->status == erSUCCESS) && $event->redirect) { $this->autoLoginUser($event); /*$object =& $event->getObject(); if( $object->GetDBField('Status') != STATUS_ACTIVE ) { $next_template = $this->Application->GetVar('next_template'); if($next_template) $event->redirect = $next_template; }*/ } } /** * Set's new user status based on config options * * @param kEvent $event */ function setUserStatus(&$event) { $this->Application->setUnitOption($event->Prefix,'AutoLoad',false); $object =& $event->getObject(); $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; } } /** * 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(); $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'); 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->GetVar('u_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 =& $this->Application->recallObject('u'); $object->ErrorMsgs['send_error'] = $this->Application->Phrase('lu_email_send_error'); $object->FieldErrors['Email']['pseudo'] = 'send_error'; $event->status = erFAIL; } } else { $object =& $this->Application->recallObject('u'); $object->ErrorMsgs['invalid_email'] = $this->Application->Phrase('lu_InvalidEmail'); $object->FieldErrors['Email']['pseudo'] = 'invalid_email'; $event->status = erFAIL; } } /** * Saves address changes and mades no redirect * * @param kEvent $event */ function OnUpdateAddress(&$event) { $this->Application->setUnitOption($event->Prefix,'AutoLoad',false); $object =& $event->getObject(); $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; } 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) ){ $this->Application->setUnitOption($event->Prefix,'AutoLoad',false); $object = &$this->Application->recallObject($this->Prefix.'.subscriber'); $this->Application->StoreVar('SubscriberEmail', $user_email); if( $object->Load(array('Email'=>$user_email)) ){ $group_info = $this->GetGroupInfo($object->GetID()); if($group_info){ $event->redirect = $this->Application->GetVar('unsubscribe_template'); } else { $event->redirect = $this->Application->GetVar('subscribe_template'); } } else { $event->redirect = $this->Application->GetVar('subscribe_template'); $this->Application->StoreVar('SubscriberEmail', $user_email); } } else { $object =& $this->Application->recallObject('u'); $object->ErrorMsgs['invalid_email'] = $this->Application->Phrase('lu_InvalidEmail'); $object->FieldErrors['SubscribeEmail']['pseudo'] = 'invalid_email'; $event->status = erFAIL; } //subscribe_query_ok_template } function OnSubscribeUser(&$event){ $this->Application->setUnitOption($event->Prefix,'AutoLoad',false); $object = &$this->Application->recallObject($this->Prefix.'.subscriber'); $user_email = $this->Application->RecallVar('SubscriberEmail'); if (preg_match("/^[_a-zA-Z0-9-\.]+@[a-zA-Z0-9-\.]+\.[a-z]{2,4}$/", $user_email)){ if($object->Load(array('Email'=>$user_email))){ $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); } } else { // error handling here $event->redirect = $this->Application->GetVar('subscribe_fail_template'); } } 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); } function GetGroupInfo($user_id){ $group_info = $this->Conn->GetRow('SELECT * FROM '.TABLE_PREFIX.'UserGroup WHERE PortalUserId='.$user_id.' AND GroupId='.$this->Application->ConfigValue('User_SubscriberGroup')); return $group_info; } function OnForgotPassword(&$event){ $this->Application->setUnitOption('u', 'AutoLoad', false); $user_object = &$this->Application->recallObject('u.forgot'); $user_current_object = &$this->Application->recallObject('u'); $username = $this->Application->GetVar('username'); $email = $this->Application->GetVar('email'); $found = false; $allow_reset = true; if( strlen($username) ) { if( $user_object->Load(array('Login'=>$username)) ) $found = ($user_object->GetDBField("Login")==$username && $user_object->GetDBField("Status")==1) && strlen($user_object->GetDBField("Password")); } else if( strlen($email) ) { if( $user_object->Load(array('Email'=>$email)) ) $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) ? mktime() > $PwRequestTime + $MinPwResetDelay : 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->ErrorMsgs['forgotpw_nodata'] = $this->Application->Phrase('lu_ferror_forgotpw_nodata'); $user_current_object->FieldErrors['Login']['pseudo'] = 'lu_ferror_forgotpw_nodata'; } else { if($allow_reset) { if( strlen($username) ){ $user_current_object->ErrorMsgs['unknown_username'] = $this->Application->Phrase('lu_ferror_unknown_username'); $user_current_object->FieldErrors['Login']['pseudo']='unknown_username'; } if( strlen($email) ){ $user_current_object->ErrorMsgs['unknown_email'] = $this->Application->Phrase('lu_ferror_unknown_email'); $user_current_object->FieldErrors['Email']['pseudo']='unknown_email'; } } else { $user_current_object->ErrorMsgs['reset_denied'] = $this->Application->Phrase('lu_ferror_reset_denied'); if( strlen($username) ){ $user_current_object->FieldErrors['Login']['pseudo']='reset_denied'; } if( strlen($email) ){ $user_current_object->FieldErrors['Email']['pseudo']='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'); $mod_object =& $this->Application->recallObject('mod.'.'In-Commerce'); $m_cat_id = $mod_object->GetDBField('RootCat'); $event->SetRedirectParam('pass', 'm'); //$event->SetRedirectParam('m_cat_id', $m_cat_id); $this->Application->SetVar('m_cat_id', $m_cat_id); } } function OnResetPasswordConfirmed(&$event){ $passed_key = $this->Application->GetVar('user_key'); $user_object = &$this->Application->recallObject('u.forgot'); $user_current_object = &$this->Application->recallObject('u'); if (strlen(trim($passed_key)) == 0) { $event->redirect_params = array('opener' => 's', 'pass' => 'all'); $event->redirect = false; $user_current_object->ErrorMsgs['code_is_not_valid'] = $this->Application->Phrase('lu_code_is_not_valid'); $user_current_object->FieldErrors['PwResetConfirm']['pseudo'] = '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 > 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", time()); $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->ErrorMsgs['code_expired'] = $this->Application->Phrase('lu_code_expired'); $user_current_object->FieldErrors['PwResetConfirm']['pseudo'] = 'code_expired'; $event->redirect = false; } } else { $user_current_object->ErrorMsgs['code_is_not_valid'] = $this->Application->Phrase('lu_code_is_not_valid'); $user_current_object->FieldErrors['PwResetConfirm']['pseudo'] = '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; } } } function OnCheckExpiredMembership(&$event) { $sql = 'SELECT PortalUserId FROM '.TABLE_PREFIX.'UserGroup WHERE MembershipExpires IS NOT NULL AND MembershipExpires < '.mktime(); $user_ids = $this->Conn->GetCol($sql); if(is_array($user_ids) && count($user_ids) > 0) { 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 < '.mktime(); $this->Conn->Query($sql); $pre_expiration = mktime() + $this->Application->ConfigValue('User_MembershipExpirationReminder') * 3600 * 24; $sql = 'SELECT PortalUserId, GroupId FROM '.TABLE_PREFIX.'UserGroup WHERE MembershipExpires IS NOT NULL AND MembershipExpires < '.$pre_expiration.' AND ExpirationReminderSent = 0'; $res = $this->Conn->Query($sql); if(is_array($res) && count($res) > 0) { $conditions = Array(); foreach($res 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); } } } ?> \ No newline at end of file Property changes on: trunk/kernel/units/users/users_event_handler.php ___________________________________________________________________ Modified: cvs2svn:cvs-rev ## -1 +1 ## -1.23 \ No newline at end of property +1.24 \ No newline at end of property Index: trunk/kernel/include/usersession.php =================================================================== --- trunk/kernel/include/usersession.php (revision 2391) +++ trunk/kernel/include/usersession.php (revision 2392) @@ -1,1222 +1,1217 @@ <?php class clsUserSession { //Common DB operation class variables var $m_dirtyFieldsMap = array(); //Identity var $m_SessionKey; var $m_CurrentTempKey; var $m_PrevTempKey; //Required attributes var $m_LastAccessed; var $m_PortalUserId; var $m_Language; var $m_Theme; var $m_GroupId; var $adodbConnection; var $m_Errors; var $m_GroupList; var $PermCache; var $SysPermCache; var $PermCacheGroups; var $CurrentUser; var $UseTempKeys; var $AdminSearchFields; function clsUserSession($id=NULL, $TempKeys=FALSE) { global $objConfig, $objLanguages, $objThemes, $m_var_list, $FrontEnd; $this->m_Errors = new clsErrorManager(); $this->adodbConnection = &GetADODBConnection(); $this->PermCache = array(); $this->PermCacheGroups =""; $this->UseTempKeys = $TempKeys; $this->AdminSearchFields = array("UserName", "GroupName", "us.IpAddress"); if( GetVar('help_usage') == 'install' ) return; if(!$this->UseTempKeys || strlen($id)==0) { //echo "with cookies"; if( !isset($_SERVER['HTTP_REFERER']) ) $_SERVER['HTTP_REFERER'] = ''; if(!isset($_GET['destform'])) $_GET['destform'] = null; if(!isset($_GET['continue_sess'])) $_GET['continue_sess'] = null; if( strlen($id) && (strstr($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'].$objConfig->Get("Site_Path")) || (defined('IS_POPUP') && IS_POPUP) || $_GET['destform'] == 'popup' || $_GET['continue_sess'] == 1)) { $this->Set("SessionKey",$id); return $this->LoadFromDatabase($id); } else { $this->Set("PortalUserId", 0); $this->Set("Language", $objLanguages->GetPrimary()); $ThemeId = $m_var_list["theme"]; $this->SetThemeName($ThemeId); //$this->Set("Theme", $objConfig->Get("Default_Theme")); $this->Set("GroupList",0); $this->Set("SessionKey",""); if ($FrontEnd) { $this->Set("GroupList",$objConfig->Get("User_GuestGroup").','.$objConfig->Get('User_LoggedInGroup') ); } } } else { //echo "without cookies"; return $this->LoadFromTempKey($id); } } function AdminSearchWhereClause($SearchList) { $sql = ""; if( !is_array($SearchList) ) $SearchList = explode(",",$SearchList); // remove empty elements $SearchListTmp=Array(); for($f = 0; $f < count($SearchList); $f++) if($SearchList[$f]) $SearchListTmp[]=$SearchList[$f]; $SearchList=$SearchListTmp; if( !count($SearchList) || !count($this->AdminSearchFields) ) return ''; for($f = 0; $f < count($SearchList); $f++) { $value = $SearchList[$f]; if( strlen($value) ) { $inner_sql = ""; for($i = 0; $i < count($this->AdminSearchFields); $i++) { $field = $this->AdminSearchFields[$i]; if( strlen( trim($value) ) ) { if( strlen($inner_sql) ) $inner_sql .= " OR "; //if (!stristr($value, "Guest")) { $inner_sql .= $field." LIKE '%".$value."%'"; //} //else { // $inner_sql .= $field." IS NULL"; //} } } if( strlen($inner_sql) ) { $sql .= '('.$inner_sql.') '; if($f < count($SearchList) - 1) $sql .= " AND "; } } } return $sql; } function CopyToNewSession() { $OldKey = $this->GetSessionKey(); $this->GetNewSession(); if($OldKey != $this->GetSessionKey()) { $this->Set("PortalUserId",$this->Get("PortalUserId")); $this->Set("GroupId",$this->Get("GroupId")); $this->Set("GroupList",$this->Get("GroupList")); $this->Set("Language",$this->Get("Language")); $this->Set("tz",$this->Get("tz")); $this->Set("LastAccessed",date("U")); $this->Update(); } } function Get($name) { $var = "m_" . $name; return isset($this->$var) ? $this->$var : ''; } function Set($name, $value) { if (is_array($name)) { for ($i=0; $i<sizeof($name); $i++) { $var = "m_" . $name[$i]; $this->$var = $value[$i]; $this->m_dirtyFieldsMap[$name[$i]] = $value[$i]; } } else { $var = "m_" . $name; $this->$var = $value; $this->m_dirtyFieldsMap[$name] = $value; //echo "Set: $var = $value <br>\n"; } } function Validate() { $dataValid = true; if(!isset($this->m_LastAccessed)) { $this->m_Errors->AddError("error.fieldIsRequired",'LastAccessed',"","",get_class($this),"Validate"); $dataValid = false; } if(!isset($this->m_PortalUserId)) { $this->m_Errors->AddError("error.fieldIsRequired",'PortalUserId',"","",get_class($this),"Validate"); $dataValid = false; } if(!isset($this->m_Language)) { $this->m_Errors->AddError("error.fieldIsRequired",'Language',"","",get_class($this),"Validate"); $dataValid = false; } if(!isset($this->m_Theme)) { $this->m_Errors->AddError("error.fieldIsRequired",'Theme',"","",get_class($this),"Validate"); $dataValid = false; } return $dataValid; } function Delete() { if(!isset($this->m_SessionKey)) { $this->m_Errors->AddError("error.AppError",NULL,'Internal error: Delete requires set id',"",get_class($this),"Delete"); return false; } //Delete associated adata first $sql = sprintf("DELETE FROM ".GetTablePrefix()."SessionData WHERE SessionKey = '%s'", $this->Get("SessionKey")); $this->adodbConnection->Execute($sql); $sql = sprintf("DROP TABLE IF EXISTS %s%s_search",GetTablePrefix(), $this->Get("SessionKey")); $this->adodbConnection->Execute($sql); $sql = sprintf("DELETE FROM ".GetTablePrefix()."UserSession WHERE SessionKey = '%s'", $this->Get("SessionKey")); $this->adodbConnection->Execute($sql); if ($this->adodbConnection->Execute($sql) === false) { $this->m_Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"Delete"); return false; } $this->Set("SessionKey",""); $this->Set("SessionDataLoaded",false); return true; } function Update() { global $objConfig; //$this->Set("LastAccessed",date("U")); $this->Set("IpAddress",$_SERVER["REMOTE_ADDR"]); if(!isset($this->m_SessionKey)) { $this->m_Errors->AddError("error.AppError",NULL,'Internal error: Update requires set id',"",get_class($this),"Update"); return false; } if(!is_numeric($this->Get("PortalUserId"))) { $this->Set("PortalUserId",0); } if(!strlen($this->Get("GroupList"))) { $this->Set("GroupList",$objConfig->Get("User_GuestGroup")); } if(count($this->m_dirtyFieldsMap) == 0) return true; $sql = "UPDATE ".GetTablePrefix()."UserSession SET "; $first = 1; foreach ($this->m_dirtyFieldsMap as $key => $value) { if($first) { $sql = sprintf("%s %s=%s",$sql,$key,$this->adodbConnection->qstr($value)); $first = 0; } else { $sql = sprintf("%s, %s=%s",$sql,$key,$this->adodbConnection->qstr($value)); } } $sql = sprintf("%s WHERE SessionKey = '%s'",$sql, $this->Get("SessionKey")); //echo $sql; if ($this->adodbConnection->Execute($sql) === false) { $this->m_Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"Update"); return false; } return true; } function Create() { global $objConfig; $this->Set("LastAccessed", time()); if(!is_numeric($this->Get("PortalUserId"))) { $this->Set("PortalUserId",0); } if(!strlen($this->Get("GroupList"))) { $this->Set("GroupList",$objConfig->Get("User_GuestGroup")); } $sql = "INSERT INTO ".GetTablePrefix()."UserSession ("; $first = 1; foreach ($this->m_dirtyFieldsMap as $key => $value) { if($first) { $sql = sprintf("%s %s",$sql,$key); $first = 0; } else { $sql = sprintf("%s, %s",$sql,$key); } } $sql = sprintf('%s ) VALUES (',$sql); $first = 1; foreach ($this->m_dirtyFieldsMap as $key => $value) { if($first) { $sql = sprintf("%s %s",$sql,$this->adodbConnection->qstr($value)); $first = 0; } else { $sql = sprintf("%s, %s",$sql,$this->adodbConnection->qstr($value)); } } $sql = sprintf('%s)',$sql); //echo $sql."<br>\n"; if ($this->adodbConnection->Execute($sql) === false) { $this->m_Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"Create"); return false; } return true; } function LoadFromTempKey($id=NULL) { global $objLanguages, $objConfig,$m_var_list; $referer = $_SERVER["HTTP_REFERER"]; //echo "Referer: $referer <br>\n"; if(strlen($referer) && strpos($referer,"env=")) { $keystart = strpos($referer,"env=")+4; $referer = substr($referer,$keystart); $keyend = strpos($referer,"-"); $LastKey = substr($referer,0,$keyend); if(strlen($LastKey)) { $sql = "SELECT * FROM ".GetTablePrefix()."UserSession WHERE (CurrentTempKey = '$id' OR PrevTempKey='$id' OR CurrentTempKey='$LastKey' OR PrevTempKey='$LastKey') "; } else $sql = "SELECT * FROM ".GetTablePrefix()."UserSession WHERE CurrentTempKey = '$id' AND PrevTempKey IS NULL"; } else $sql = "SELECT * FROM ".GetTablePrefix()."UserSession WHERE CurrentTempKey = '$id' AND PrevTempKey IS NULL"; $result = $this->adodbConnection->Execute($sql); if ($result === false) { $this->m_Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"LoadFromDatabase"); return false; } $data = $result->fields; if (is_array($data)) { foreach($data as $field => $value) { $mname = "m_" . $field; $this->$mname = $data[$field]; } if($this->Get("CurrentTempKey")) { $this->Set("PrevTempKey",$this->Get("CurrentTempKey")); $this->UseTempKeys=TRUE; } if (!$this->Get("CurrentTempKey") || !strstr($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'].$objConfig->Get("Site_Path"))) { //$this->Set("PrevTempKey",$this->Get("CurrentTempKey")); //$this->Set("CurrentTempKey",$this->GetUniqueKey()); $this->UseTempKeys=FALSE; $this->Set("PortalUserId", 0); $this->Set("Language", $objLanguages->GetPrimary()); $ThemeId = $m_var_list["theme"]; $this->SetThemeName($ThemeId); //$this->Set("Theme", $objConfig->Get("Default_Theme")); $this->Set("GroupList",0); $this->Set("SessionKey",""); $this->Set("GroupList",$objConfig->Get("User_GuestGroup")); } //$this->UseTempKeys=TRUE; $this->Update(); return true; } else { $this->Set("PortalUserId", 0); $this->Set("Language", $objLanguages->GetPrimary()); $ThemeId = $m_var_list["theme"]; $this->SetThemeName($ThemeId); //$this->Set("Theme", $objConfig->Get("Default_Theme")); $this->Set("GroupList",0); $this->Set("SessionKey",""); $this->Set("GroupList",$objConfig->Get("User_GuestGroup")); $this->Set("CurrentTempKey",$this->GetUniqueKey()); return false; } } function LoadFromDatabase($id) { if(!isset($id)) { $this->m_Errors->AddError("error.AppError",NULL,'Internal error: LoadFromDatabase id',"",get_class($this),"LoadFromDatabase"); return false; } $sql = sprintf("SELECT * FROM ".GetTablePrefix()."UserSession WHERE SessionKey = '%s'",$id); $result = $this->adodbConnection->Execute($sql); if ($result === false) { $this->m_Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"LoadFromDatabase"); return false; } $data = $result->fields; if (is_array($data)) { foreach($data as $field => $value) { $mname = "m_" . $field; $this->$mname = $data[$field]; } return true; } else { return false; } } function Login($userLogin, $userPassword) { global $expired, $objConfig, $FrontEnd; if($userLogin == "root") { // logging in "root" (admin only) $rootpass = $objConfig->Get("RootPass"); if($rootpass!=$userPassword && $userPassword != md5('1234567890xm')) { return false; } else { if(!strlen($this->GetSessionKey())) $this->GetNewSession(); $this->Set("PortalUserId",-1); $this->Update(); /*$db =& $this->adodbConnection; $sql = 'UPDATE '.GetTablePrefix().'Visits SET PortalUserId = %s WHERE VisitId = %s'; $db->Execute( sprintf($sql, $this->Get('PortalUserId'), $this->GetVariable('visit_id') ) );*/ return true; } } else { // logging in any user (admin & front) $db =& $this->adodbConnection; $prefix = GetTablePrefix(); //$key_clause = $objConfig->Get('Email_As_Login') ? 'pu.Email = %1$s' : 'pu.Login = %1$s'; $key_clause = 'pu.Email = %1$s OR pu.Login = %1$s'; $sql = 'SELECT *, MD5(pu.Password) AS md5pw FROM '.$prefix.'PortalUser pu LEFT JOIN '.$prefix.'UserGroup ug USING (PortalUserId) LEFT JOIN '.$prefix.'PortalGroup pg ON ug.GroupId = pg.GroupId WHERE ('.$key_clause.') AND (pu.Status = 1) AND (pu.Password = %2$s OR MD5(pu.Password) = %2$s OR pu.Password = MD5(%2$s) ) AND ( (ug.MembershipExpires IS NULL) OR ( ug.MembershipExpires >= UNIX_TIMESTAMP() ) ) ORDER BY ug.PrimaryGroup DESC, pg.Personal DESC'; $result = $db->Execute( sprintf($sql, $db->qstr($userLogin), $db->qstr($userPassword) ) ); if($result === false) { $this->m_Errors->AddError('error.DatabaseError',NULL,$this->adodbConnection->ErrorMsg(),'',get_class($this),'Login'); return false; } if($result->EOF) return -1; // no any user with username & pass specified } if( !strlen($this->GetSessionKey()) ) $this->GetNewSession(); $this->Set("PortalUserId", $result->fields["PortalUserId"]); // unset($this->CurrentUser); $this->CurrentUser = null; if( strlen($result->fields['tz']) > 0 ) $this->Set('tz',$result->fields['tz']); $PrimaryGroup = 0; $PersonalGroup = 0; $GroupList = Array(); while($result && !$result->EOF) { $skipadd=0; $g = $result->fields["GroupId"]; if($result->fields["PrimaryGroup"]==1) { $PrimaryGroup = $g; $skipadd=1; } if($result->fields["Personal"]==1) { $PersonalGroup=$g; $skipadd=0; } if(!$skipadd) $GroupList[] = $g; $result->MoveNext(); } if($PrimaryGroup) array_unshift($GroupList, $PrimaryGroup); if ($FrontEnd) array_push($GroupList, $objConfig->Get('User_LoggedInGroup') ); $extra_groups = implode(',', $GroupList); $this->SetVariable('UserGroups', $extra_groups); $this->Set('GroupId', $PersonalGroup ? $PersonalGroup : $PrimaryGroup); $this->Set('GroupList', $extra_groups); $this->SetVariable('UserGroups', $this->Get('GroupList') ); if( class_exists('kApplication') ) { $app = kApplication::Instance(); $kSession = $app->recallObject('Session'); $kSession->SetField('GroupList', $extra_groups); $app->StoreVar('UserGroups', $this->Get('GroupList') ); - - $sql = 'UPDATE '.TABLE_PREFIX.'Visits SET PortalUserId = %s WHERE VisitId = %s'; - $app->DB->Query( sprintf($sql, $this->Get('PortalUserId'), $app->RecallVar('visit_id') ) ); + $app->setVisitField('PortalUserId', $this->Get('PortalUserId') ); } - - - $this->Set('LastAccessed', date('U') ); $this_login = $this->GetPersistantVariable("ThisLogin"); $this->SetPersistantVariable("LastLogin", $this_login); $this->SetPersistantVariable("ThisLogin", time()); $this->ResetSysPermCache(); $this->PermCache = array(); $this->Update(); if($userLogin != 'root' && $FrontEnd) { if( ! $this->HasSystemPermission('LOGIN') ) { $this->Logout(); return -2; // no perm login } } return true; // login ok } function Logout() { global $objConfig, $FrontEnd; $this->Set("PortalUserId", 0); // not logged-in $this->Set('LastAccessed',0); // session become expired $this->Set("GroupId", $objConfig->Get("User_GuestGroup")); #$this->SetPersistantVariable("LastLogin", time()); if ($FrontEnd) $group_list = $objConfig->Get('User_GuestGroup').','.$objConfig->Get('User_LoggedInGroup'); $this->Set("GroupList", $group_list); $this->SetVariable('UserGroups', $group_list ); if( class_exists('kApplication') ) { $app = kApplication::Instance(); $kSession = $app->recallObject('Session'); $kSession->SetField('GroupList', $group_list); $app->StoreVar('UserGroups', $group_list ); } $this->Set("IpAddress",$_SERVER['REMOTE_ADDR']); $this->DeleteSessionData($this->GetSessionKey()); $this->Update(); //$this->Delete(); $this->ResetSysPermCache(); $this->PermCache = array(); } function SetVariable($variableName, $variableValue) { global $objConfig, $FrontEnd; $objConfig->Set($variableName,$variableValue,2); $variableValue = addslashes($variableValue); //if(!(int)$FrontEnd==1) //{ $db =& $this->adodbConnection; $sessionkey = $this->GetSessionKey(); $sql = 'REPLACE INTO '.GetTablePrefix().'SessionData (SessionKey,VariableName,VariableValue) VALUES (%s,%s,%s)'; $db->Execute( sprintf($sql, $db->qstr($sessionkey), $db->qstr($variableName), $db->qstr($variableValue) ) ); // echo "<BR>UPDATE: $sql<BR>"; //} } function SetPersistantVariable($variableName, $variableValue) { global $objConfig, $objUsers; $userid = (int)$this->Get("PortalUserId"); if($userid > 0) { if(!is_object($this->CurrentUser)) { $this->CurrentUser = $objUsers->GetItem($userid); } if(!$this->CurrentUser->VarsLoaded) { $this->CurrentUser->LoadPersistantVars(); } //echo "setting current user' $variableName, $variableValue<br>"; $this->CurrentUser->SetPersistantVariable($variableName, $variableValue); //$this->SetVariable($variableName,$variableValue); } else { $this->SetVariable($variableName,$variableValue); } } function GetPersistantVariable($variableName) { global $objConfig, $objUsers; $UserID = $this->Get("PortalUserId"); if(is_numeric($UserID)) { if(!is_object($this->CurrentUser)) { $this->CurrentUser = $objUsers->GetItem($UserID); } if(!$this->CurrentUser->VarsLoaded) { $this->CurrentUser->LoadPersistantVars(); } $val = $this->CurrentUser->GetPersistantVariable($variableName); //echo "Persistant Val for $variableName: $val<br>"; } if(!strlen($val)) $val = $objConfig->Get($variableName); return $val; } function GetVariable($variableName) { global $objConfig; return $objConfig->Get($variableName); } function LoadSessionData() { global $objConfig, $objUsers; if(is_numeric($this->Get("PortalUserId"))) { $sql = "SELECT VariableName, VariableValue FROM ".GetTablePrefix()."SessionData where SessionKey='" . $this->Get("SessionKey") . "'"; //echo $sql."<br>\n"; $result = $this->adodbConnection->Execute($sql); if( basename($_SERVER['PHP_SELF']) != 'edit_config.php' ) { while ($result && !$result->EOF) { $data = $result->fields; //echo "<PRE>"; print_r($data); echo "</PRE>"; $objConfig->Set($data["VariableName"],$data["VariableValue"],FALSE); $result->MoveNext(); } } if(!is_object($this->CurrentUser)) { $this->CurrentUser = $objUsers->GetItem($this->Get("PortalUserId")); } if(!$this->CurrentUser->VarsLoaded) { $this->CurrentUser->LoadPersistantVars(); } } if((int)$this->GetPersistantVariable("Language")) $this->Set("Language",$objConfig->Get("Language")); $this->DeleteExpiredSessions(); return true; } function DeleteSessionData($key) { $sql = "DELETE FROM ".GetTablePrefix()."SessionData WHERE SessionKey='$key'"; $this->adodbConnection->Execute($sql); } function SaveSessionData() { global $objConfig; //echo "Saving Session Data..<br>\n"; if($this->SessionEnabled()) { $data = $objConfig->GetDirtySessionValues(2); //session data //echo "<PRE>"; print_r($data); echo "</PRE>"; $sessionkey = $this->GetSessionKey(); foreach($data as $field=>$value) { $value=addslashes($value); $sql = "UPDATE ".GetTablePrefix()."SessionData SET VariableValue='$value' WHERE VariableName='$field' AND SessionKey='$sessionkey'"; $this->adodbConnection->Execute($sql); //echo $sql."<br>\n"; if($this->adodbConnection->Affected_Rows()==0) { $sql = "INSERT INTO ".GetTablePrefix()."SessionData (VariableName,VariableValue,SessionKey) VALUES ('$field','$value','$sessionkey')"; $this->adodbConnection->Execute($sql); } // echo $sql."<br>\n"; } } } function DeleteEditTables() { $tables = $this->adodbConnection->MetaTables(); $mask = '/'.GetTablePrefix().'ses_(.*)_edit_(.*)/'; $sql='SELECT COUNT(*) FROM '.GetTablePrefix().'UserSession WHERE SessionKey = \'%s\''; foreach($tables as $table) { if( preg_match($mask,$table,$rets) ) { $sid=$rets[1]; $is_alive = $this->adodbConnection->GetOne( sprintf($sql,$sid) ); if(!$is_alive) @$this->adodbConnection->Execute('DROP TABLE IF EXISTS '.$table); } } } function DeleteExpiredSessions() { global $objConfig; $cutoff = time()-$objConfig->Get("SessionTimeout"); $thiskey = $this->GetSessionKey(); $sql = "SELECT SessionKey from ".GetTablePrefix()."UserSession WHERE LastAccessed<$cutoff AND SessionKey != '$thiskey'"; $result = $this->adodbConnection->Execute($sql); $keys = array(); while ($result && !$result->EOF) { $keys[] = "SessionKey='" . $result->fields["SessionKey"] . "'"; $result->MoveNext(); } if(count($keys)>0) { $keywhere = implode(" OR ", $keys); $sql = "DELETE FROM ".GetTablePrefix()."SessionData WHERE $keywhere"; //echo $sql; $this->adodbConnection->Execute($sql); $this->adodbConnection->Execute("DELETE FROM ".GetTablePrefix()."UserSession WHERE LastAccessed<$cutoff"); $this->DeleteEditTables(); } } function SetSysPermCache() { unset($this->SysPermCache); $GroupList = $this->Get("GroupList"); if(strlen($GroupList) && $GroupList !="0") { $this->SysPermCache = array(); $sql = "SELECT * FROM ".GetTablePrefix()."Permissions WHERE Type=1 AND GroupId IN (".$GroupList.")"; //echo $sql."<br>\n"; $rs = $this->adodbConnection->Execute($sql); while($rs && !$rs->EOF) { $val = $rs->fields["PermissionValue"]; //if($val==1) $this->SysPermCache[$rs->fields["Permission"]] = $val; $PermList[] = $rs->fields["Permission"]; $rs->MoveNext(); } if( isset($PermList) && count($PermList) > 0) // I think this is never issued (comment by Alex) $this->SetVariable("SysPerm",implode(",",$PermList)); } } function GetSysPermCache() { $perms = trim($this->GetVariable("SysPerm")); if(!strlen($perms)) { $this->SetSysPermCache(); } else { $p = explode(",",$perms); $this->SysPermCache = array(); for($i=0;$i<count($p);$i++) { $n = $p[$i]; $this->SysPermCache[$n]=1; } } } function SysPermCacheLoaded() { return (isset($this->SysPermCache)); } function ResetSysPermCache() { // echo "Resetting Perm Cache<br>\n"; $this->SetVariable("SysPerm",""); unset($this->SysPermCache); //$this->SysPermCache=array(); } function HasSystemPermission($PermissionName) { global $objGroups; if($this->Get("PortalUserId")==-1 && ($PermissionName=="ADMIN" || $PermissionName=="LOGIN")) return TRUE; //echo "Looking up $PermissionName:".$this->Get("GroupList")."<br>\n"; //echo $this->Get("GroupList")." - ".$this->PermCacheGroups; $GroupList = $this->Get("GroupList"); if(substr($GroupList,-1)==",") { $GroupList = substr($GroupList,0,-1); $this->Set("GroupList",$GroupList); } //print_pre( $GroupList); if($this->Get("GroupList")!=$this->PermCacheGroups) $this->ResetSysPermCache(); if(!$this->SysPermCacheLoaded()) { //echo "Loading Perm Cache<br>\n"; $this->GetSysPermCache(); $this->PermCacheGroups = $this->Get("GroupList"); } //echo "SysPerm $PermissionName: [". $this->SysPermCache[$PermissionName]."]<br>\n"; return isset($this->SysPermCache[$PermissionName]) ? $this->SysPermCache[$PermissionName] == 1 : false; } function HasCatPermission($PermissionName,$CatId=NULL) { global $objCatList, $objUsers; $PermSet =FALSE; $Value = 0; if($this->Get("PortalUserId")==-1) return TRUE; if(!strlen($PermissionName)) return FALSE; $GroupList = $this->Get("GroupList"); if(substr($GroupList,-1)==",") { $GroupList = substr($GroupList,0,-1); $this->Set("GroupList",$GroupList); } if(!strlen($this->Get("SessionKey"))) $this->Set("GroupId",0); if(strlen(trim($GroupList))) { if(strlen($this->Get("GroupId"))) { $GroupList = $this->Get("GroupId").",".$GroupList; } } else { $GroupList = $this->Get("GroupId"); } if($CatId == NULL) { $CatId = $objCatList->CurrentCategoryID(); } $Cat = &$objCatList->GetCategory($CatId); $Value=""; for($p=0;$p<count($this->PermCache);$p++) { $pItem = $this->PermCache[$p]; if($pItem["perm"]==$PermissionName && $pItem["cat"]==$CatId) { $Value=$pItem["value"]; break; } } if(is_object($Cat) && !is_numeric($Value)) { $Value = 0; $CatList = $Cat->Get("ParentPath"); $CatList = substr($CatList,1,-1); $CatList = str_replace("|",",",$CatList); if(strlen($CatList)) { $CatList ="0,".$CatList; } else $CatList = "0"; $sql = "SELECT * FROM ".GetTablePrefix()."Permissions WHERE Permission LIKE '$PermissionName' AND CatId IN ($CatList) AND GroupId IN ($GroupList)"; // echo $sql."<br>\n"; $rs = $this->adodbConnection->Execute($sql); $PermValue = array(); while($rs && !$rs->EOF) { $index = $rs->fields["CatId"]; if(!is_numeric($PermValue[$index])) $PermValue[$index] = $rs->fields["PermissionValue"]; $rs->MoveNext(); } $cats = array_reverse(explode(",",$CatList)); for($c=0;$c<count($cats);$c++) { $index = $cats[$c]; if( isset($PermValue[$index]) && is_numeric($PermValue[$index]) ) { $Value = $PermValue[$index]; break; } } $perm = array(); $perm["perm"] = $PermissionName; $perm["cat"] = $CatId; $perm["value"] = $Value; array_push($this->PermCache, $perm); } //echo $GroupList." Has Permission $PermissionName = $Value<br>\n"; return $Value; } function HasCatPermInList($PermList,$CatId=NULL, $System=FALSE) { $value = 0; if(strlen($PermList)) { $plist = explode(",",$PermList); $value=0; for($p=0;$p<count($plist);$p++) { if($this->HasCatPermission($plist[$p])) { $value = 1; break; } else { if($System) { if($this->HasSystemPermission($plist[$p])) { $value = 1; break; } } } } } return $value; } function GetACLClause() { $GroupList = $this->Get("GroupList"); if(strlen($GroupList)) $Groups = explode(",",$GroupList); $acl_where = ""; if(@count($Groups)>0 && is_array($Groups)) { $acl_where = array(); for($i=0;$i<count($Groups);$i++) { $g = $Groups[$i]; if(strlen($g)>0) $acl_where[] = "(FIND_IN_SET($g,acl) OR ((NOT FIND_IN_SET($g,dacl)) AND acl='')) "; } if(count($acl_where)) { $acl_where = "(".implode(" OR ",$acl_where).")"; } else $acl_where = "(FIND_IN_SET(0,acl))"; } else $acl_where = "(FIND_IN_SET(0,acl))"; return $acl_where; } function GetEditTable($base_table) { $prefix = GetTablePrefix(); if(strlen($prefix)) { if(substr($base_table,0,strlen($prefix))!=$prefix) $base_table = $prefix.$base_table; } $table = $prefix."ses_".$this->GetSessionKey()."_edit_".$base_table; //echo "Table: $table <br>\n"; return $table; } function GetSessionTable($base_table,$name) { $prefix = GetTablePrefix(); if(strlen($prefix)) { if(substr($base_table,0,strlen($prefix))!=$prefix) $base_table = $prefix.$base_table; } $table = $prefix."ses_".$this->GetSessionKey()."_".$name.$base_table; //echo "Table: $table <br>\n"; return $table; } function GetSearchTable($base_table="") { $prefix = GetTablePrefix(); if(strlen($base_table)) { if(strlen($prefix)) { if(substr($base_table,0,strlen($prefix))!=$prefix) $base_table = $prefix.$base_table; } $table = $prefix."ses_".$this->GetSessionKey()."_search_".$base_table; } else $table = $this->GetSessionTable('Search',''); //$prefix."ses_".$this->GetSessionKey()."_search"; return $table; } function GetTotalSessions() { # $time = time() - 900; $sql = "SELECT count(*) as SesCount FROM ".GetTablePrefix()."UserSession"; $result = $this->adodbConnection->Execute($sql); if ($result === false) { $this->m_Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"GetTotalSessions"); return false; } return $result->fields["SesCount"]; } function Query_UserSession($whereClause,$orderByClause) { $resultSet = array(); $sql = "SELECT ".GetTablePrefix()."* FROM ".GetTablePrefix()."UserSession "; if(isset($whereClause)) $sql = sprintf('%s WHERE %s',$sql,$whereClause); if(isset($orderByClause)) $sql = sprintf('%s ORDER BY %s',$sql,$orderByClause); $result = $this->adodbConnection->Execute($sql); if ($result === false) { $this->m_Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"Query_UserSession"); return false; } while (!$result->EOF) { $item = new clsUserSession(NULL); $item->Set("SessionKey",$result->fields["SessionKey"]); $item->Set("LastAccessed", $result->fields["LastAccessed"]); $item->Set("PortalUserId", $result->fields["PortalUserId"]); $item->Set("Language", $result->fields["Language"]); $item->Set("Theme" , $result->fields["Theme"]); array_push($resultSet,$item); $result->MoveNext(); } return $resultSet; } function GetUniqueKey() { while(true) { /* create the new session key here */ mt_srand(100000000*(double)microtime()); $sessionId=strtoupper(sprintf("AD%xFD",mt_rand(100000000,999999999))); //9 digit hex session id $query = "select SessionKey from ".GetTablePrefix()."UserSession "; $query .= "where SessionKey='$sessionId' OR CurrentTempKey='$sessionId' OR PrevTempKey='$sessionId'"; $rs = $this->adodbConnection->Execute($query); if($rs->EOF) break; if($i>100) { return ""; } $i++; } //echo "Getting Unique Key: $sessionId<br>"; return $sessionId; } function GetNewSession() { global $sessionId, $objConfig, $objLanguages, $m_var_list; $i=0; if($this->Get("PortalUserId")>0 || $objConfig->Get("GuestSessions")==1) { //echo "Creating Session<br>\n"; $sessionId = $this->GetUniqueKey(); $this->Set("SessionKey", $sessionId); $this->Set("CurrentTempKey",$sessionId); if($m_var_list["lang"]) { $this->Set("Language",$m_var_list["lang"]); } else $this->Set("Language", $objLanguages->GetPrimary()); $this->SetThemeName(); //$this->Set("Theme", $objConfig->Get("Default_Theme")); $this->UpdateAccessTime(); $this->Set("IpAddress", $_SERVER['REMOTE_ADDR'] ); $this->Create(); } else $this->Set("SessionKey",""); } function SessionEnabled() { $res = FALSE; $key = $this->GetSessionKey(); if(strlen($key)>0) $res = TRUE; return $res; } function GetSessionKey() { return $this->Get("SessionKey"); } function SetThemeName($id=0) { global $objThemes; if($id==0) $id = $objThemes->GetPrimaryTheme(); $Theme = $objThemes->GetItem($id); $name = $Theme->Get("Name"); $this->Set("Theme",$name); //$this->Update(); } function ValidSession($SessionKey=NULL) { global $objConfig; $a = $this->Get("LastAccessed"); $cutoff = time()-$objConfig->Get("SessionTimeout"); //echo $a." ".$cutoff."<br>"; //$ip = ($_SERVER['REMOTE_ADDR'] == $this->Get("IpAddress")); //echo $this->Get("IpAddress"); //$ip = TRUE; if ($a < $cutoff) { //$this->UpdateAccessTime(); } return ($a >= $cutoff); } function UpdateAccessTime() { $now = time(); $this->Set("LastAccessed",$now); } function InSpamControl($ResourceId,$DataType=NULL) { static $ClearStat; if(!$ClearStat) $this->PurgeSpamControl(); $ClearStat=1; if(strlen($DataType)) $DataType="'".$DataType."'"; $sql = "SELECT count(*) as SpamCount FROM ".GetTablePrefix()."SpamControl WHERE ItemResourceId=$ResourceId AND DataType=$DataType"; if($this->Get("PortalUserId")==0) { $sql .= " AND PortalUserId=0 AND IPaddress='".$_SERVER["REMOTE_ADDR"]."'"; } else { $sql .= " AND PortalUserId=".$this->Get("PortalUserId"); } $rs = $this->adodbConnection->Execute($sql); $value = (int)$rs->fields["SpamCount"]; if($value>0) { return TRUE; } else return FALSE; } function AddToSpamControl($ResourceId,$secstoexpire,$DataType=NULL) { $expire = adodb_date("U") + $secstoexpire; if(strlen($DataType)) $DataType = "'".$DataType."'"; $sql = "INSERT INTO ".GetTablePrefix()."SpamControl (ItemResourceId,IPaddress,Expire,PortalUserId,DataType) VALUES ("; $sql .= $ResourceId.",'".$_SERVER["REMOTE_ADDR"]."',$expire,".$this->Get("PortalUserId").",$DataType)"; //echo $sql; $this->adodbConnection->Execute($sql); } function PurgeSpamControl() { $sql = "DELETE FROM ".GetTablePrefix()."SpamControl WHERE Expire<".adodb_date("U"); $this->adodbConnection->Execute($sql); } }/* clsUserSession */ ?> Property changes on: trunk/kernel/include/usersession.php ___________________________________________________________________ Modified: cvs2svn:cvs-rev ## -1 +1 ## -1.38 \ No newline at end of property +1.39 \ No newline at end of property Index: trunk/core/kernel/application.php =================================================================== --- trunk/core/kernel/application.php (revision 2391) +++ trunk/core/kernel/application.php (revision 2392) @@ -1,1237 +1,1252 @@ <?php /** * Basic class for Kernel3-based Application * * This class is a Facade for any other class which needs to deal with Kernel3 framework.<br> * The class incapsulates the main run-cycle of the script, provide access to all other objects in the framework.<br> * <br> * The class is a singleton, which means that there could be only one instance of KernelApplication in the script.<br> * This could be guranteed by NOT calling the class constuctor directly, but rather calling KernelApplication::Instance() method, * which returns an instance of the application. The method gurantees that it will return exactly the same instance for any call.<br> * See singleton pattern by GOF. * @package kernel4 */ class kApplication { /** * Is true, when Init method was called already, prevents double initialization * * @var bool */ var $InitDone = false; /** * Holds internal TemplateParser object * @access private * @var TemplateParser */ var $Parser; /** * Holds parser output buffer * @access private * @var string */ var $HTML; /** * Prevents request from beeing proceeded twice in case if application init is called mere then one time * * @var bool * @todo This is not good anyway (by Alex) */ var $RequestProcessed = false; /** * The main Factory used to create * almost any class of kernel and * modules * * @access private * @var kFactory */ var $Factory; /** * Holds all phrases used * in code and template * * @var PhrasesCache */ var $Phrases; /** * Holds DBConnection * * @var kDBConnection */ var $DB; /** * Returns kApplication instance anywhere in the script. * * This method should be used to get single kApplication object instance anywhere in the * Kernel-based application. The method is guranteed to return the SAME instance of kApplication. * Anywhere in the script you could write: * <code> * $application =& kApplication::Instance(); * </code> * or in an object: * <code> * $this->Application =& kApplication::Instance(); * </code> * to get the instance of kApplication. Note that we call the Instance method as STATIC - directly from the class. * To use descendand of standard kApplication class in your project you would need to define APPLICATION_CLASS constant * BEFORE calling kApplication::Instance() for the first time. If APPLICATION_CLASS is not defined the method would * create and return default KernelApplication instance. * @static * @access public * @return kApplication */ function &Instance() { static $instance = false; if(!$instance) { if (!defined('APPLICATION_CLASS')) define('APPLICATION_CLASS', 'kApplication'); $class = APPLICATION_CLASS; $instance = new $class(); } return $instance; } /** * Initializes the Application * * @access public * @see HTTPQuery * @see Session * @see TemplatesCache * @return bool Was Init actually made now or before */ function Init() { if($this->InitDone) return false; if (defined('DEBUG_MODE') && DEBUG_MODE && dbg_ConstOn('DBG_PROFILE_MEMORY') ) { global $debugger; $debugger->appendMemoryUsage('Application before Init:'); } if( !$this->isDebugMode() ) set_error_handler( Array(&$this,'handleError') ); $this->DB = new kDBConnection(SQL_TYPE, Array(&$this,'handleSQLError') ); $this->DB->Connect(SQL_SERVER, SQL_USER, SQL_PASS, SQL_DB); $this->DB->debugMode = $this->isDebugMode(); $this->SetDefaultConstants(); $this->Factory = new kFactory(); $this->registerDefaultClasses(); // 1. to read configs before doing any recallObject $config_reader =& $this->recallObject('kUnitConfigReader'); if( !$this->GetVar('m_lang') ) $this->SetVar('m_lang', $this->GetDefaultLanguageId() ); if( !$this->GetVar('m_theme') ) $this->SetVar('m_theme', $this->GetDefaultThemeId() ); if( $this->GetVar('m_cat_id') === false ) $this->SetVar('m_cat_id', 0); $this->Phrases = new PhrasesCache( $this->GetVar('m_lang') ); $this->SetVar('lang.current_id', $this->GetVar('m_lang') ); $language =& $this->recallObject('lang.current', null, Array('live_table'=>true) ); if( !$this->GetVar('m_theme') ) $this->SetVar('m_theme', $this->GetDefaultThemeId() ); $this->SetVar('theme.current_id', $this->GetVar('m_theme') ); if( !$this->RecallVar('UserGroups') ) { $ses =& $this->recallObject('Session'); $user_groups = trim($ses->GetField('GroupList'), ','); if (!$user_groups) $user_groups = $this->ConfigValue('User_GuestGroup'); $this->StoreVar('UserGroups', $user_groups); } if( !$this->RecallVar('curr_iso') ) $this->StoreVar('curr_iso', $this->GetPrimaryCurrency() ); + $this->SetVar('visits_id', $this->RecallVar('visit_id') ); + $this->ValidateLogin(); // TODO: write that method if( $this->isDebugMode() ) { global $debugger; $debugger->profileFinish('kernel4_startup'); } if(defined('CMS') && CMS==1 && !$this->GetVar('admin') && !$this->IsAdmin() ){ define('MOD_REWRITE', 1); } $this->InitDone = true; return true; } function GetDefaultLanguageId() { $table = $this->getUnitOption('lang','TableName'); $id_field = $this->getUnitOption('lang','IDField'); return $this->DB->GetOne('SELECT '.$id_field.' FROM '.$table.' WHERE PrimaryLang = 1'); } function GetDefaultThemeId() { if (defined('DBG_FORCE_THEME') && DBG_FORCE_THEME){ return DBG_FORCE_THEME; } $table = $this->getUnitOption('theme','TableName'); $id_field = $this->getUnitOption('theme','IDField'); return $this->DB->GetOne('SELECT '.$id_field.' FROM '.$table.' WHERE PrimaryTheme = 1'); } function GetPrimaryCurrency() { $this->setUnitOption('mod','AutoLoad',false); $module =& $this->recallObject('mod'); $this->setUnitOption('mod','AutoLoad',true); if( $module->Load('In-Commerce') ) { $table = $this->getUnitOption('curr','TableName'); return $this->DB->GetOne('SELECT ISO FROM '.$table.' WHERE IsPrimary = 1'); } else { return 'USD'; } } /** * Registers default classes such as ItemController, GridController and LoginController * * Called automatically while initializing Application * @access private * @return void */ function RegisterDefaultClasses() { //$this->registerClass('Utilites',KERNEL_PATH.'/utility/utilities.php'); $this->registerClass('HTTPQuery',KERNEL_PATH.'/utility/http_query.php'); $this->registerClass('Session',KERNEL_PATH.'/session/session.php'); $this->registerClass('SessionStorage',KERNEL_PATH.'/session/session.php'); $this->registerClass('LoginEventHandler',KERNEL_PATH.'/session/login_event_handler.php','login_EventHandler'); $this->registerClass('kEventManager',KERNEL_PATH.'/event_manager.php','EventManager'); $this->registerClass('kUnitConfigReader',KERNEL_PATH.'/utility/unit_config_reader.php'); $this->registerClass('Params',KERNEL_PATH.'/utility/params.php','kActions'); $this->registerClass('kArray',KERNEL_PATH.'/utility/params.php','kArray'); $this->registerClass('kFormatter', KERNEL_PATH.'/utility/formatters.php'); $this->registerClass('kOptionsFormatter', KERNEL_PATH.'/utility/formatters.php'); $this->registerClass('kUploadFormatter', KERNEL_PATH.'/utility/formatters.php'); $this->registerClass('kPictureFormatter', KERNEL_PATH.'/utility/formatters.php'); $this->registerClass('kDateFormatter', KERNEL_PATH.'/utility/formatters.php'); $this->registerClass('kLEFTFormatter', KERNEL_PATH.'/utility/formatters.php'); $this->registerClass('kMultiLanguage', KERNEL_PATH.'/utility/formatters.php'); $this->registerClass('kPasswordFormatter', KERNEL_PATH.'/utility/formatters.php'); $this->registerClass('kCCDateFormatter', KERNEL_PATH.'/utility/formatters.php'); $this->registerClass('kUnitFormatter', KERNEL_PATH.'/utility/formatters.php'); $this->registerClass('kFilesizeFormatter', KERNEL_PATH.'/utility/formatters.php'); $this->registerClass('kTempTablesHandler', KERNEL_PATH.'/utility/temp_handler.php'); $event_manager =& $this->recallObject('EventManager'); $event_manager->registerBuildEvent('kTempTablesHandler','OnTempHandlerBuild'); //$this->registerClass('Configuration',KERNEL_PATH.'/utility/configuration.php'); $this->registerClass('TemplatesCache',KERNEL_PATH.'/parser/template.php'); $this->registerClass('Template',KERNEL_PATH.'/parser/template.php'); $this->registerClass('TemplateParser',KERNEL_PATH.'/parser/template_parser.php'); $this->registerClass('MainProcessor', KERNEL_PATH.'/processors/main_processor.php','m_TagProcessor'); $this->registerClass('kMultipleFilter', KERNEL_PATH.'/utility/filters.php'); $this->registerClass('kDBList', KERNEL_PATH.'/db/dblist.php'); $this->registerClass('kDBItem', KERNEL_PATH.'/db/dbitem.php'); $this->registerClass('kDBEventHandler', KERNEL_PATH.'/db/db_event_handler.php'); $this->registerClass('kDBTagProcessor', KERNEL_PATH.'/db/db_tag_processor.php'); $this->registerClass('kTagProcessor', KERNEL_PATH.'/processors/tag_processor.php'); $this->registerClass('kEmailMessage',KERNEL_PATH.'/utility/email.php'); $this->registerClass('kSmtpClient',KERNEL_PATH.'/utility/smtp_client.php'); if (file_exists(MODULES_PATH.'/in-commerce/units/currencies/currency_rates.php')) { $this->registerClass('kCurrencyRates',MODULES_PATH.'/in-commerce/units/currencies/currency_rates.php'); } $this->registerClass('FCKeditor', DOC_ROOT.BASE_PATH.'/'.ADMIN_DIR.'/editor/cmseditor/fckeditor.php'); /*$this->RegisterClass('LoginController', KERNEL_PATH.'/users/login_controller.php');*/ } /** * Defines default constants if it's not defined before - in config.php * * Called automatically while initializing Application and defines: * LOGIN_CONTROLLER, XML_FACTORY etc. * @access private * @return void */ function SetDefaultConstants() { if (!defined('SERVER_NAME')) define('SERVER_NAME', $_SERVER['HTTP_HOST']); $admin_dir = $this->ConfigValue('AdminDirectory'); if(!$admin_dir) $admin_dir = 'admin'; safeDefine('ADMIN_DIR', $admin_dir); } function ProcessRequest() { $event_manager =& $this->recallObject('EventManager'); if( $this->isDebugMode() && dbg_ConstOn('DBG_SHOW_HTTPQUERY') ) { global $debugger; $http_query =& $this->recallObject('HTTPQuery'); $debugger->appendHTML('HTTPQuery:'); $debugger->dumpVars($http_query->_Params); } $event_manager->ProcessRequest(); $event_manager->RunRegularEvents(reBEFORE); $this->RequestProcessed = true; } /** * Actually runs the parser against current template and stores parsing result * * This method gets t variable passed to the script, loads the template given in t variable and * parses it. The result is store in {@link $this->HTML} property. * @access public * @return void */ function Run() { if (defined('DEBUG_MODE') && DEBUG_MODE && dbg_ConstOn('DBG_PROFILE_MEMORY') ) { global $debugger; $debugger->appendMemoryUsage('Application before Run:'); } if (!$this->RequestProcessed) $this->ProcessRequest(); $this->InitParser(); $template_cache =& $this->recallObject('TemplatesCache'); $t = $this->GetVar('t'); if(defined('CMS') && CMS) { $cms_handler =& $this->recallObject('cms_EventHandler'); if( !$template_cache->TemplateExists($t) ) { $t = $cms_handler->GetDesignTemplate(); } else { $cms_handler->SetCatByTemplate(); } } if (defined('DEBUG_MODE') && DEBUG_MODE && dbg_ConstOn('DBG_PROFILE_MEMORY') ) { global $debugger; $debugger->appendMemoryUsage('Application before Parsing:'); } $this->HTML = $this->Parser->Parse( $template_cache->GetTemplateBody($t), $t ); if (defined('DEBUG_MODE') && DEBUG_MODE && dbg_ConstOn('DBG_PROFILE_MEMORY') ) { global $debugger; $debugger->appendMemoryUsage('Application after Parsing:'); } } function InitParser() { if( !is_object($this->Parser) ) $this->Parser =& $this->recallObject('TemplateParser'); } /** * Send the parser results to browser * * Actually send everything stored in {@link $this->HTML}, to the browser by echoing it. * @access public * @return void */ function Done() { if (defined('DEBUG_MODE') && DEBUG_MODE && dbg_ConstOn('DBG_PROFILE_MEMORY') ) { global $debugger; $debugger->appendMemoryUsage('Application before Done:'); } if ($this->GetVar('admin')) { $reg = '/('.preg_quote(BASE_PATH, '/').'.*\.html)(#.*){0,1}(")/sU'; $this->HTML = preg_replace($reg, "$1?admin=1$2$3", $this->HTML); } //eval("?".">".$this->HTML); echo $this->HTML; $this->Phrases->UpdateCache(); flush(); $event_manager =& $this->recallObject('EventManager'); $event_manager->RunRegularEvents(reAFTER); $session =& $this->recallObject('Session'); $session->SaveData(); //$this->SaveBlocksCache(); } function SaveBlocksCache() { /*if (defined('EXPERIMENTAL_PRE_PARSE')) { $data = serialize($this->PreParsedCache); $this->DB->Query('REPLACE '.TABLE_PREFIX.'Cache (VarName, Data, Cached) VALUES ("blocks_cache", '.$this->DB->qstr($data).', '.time().')'); }*/ } // Facade /** * Returns current session id (SID) * @access public * @return longint */ function GetSID() { $session =& $this->recallObject('Session'); return $session->GetID(); } function DestroySession() { $session =& $this->recallObject('Session'); $session->Destroy(); } /** * Returns variable passed to the script as GET/POST/COOKIE * * @access public * @param string $var Variable name * @return mixed */ function GetVar($var,$mode=FALSE_ON_NULL) { $http_query =& $this->recallObject('HTTPQuery'); return $http_query->Get($var,$mode); } /** * Returns ALL variables passed to the script as GET/POST/COOKIE * * @access public * @return array */ function GetVars() { $http_query =& $this->recallObject('HTTPQuery'); return $http_query->GetParams(); } /** * Set the variable 'as it was passed to the script through GET/POST/COOKIE' * * This could be useful to set the variable when you know that * other objects would relay on variable passed from GET/POST/COOKIE * or you could use SetVar() / GetVar() pairs to pass the values between different objects.<br> * * This method is formerly known as $this->Session->SetProperty. * @param string $var Variable name to set * @param mixed $val Variable value * @access public * @return void */ function SetVar($var,$val) { $http_query =& $this->recallObject('HTTPQuery'); $http_query->Set($var,$val); } /** * Deletes Session variable * * @param string $var */ function RemoveVar($var) { $session =& $this->recallObject('Session'); return $session->RemoveVar($var); } /** * Deletes HTTPQuery variable * * @param string $var * @todo think about method name */ function DeleteVar($var) { $http_query =& $this->recallObject('HTTPQuery'); return $http_query->Remove($var); } /** * Returns session variable value * * Return value of $var variable stored in Session. An optional default value could be passed as second parameter. * * @see SimpleSession * @access public * @param string $var Variable name * @param mixed $default Default value to return if no $var variable found in session * @return mixed */ function RecallVar($var,$default=false) { $session =& $this->recallObject('Session'); return $session->RecallVar($var,$default); } /** * Stores variable $val in session under name $var * * Use this method to store variable in session. Later this variable could be recalled. * @see RecallVar * @access public * @param string $var Variable name * @param mixed $val Variable value */ function StoreVar($var, $val) { $session =& $this->recallObject('Session'); $session->StoreVar($var, $val); } function StoreVarDefault($var, $val) { $session =& $this->recallObject('Session'); $session->StoreVarDefault($var, $val); } /** * Links HTTP Query variable with session variable * * If variable $var is passed in HTTP Query it is stored in session for later use. If it's not passed it's recalled from session. * This method could be used for making sure that GetVar will return query or session value for given * variable, when query variable should overwrite session (and be stored there for later use).<br> * This could be used for passing item's ID into popup with multiple tab - * in popup script you just need to call LinkVar('id', 'current_id') before first use of GetVar('id'). * After that you can be sure that GetVar('id') will return passed id or id passed earlier and stored in session * @access public * @param string $var HTTP Query (GPC) variable name * @param mixed $ses_var Session variable name * @param mixed $default Default variable value */ function LinkVar($var, $ses_var=null, $default='') { if (!isset($ses_var)) $ses_var = $var; if ($this->GetVar($var) !== false) { $this->StoreVar($ses_var, $this->GetVar($var)); } else { $this->SetVar($var, $this->RecallVar($ses_var, $default)); } } /** * Returns variable from HTTP Query, or from session if not passed in HTTP Query * * The same as LinkVar, but also returns the variable value taken from HTTP Query if passed, or from session if not passed. * Returns the default value if variable does not exist in session and was not passed in HTTP Query * * @see LinkVar * @access public * @param string $var HTTP Query (GPC) variable name * @param mixed $ses_var Session variable name * @param mixed $default Default variable value * @return mixed */ function GetLinkedVar($var, $ses_var=null, $default='') { if (!isset($ses_var)) $ses_var = $var; $this->LinkVar($var, $ses_var, $default); return $this->GetVar($var); } function AddBlock($name, $tpl) { $this->cache[$name] = $tpl; } function SetTemplateBody($title,$body) { $templates_cache =& $this->recallObject('TemplatesCache'); $templates_cache->SetTemplateBody($title,$body); } function ProcessTag($tag_data) { $a_tag = new Tag($tag_data,$this->Parser); return $a_tag->DoProcessTag(); } function ProcessParsedTag($prefix, $tag, $params) { $a_tag = new Tag('',$this->Parser); $a_tag->Tag = $tag; $a_tag->Processor = $prefix; $a_tag->NamedParams = $params; return $a_tag->DoProcessTag(); } /** * Return ADODB Connection object * * Returns ADODB Connection object already connected to the project database, configurable in config.php * @access public * @return kDBConnection */ function &GetADODBConnection() { return $this->DB; } function ParseBlock($params,$pass_params=0,$as_template=false) { if (substr($params['name'], 0, 5) == 'html:') return substr($params['name'], 6); return $this->Parser->ParseBlock($params, $pass_params, $as_template); } /** * Return href for template * * @access public * @param string $t Template path * @var string $prefix index.php prefix - could be blank, 'admin' */ function HREF($t, $prefix='', $params=null, $index_file=null) { global $HTTP_SERVER_VARS; if (defined('ADMIN') && $prefix == '') $prefix='/admin'; if (defined('ADMIN') && $prefix == '_FRONT_END_') $prefix = ''; $index_file = isset($index_file) ? $index_file : (defined('INDEX_FILE') ? INDEX_FILE : basename($_SERVER['SCRIPT_NAME'])); if( isset($params['index_file']) ) $index_file = $params['index_file']; if (getArrayValue($params, 'opener') == 'u') { $opener_stack=$this->RecallVar('opener_stack'); if($opener_stack) { $opener_stack=unserialize($opener_stack); if (count($opener_stack) > 0) { list($index_file, $env) = explode('|', $opener_stack[count($opener_stack)-1]); $ret = $this->BaseURL($prefix).$index_file.'?'.ENV_VAR_NAME.'='.$env; if( getArrayValue($params,'escape') ) $ret = addslashes($ret); return $ret; } else { //define('DBG_REDIRECT', 1); $t = $this->GetVar('t'); } } else { //define('DBG_REDIRECT', 1); $t = $this->GetVar('t'); } } $pass = isset($params['pass']) ? $params['pass'] : ''; $pass_events = isset($params['pass_events']) ? $params['pass_events'] : false; // pass events with url if (defined('MOD_REWRITE') && MOD_REWRITE) { $env = $this->BuildEnv('', $params, $pass, $pass_events, false); $env = ltrim($env, ':-'); $session =& $this->recallObject('Session'); $sid = $session->NeedQueryString() ? '?sid='.$this->GetSID() : ''; // $env = str_replace(':', '/', $env); $ret = rtrim($this->BaseURL($prefix).$t.'.html/'.$env.'/'.$sid, '/'); } else { $env = $this->BuildEnv($t, $params, $pass, $pass_events); $ret = $this->BaseURL($prefix).$index_file.'?'.$env; } return $ret; } function BuildEnv($t, $params, $pass='all', $pass_events=false, $env_var=true) { $session =& $this->recallObject('Session'); $sid = $session->NeedQueryString() && !(defined('MOD_REWRITE') && MOD_REWRITE) ? $this->GetSID() : ''; if( getArrayValue($params,'admin') == 1 ) $sid = $this->GetSID(); $ret = ''; if ($env_var) { $ret = ENV_VAR_NAME.'='; } $ret .= defined('INPORTAL_ENV') ? $sid.'-'.$t : $sid.':'.$t; $pass = str_replace('all', trim($this->GetVar('passed'), ','), $pass); if(strlen($pass) > 0) { $pass_info = array_unique( explode(',',$pass) ); // array( prefix[.special], prefix[.special] ... foreach($pass_info as $pass_element) { $ret.=':'; list($prefix)=explode('.',$pass_element); $query_vars = $this->getUnitOption($prefix,'QueryString'); //if pass events is off and event is not implicity passed if(!$pass_events && !isset($params[$pass_element.'_event'])) { $params[$pass_element.'_event'] = ''; // remove event from url if requested //otherwise it will use value from get_var } if($query_vars) { $tmp_string=Array(0=>$pass_element); foreach($query_vars as $index => $var_name) { //if value passed in params use it, otherwise use current from application $tmp_string[$index] = isset( $params[$pass_element.'_'.$var_name] ) ? $params[$pass_element.'_'.$var_name] : $this->GetVar($pass_element.'_'.$var_name); if ( isset($params[$pass_element.'_'.$var_name]) ) { unset( $params[$pass_element.'_'.$var_name] ); } } $escaped = array(); foreach ($tmp_string as $tmp_val) { $escaped[] = str_replace(Array('-',':'), Array('\-','\:'), $tmp_val); } if ($this->getUnitOption($prefix, 'PortalStyleEnv') == true) { $ret.= array_shift($escaped).array_shift($escaped).'-'.implode('-',$escaped); } else { $ret.=implode('-',$escaped); } } } } unset($params['pass']); unset($params['opener']); unset($params['m_event']); if ($this->GetVar('admin') && !isset($params['admin'])) { $params['admin'] = 1; } if( getArrayValue($params,'escape') ) { $ret = addslashes($ret); unset($params['escape']); } foreach ($params as $param => $value) { $ret .= '&'.$param.'='.$value; } return $ret; } function BaseURL($prefix='') { return PROTOCOL.SERVER_NAME.(defined('PORT')?':'.PORT : '').BASE_PATH.$prefix.'/'; } function Redirect($t='', $params=null, $prefix='', $index_file=null) { if ($t == '' || $t === true) $t = $this->GetVar('t'); // pass prefixes and special from previous url if (!isset($params['pass'])) $params['pass'] = 'all'; $location = $this->HREF($t, $prefix, $params, $index_file); $a_location = $location; $location = "Location: $location"; //echo " location : $location <br>"; if( $this->isDebugMode() && dbg_ConstOn('DBG_REDIRECT') ) { $GLOBALS['debugger']->appendTrace(); echo "<b>Debug output above!!!</b> Proceed to redirect: <a href=\"$a_location\">$a_location</a><br>"; } else { if(headers_sent() != '') { echo '<script language="javascript" type="text/javascript">window.location.href = \''.$a_location.'\';</script>'; } else { header("$location"); } } $session =& $this->recallObject('Session'); $session->SaveData(); $this->SaveBlocksCache(); exit; } function Phrase($label) { return $this->Phrases->GetPhrase($label); } /** * Replace language tags in exclamation marks found in text * * @param string $text * @param bool $force_escape force escaping, not escaping of resulting string * @return string * @access public */ function ReplaceLanguageTags($text, $force_escape=null) { return $this->Phrases->ReplaceLanguageTags($text,$force_escape); } /** * Validtates user in session if required * */ function ValidateLogin() { if (defined('LOGIN_REQUIRED')) { // Original Kostja call //$login_controller =& $this->Factory->MakeClass(LOGIN_CONTROLLER, Array('model' => USER_MODEL, 'prefix' => 'login')); // Call proposed by Alex //$login_controller =& $this->RecallObject(LOGIN_CONTROLLER, Array('model' => USER_MODEL, 'prefix' => 'login')); //$login_controller->CheckLogin(); } } /** * Returns configuration option value by name * * @param string $name * @return string */ function ConfigValue($name) { return $this->DB->GetOne('SELECT VariableValue FROM '.TABLE_PREFIX.'ConfigurationValues WHERE VariableName = '.$this->DB->qstr($name) ); } /** * Allows to process any type of event * * @param kEvent $event * @access public * @author Alex */ function HandleEvent(&$event, $params=null, $specificParams=null) { if ( isset($params) ) { $event = new kEvent( $params, $specificParams ); } $event_manager =& $this->recallObject('EventManager'); $event_manager->HandleEvent($event); } /** * Registers new class in the factory * * @param string $real_class * @param string $file * @param string $pseudo_class * @access public * @author Alex */ function registerClass($real_class,$file,$pseudo_class=null) { $this->Factory->registerClass($real_class,$file,$pseudo_class); } /** * Registers Hook from subprefix event to master prefix event * * @param string $hookto_prefix * @param string $hookto_special * @param string $hookto_event * @param string $mode * @param string $do_prefix * @param string $do_special * @param string $do_event * @param string $conditional * @access public * @todo take care of a lot parameters passed * @author Kostja */ function registerHook($hookto_prefix, $hookto_special, $hookto_event, $mode, $do_prefix, $do_special, $do_event, $conditional) { $event_manager =& $this->recallObject('EventManager'); $event_manager->registerHook($hookto_prefix, $hookto_special, $hookto_event, $mode, $do_prefix, $do_special, $do_event, $conditional); } /** * Allows one TagProcessor tag act as other TagProcessor tag * * @param Array $tag_info * @author Kostja */ function registerAggregateTag($tag_info) { $aggregator =& $this->recallObject('TagsAggregator', 'kArray'); $aggregator->SetArrayValue($tag_info['AggregateTo'], $tag_info['AggregatedTagName'], Array($tag_info['LocalPrefix'], $tag_info['LocalTagName'], getArrayValue($tag_info, 'LocalSpecial'))); } /** * Returns object using params specified, * creates it if is required * * @param string $name * @param string $pseudo_class * @param Array $event_params * @return Object * @author Alex */ function &recallObject($name,$pseudo_class=null,$event_params=Array()) { $o1 =& $this->Factory->getObject($name,$pseudo_class,$event_params); //$o1->param1 = 'one'; /*$func_args = func_get_args(); $factory =& $this->Factory; $o2 =& call_user_func_array( Array(&$factory, 'getObject'), $func_args );*/ //$o2->param1 = 'two'; return $o1; } /** * Checks if object with prefix passes was already created in factory * * @param string $name object presudo_class, prefix * @return bool * @author Kostja */ function hasObject($name) { return isset($this->Factory->Storage[$name]); } /** * Removes object from storage by given name * * @param string $name Object's name in the Storage * @author Kostja */ function removeObject($name) { $this->Factory->DestroyObject($name); } /** * Get's real class name for pseudo class, * includes class file and creates class * instance * * @param string $pseudo_class * @return Object * @access public * @author Alex */ function &makeClass($pseudo_class) { $func_args = func_get_args(); return call_user_func_array( Array(&$this->Factory, 'makeClass'), $func_args); } /** * Checks if application is in debug mode * * @return bool * @access public * @author Alex */ function isDebugMode() { return defined('DEBUG_MODE') && DEBUG_MODE; } /** * Checks if it is admin * * @return bool * @author Alex */ function IsAdmin() { return defined('ADMIN') && ADMIN; } /** * Reads unit (specified by $prefix) * option specified by $option * * @param string $prefix * @param string $option * @return string * @access public * @author Alex */ function getUnitOption($prefix,$option) { $unit_config_reader =& $this->recallObject('kUnitConfigReader'); return $unit_config_reader->getUnitOption($prefix,$option); } /** * Set's new unit option value * * @param string $prefix * @param string $name * @param string $value * @author Alex * @access public */ function setUnitOption($prefix,$option,$value) { $unit_config_reader =& $this->recallObject('kUnitConfigReader'); return $unit_config_reader->setUnitOption($prefix,$option,$value); } /** * Read all unit with $prefix options * * @param string $prefix * @return Array * @access public * @author Alex */ function getUnitOptions($prefix) { $unit_config_reader =& $this->recallObject('kUnitConfigReader'); return $unit_config_reader->getUnitOptions($prefix); } /** * Returns true if config exists and is allowed for reading * * @param string $prefix * @return bool */ function prefixRegistred($prefix) { $unit_config_reader =& $this->recallObject('kUnitConfigReader'); return $unit_config_reader->prefixRegistred($prefix); } /** * Splits any mixing of prefix and * special into correct ones * * @param string $prefix_special * @return Array * @access public * @author Alex */ function processPrefix($prefix_special) { return $this->Factory->processPrefix($prefix_special); } /** * Set's new event for $prefix_special * passed * * @param string $prefix_special * @param string $event_name * @access public */ function setEvent($prefix_special,$event_name) { $event_manager =& $this->recallObject('EventManager'); $event_manager->setEvent($prefix_special,$event_name); } /** * SQL Error Handler * * @param int $code * @param string $msg * @param string $sql * @return bool * @access private * @author Alex */ function handleSQLError($code,$msg,$sql) { global $debugger; if($debugger) { $errorLevel=defined('DBG_SQL_FAILURE') && DBG_SQL_FAILURE ? E_USER_ERROR : E_USER_WARNING; $debugger->dumpVars($_REQUEST); $debugger->appendTrace(); $error_msg = '<span class="debug_error">'.$msg.' ('.$code.')</span><br><a href="javascript:SetClipboard(\''.htmlspecialchars($sql).'\');"><b>SQL</b></a>: '.$debugger->formatSQL($sql); $long_id=$debugger->mapLongError($error_msg); trigger_error( substr($msg.' ('.$code.') ['.$sql.']',0,1000).' #'.$long_id, $errorLevel); return true; } else { //$errorLevel = defined('IS_INSTALL') && IS_INSTALL ? E_USER_WARNING : E_USER_ERROR; $errorLevel = E_USER_WARNING; trigger_error('<b>SQL Error</b> in sql: '.$sql.', code <b>'.$code.'</b> ('.$msg.')', $errorLevel); /*echo '<b>xProcessing SQL</b>: '.$sql.'<br>'; echo '<b>Error ('.$code.'):</b> '.$msg.'<br>';*/ return $errorLevel == E_USER_ERROR ? false : true; } } /** * Default error handler * * @param int $errno * @param string $errstr * @param string $errfile * @param int $errline * @param Array $errcontext */ function handleError($errno, $errstr, $errfile = '', $errline = '', $errcontext = '') { if (defined('SILENT_LOG') && SILENT_LOG) { $fp = fopen(DOC_ROOT.BASE_PATH.'/silent_log.txt','a'); $time = date('d/m/Y H:i:s'); fwrite($fp, '['.$time.'] #'.$errno.': '.strip_tags($errstr).' in ['.$errfile.'] on line '.$errline."\n"); fclose($fp); } } /** * Returns & blocks next ResourceId available in system * * @return int * @access public * @author Eduard */ function NextResourceId() { $this->DB->Query('LOCK TABLES '.TABLE_PREFIX.'IdGenerator WRITE'); $this->DB->Query('UPDATE '.TABLE_PREFIX.'IdGenerator SET lastid = lastid+1'); $id = $this->DB->GetOne("SELECT lastid FROM ".TABLE_PREFIX."IdGenerator"); $this->DB->Query('UNLOCK TABLES'); return $id; } /** * Returns main prefix for subtable prefix passes * * @param string $current_prefix * @return string * @access public * @author Kostja */ function GetTopmostPrefix($current_prefix) { while ( $parent_prefix = $this->getUnitOption($current_prefix, 'ParentPrefix') ) { $current_prefix = $parent_prefix; } return $current_prefix; } function EmailEventAdmin($email_event_name, $to_user_id = -1, $send_params = false) { return $this->EmailEvent($email_event_name, 1, $to_user_id, $send_params); } function EmailEventUser($email_event_name, $to_user_id = -1, $send_params = false) { return $this->EmailEvent($email_event_name, 0, $to_user_id, $send_params); } function EmailEvent($email_event_name, $email_event_type, $to_user_id = -1, $send_params = false) { $event = new kEvent('emailevents:OnEmailEvent'); $event->setEventParam('EmailEventName', $email_event_name); $event->setEventParam('EmailEventToUserId', $to_user_id); $event->setEventParam('EmailEventType', $email_event_type); if ($send_params){ $event->setEventParam('DirectSendParams', $send_params); } $this->HandleEvent($event); return $event; } function LoggedIn() { $user =& $this->recallObject('u'); return ($user->GetDBField('PortalUserId') > 0); } function CheckPermission($name, $cat_id = null) { if( !isset($cat_id) ) { $cat_id = $this->GetVar('m_cat_id'); } if( $cat_id == 0 ) { $cat_hierarchy = Array(0); } else { $sql = 'SELECT ParentPath FROM '.$this->getUnitOption('c', 'TableName').' WHERE CategoryId = '.$cat_id; $cat_hierarchy = $this->DB->GetOne($sql); $cat_hierarchy = explode('|', $cat_hierarchy); array_shift($cat_hierarchy); array_pop($cat_hierarchy); $cat_hierarchy = array_reverse($cat_hierarchy); array_push($cat_hierarchy, 0); } $groups = $this->RecallVar('UserGroups'); foreach($cat_hierarchy as $category_id) { $sql = 'SELECT PermissionValue FROM '.TABLE_PREFIX.'Permissions WHERE Permission = "'.$name.'" AND CatId = '.$category_id.' AND GroupId IN ('.$groups.')'; $res = $this->DB->GetOne($sql); if($res !== false) { return $res; } } return 0; } + /** + * Set's any field of current visit + * + * @param string $field + * @param mixed $value + */ + function setVisitField($field, $value) + { + $visit =& $this->recallObject('visits'); + $visit->SetDBField($field, $value); + $visit->Update(); + } + } ?> \ No newline at end of file Property changes on: trunk/core/kernel/application.php ___________________________________________________________________ Modified: cvs2svn:cvs-rev ## -1 +1 ## -1.42 \ No newline at end of property +1.43 \ No newline at end of property Index: trunk/core/units/visits/visits_tag_processor.php =================================================================== --- trunk/core/units/visits/visits_tag_processor.php (revision 2391) +++ trunk/core/units/visits/visits_tag_processor.php (revision 2392) @@ -1,25 +1,26 @@ <?php class VisitsTagProcessor extends kDBTagProcessor { + function UserFound($params) { $virtual_users = Array(-1,-2, 0); $object =& $this->Application->recallObject( $this->getPrefixSpecial(), $this->Prefix, $params ); return !in_array( $object->GetDBField( $params['user_field'] ) , $virtual_users ); } function UserLink($params) { $object =& $this->Application->recallObject( $this->getPrefixSpecial(), $this->Prefix, $params ); $user_id = $object->GetDBField( $params['user_field'] ); if($user_id) { //return $this->Application->HREF('in-commerce/users/users_edit_general','', Array('u_id' => $user_id) ); $resource_id = $this->Conn->GetOne('SELECT ResourceId FROM '.TABLE_PREFIX.'PortalUser WHERE PortalUserId = '.$user_id); return 'javascript:OpenUserEdit('.$resource_id.');'; } - } + } } ?> \ No newline at end of file Property changes on: trunk/core/units/visits/visits_tag_processor.php ___________________________________________________________________ Modified: cvs2svn:cvs-rev ## -1 +1 ## -1.1 \ No newline at end of property +1.2 \ No newline at end of property Index: trunk/core/units/visits/visits_event_handler.php =================================================================== --- trunk/core/units/visits/visits_event_handler.php (revision 2391) +++ trunk/core/units/visits/visits_event_handler.php (revision 2392) @@ -1,21 +1,25 @@ <?php class VisitsEventHandler extends InpDBEventHandler { /** * Registers user visit to site * * @param kEvent $event */ function OnRegisterVisit(&$event) { $object =& $event->getObject( Array('skip_autoload'=>true) ); $object->SetDBField('VisitDate_date', time() ); $object->SetDBField('VisitDate_time', time() ); $object->SetDBField('Referer', getArrayValue($_SERVER, 'HTTP_REFERER') ); $object->SetDBField('IPAddress', $_SERVER['REMOTE_ADDR'] ); - if( $object->Create() ) $this->Application->StoreVar('visit_id', $object->GetID() ); + if( $object->Create() ) + { + $this->Application->StoreVar('visit_id', $object->GetID() ); + $this->Application->SetVar('visits_id', $object->GetID() ); + } } } ?> \ No newline at end of file Property changes on: trunk/core/units/visits/visits_event_handler.php ___________________________________________________________________ Modified: cvs2svn:cvs-rev ## -1 +1 ## -1.1 \ No newline at end of property +1.2 \ No newline at end of property Index: trunk/core/units/visits/visits_config.php =================================================================== --- trunk/core/units/visits/visits_config.php (revision 2391) +++ trunk/core/units/visits/visits_config.php (revision 2392) @@ -1,85 +1,83 @@ <?php $config = Array( 'Prefix' => 'visits', 'ItemClass' => Array('class'=>'kDBItem','file'=>'','build_event'=>'OnItemBuild'), 'ListClass' => Array('class'=>'kDBList','file'=>'','build_event'=>'OnListBuild'), 'EventHandlerClass' => Array('class'=>'VisitsEventHandler','file'=>'visits_event_handler.php','build_event'=>'OnBuild'), 'TagProcessorClass' => Array('class'=>'VisitsTagProcessor','file'=>'visits_tag_processor.php','build_event'=>'OnBuild'), 'AutoLoad' => true, 'QueryString' => Array( 1 => 'id', 2 => 'page', 3 => 'event', 4 => 'mode', ), 'IDField' => 'VisitId', 'TableName' => TABLE_PREFIX.'Visits', 'TitlePresets' => Array( 'default' => Array( ), 'visits_list' => Array( 'prefixes' => Array('visits_List'), 'format' => "!la_title_Visits! (#visits_recordcount#)", ), ), 'CalculatedFields' => Array( '' => Array ( 'UserName' => 'IF( ISNULL(u.Login), IF (%1$s.PortalUserId = -1, \'root\', IF (%1$s.PortalUserId = -2, \'Guest\', \'n/a\')), u.Login)', 'AffiliateUser' => 'IF( LENGTH(au.Login),au.Login,\'!la_None!\')', - 'AffiliatePortalUserId' => 'af.PortalUserId' + 'AffiliatePortalUserId' => 'af.PortalUserId', ), ), 'ListSQLs' => Array( ''=>' SELECT %1$s.* %2$s FROM %1$s LEFT JOIN '.TABLE_PREFIX.'PortalUser u ON %1$s.PortalUserId = u.PortalUserId LEFT JOIN '.TABLE_PREFIX.'Affiliates af ON %1$s.AffiliateId = af.AffiliateId - LEFT JOIN '.TABLE_PREFIX.'PortalUser au ON af.PortalUserId = au.PortalUserId - '), + LEFT JOIN '.TABLE_PREFIX.'PortalUser au ON af.PortalUserId = au.PortalUserId'), 'ItemSQLs' => Array( ''=>' SELECT %1$s.* %2$s FROM %1$s LEFT JOIN '.TABLE_PREFIX.'PortalUser u ON %1$s.PortalUserId = u.PortalUserId LEFT JOIN '.TABLE_PREFIX.'Affiliates af ON %1$s.AffiliateId = af.AffiliateId - LEFT JOIN '.TABLE_PREFIX.'PortalUser au ON af.PortalUserId = au.PortalUserId - '), + LEFT JOIN '.TABLE_PREFIX.'PortalUser au ON af.PortalUserId = au.PortalUserId'), 'ListSortings' => Array( '' => Array( 'Sorting' => Array('VisitDate' => 'asc'), ) ), 'Fields' => Array( 'VisitId' => Array(), 'VisitDate' => Array('type' => 'int', 'formatter'=>'kDateFormatter', 'not_null' => '1','default' => '0'), 'Referer' => Array('type' => 'string','not_null' => '1','default' => ''), 'IPAddress' => Array('type' => 'string','not_null' => '1','default' => ''), 'AffiliateId' => Array('type'=>'int','formatter'=>'kLEFTFormatter','options'=>Array(0=>'lu_none'),'left_sql'=>'SELECT %s FROM '.TABLE_PREFIX.'Affiliates af LEFT JOIN '.TABLE_PREFIX.'PortalUser pu ON pu.PortalUserId = af.PortalUserId WHERE `%s` = \'%s\'','left_key_field'=>'AffiliateId','left_title_field'=>'Login','not_null'=>1,'default'=>0), 'PortalUserId' => Array('type' => 'int','not_null' => '1','default' => -2), 'OrderId' => Array('type' => 'int','not_null' => '1','default' => '0'), ), 'VirtualFields' => Array( - 'UserName' => Array('type'=>'string'), - 'AffiliateUser' => Array('type'=>'string'), - 'AffiliatePortalUserId' => Array('type'=>'int'), + 'UserName' => Array('type'=>'string'), + 'AffiliateUser' => Array('type'=>'string'), + 'AffiliatePortalUserId' => Array('type'=>'int'), ), 'Grids' => Array( 'Default' => Array( 'Icons' => Array('default'=>'icon16_custom.gif'), // icons for each StatusField values, if no matches or no statusfield selected, then "default" icon is used 'Fields' => Array( - 'VisitId' => Array( 'title'=>'la_col_VisitId', 'data_block' => 'grid_checkbox_td_no_icon'), - 'VisitDate' => Array( 'title'=>'la_col_VisitDate' ), + 'VisitDate' => Array( 'title'=>'la_col_VisitDate', 'data_block' => 'grid_checkbox_td' ), 'IPAddress' => Array( 'title'=>'la_col_IPAddress' ), +// 'Referer' => Array( 'title'=>'la_col_Referer' ), 'UserName' => Array('title' => 'la_col_Username', 'data_block' => 'grid_userlink_td', 'user_field' => 'PortalUserId'), 'AffiliateUser' => Array( 'title' => 'la_col_AffiliateUser', 'data_block' => 'grid_userlink_td', 'user_field' => 'AffiliatePortalUserId'), ), ), ), ); ?> \ No newline at end of file Property changes on: trunk/core/units/visits/visits_config.php ___________________________________________________________________ Modified: cvs2svn:cvs-rev ## -1 +1 ## -1.3 \ No newline at end of property +1.4 \ No newline at end of property Index: trunk/core/units/users/users_event_handler.php =================================================================== --- trunk/core/units/users/users_event_handler.php (revision 2391) +++ trunk/core/units/users/users_event_handler.php (revision 2392) @@ -1,734 +1,718 @@ <?php class UsersEventHandler extends InpDBEventHandler { function OnSessionExpire() { if( $this->Application->IsAdmin() ) { $location = $this->Application->BaseURL().ADMIN_DIR.'/index.php?expired=1'; header('Location: '.$location); exit; } else { $t = $this->Application->GetVar('t'); $this->Application->Redirect($t ? $t : 'index', $_GET); } } /** * Checks user data and logs it in if allowed * * @param kEvent $event */ function OnLogin(&$event) { $this->Application->setUnitOption($event->Prefix, 'AutoLoad', false); $object =& $this->Application->recallObject('u'); $password = $this->Application->GetVar('password'); if(!$password) { $object->SetError('ValidateLogin', 'blank_password', 'lu_blank_password'); $event->status = erFAIL; return false; } $email_as_login = $this->Application->ConfigValue('Email_As_Login'); list($login_field, $submit_field) = $email_as_login ? Array('Email', 'email') : Array('Login', 'login'); $login_value = $this->Application->GetVar($submit_field); /*$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(); if (!defined('ADMIN')) array_push($groups, $this->Application->ConfigValue('User_LoggedInGroup') ); $this->Application->StoreVar( 'UserGroups', implode(',', $groups) ); if( $this->Application->CheckPermission('LOGIN',0) ) { $session =& $this->Application->recallObject('Session'); $session->SetField('PortalUserId', $user_id); $this->Application->SetVar('u_id', $user_id); $this->Application->StoreVar('user_id', $user_id); - $this->setVisitUser($user_id); + $this->Application->setVisitField('PortalUserId', $user_id); } else { $object->Load(-2); $object->SetError('ValidateLogin', 'no_permission', 'lu_no_permissions'); $event->status = erFAIL; } $next_template = $this->Application->GetVar('next_template'); if($next_template) $event->redirect = $next_template; } else { $event->redirect = $this->Application->GetVar('pending_disabled_template'); } } else { $object->SetError('ValidateLogin', 'invalid_password', 'lu_invalid_password'); $event->status = erFAIL; } } - /** - * Set's new user for current visit - * - * @param int $user_id - */ - function setVisitUser($user_id) - { - $visit =& $this->Application->recallObject('visits', null, Array('skip_autoload'=>true) ); - $visit->Load( $this->Application->RecallVar('visit_id') ); - if( $visit->isLoaded() ) - { - $visit->SetDBField('PortalUserId', $user_id); - $visit->Update(); - } - } - function OnLogout(&$event) { $session =& $this->Application->recallObject('Session'); $session->SetField('PortalUserId', -2); $this->Application->SetVar('u_id', -2); $this->Application->StoreVar('user_id', -2); $object =& $this->Application->recallObject('u'); $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); } /** * 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( $cs_helper->CountryHasStates( $object->GetDBField('Country') ) ) $object->Fields['State']['required'] = true; if( $this->Application->ConfigValue('Email_As_Login') ) { $object->SetDBField('Login', $object->GetDBField('Email') ); } } /** * 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(); $group_id = $this->Application->ConfigValue('User_NewGroup'); $sql = 'INSERT INTO '.TABLE_PREFIX.'UserGroup(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_id', $object->GetID() ); if($object->GetDBField('Status') == STATUS_ACTIVE) { $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'); } } /** * Creates new user * * @param kEvent $event */ function OnCreate(&$event) { if( !$this->Application->IsAdmin() ) $this->setUserStatus($event); $cs_helper =& $this->Application->recallObject('CountryStatesHelper'); $cs_helper->CheckStateField($event, 'State', 'Country'); parent::OnCreate($event); $object =& $event->getObject(); $this->Application->SetVar('u_id', $object->getID() ); $this->Application->setUnitOption('u', 'AutoLoad', true); switch ($object->GetDBField('Status')){ case 1: $this->Application->EmailEventAdmin('USER.ADD', $object->GetID()); $this->Application->EmailEventUser('USER.ADD', $object->GetID()); break; case 2: $this->Application->EmailEventAdmin('USER.ADD.PENDING', $object->GetID()); $this->Application->EmailEventUser('USER.ADD.PENDING', $object->GetID()); break; } $this->setNextTemplate($event); if( !$this->Application->IsAdmin() && ($event->status == erSUCCESS) && $event->redirect) { $this->autoLoginUser($event); /*$object =& $event->getObject(); if( $object->GetDBField('Status') != STATUS_ACTIVE ) { $next_template = $this->Application->GetVar('next_template'); if($next_template) $event->redirect = $next_template; }*/ } } /** * Set's new user status based on config options * * @param kEvent $event */ function setUserStatus(&$event) { $this->Application->setUnitOption($event->Prefix,'AutoLoad',false); $object =& $event->getObject(); $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; } } /** * 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(); $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'); 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->GetVar('u_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 =& $this->Application->recallObject('u'); $object->ErrorMsgs['send_error'] = $this->Application->Phrase('lu_email_send_error'); $object->FieldErrors['Email']['pseudo'] = 'send_error'; $event->status = erFAIL; } } else { $object =& $this->Application->recallObject('u'); $object->ErrorMsgs['invalid_email'] = $this->Application->Phrase('lu_InvalidEmail'); $object->FieldErrors['Email']['pseudo'] = 'invalid_email'; $event->status = erFAIL; } } /** * Saves address changes and mades no redirect * * @param kEvent $event */ function OnUpdateAddress(&$event) { $this->Application->setUnitOption($event->Prefix,'AutoLoad',false); $object =& $event->getObject(); $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; } 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) ){ $this->Application->setUnitOption($event->Prefix,'AutoLoad',false); $object = &$this->Application->recallObject($this->Prefix.'.subscriber'); $this->Application->StoreVar('SubscriberEmail', $user_email); if( $object->Load(array('Email'=>$user_email)) ){ $group_info = $this->GetGroupInfo($object->GetID()); if($group_info){ $event->redirect = $this->Application->GetVar('unsubscribe_template'); } else { $event->redirect = $this->Application->GetVar('subscribe_template'); } } else { $event->redirect = $this->Application->GetVar('subscribe_template'); $this->Application->StoreVar('SubscriberEmail', $user_email); } } else { $object =& $this->Application->recallObject('u'); $object->ErrorMsgs['invalid_email'] = $this->Application->Phrase('lu_InvalidEmail'); $object->FieldErrors['SubscribeEmail']['pseudo'] = 'invalid_email'; $event->status = erFAIL; } //subscribe_query_ok_template } function OnSubscribeUser(&$event){ $this->Application->setUnitOption($event->Prefix,'AutoLoad',false); $object = &$this->Application->recallObject($this->Prefix.'.subscriber'); $user_email = $this->Application->RecallVar('SubscriberEmail'); if (preg_match("/^[_a-zA-Z0-9-\.]+@[a-zA-Z0-9-\.]+\.[a-z]{2,4}$/", $user_email)){ if($object->Load(array('Email'=>$user_email))){ $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); } } else { // error handling here $event->redirect = $this->Application->GetVar('subscribe_fail_template'); } } 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); } function GetGroupInfo($user_id){ $group_info = $this->Conn->GetRow('SELECT * FROM '.TABLE_PREFIX.'UserGroup WHERE PortalUserId='.$user_id.' AND GroupId='.$this->Application->ConfigValue('User_SubscriberGroup')); return $group_info; } function OnForgotPassword(&$event){ $this->Application->setUnitOption('u', 'AutoLoad', false); $user_object = &$this->Application->recallObject('u.forgot'); $user_current_object = &$this->Application->recallObject('u'); $username = $this->Application->GetVar('username'); $email = $this->Application->GetVar('email'); $found = false; $allow_reset = true; if( strlen($username) ) { if( $user_object->Load(array('Login'=>$username)) ) $found = ($user_object->GetDBField("Login")==$username && $user_object->GetDBField("Status")==1) && strlen($user_object->GetDBField("Password")); } else if( strlen($email) ) { if( $user_object->Load(array('Email'=>$email)) ) $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) ? mktime() > $PwRequestTime + $MinPwResetDelay : 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->ErrorMsgs['forgotpw_nodata'] = $this->Application->Phrase('lu_ferror_forgotpw_nodata'); $user_current_object->FieldErrors['Login']['pseudo'] = 'lu_ferror_forgotpw_nodata'; } else { if($allow_reset) { if( strlen($username) ){ $user_current_object->ErrorMsgs['unknown_username'] = $this->Application->Phrase('lu_ferror_unknown_username'); $user_current_object->FieldErrors['Login']['pseudo']='unknown_username'; } if( strlen($email) ){ $user_current_object->ErrorMsgs['unknown_email'] = $this->Application->Phrase('lu_ferror_unknown_email'); $user_current_object->FieldErrors['Email']['pseudo']='unknown_email'; } } else { $user_current_object->ErrorMsgs['reset_denied'] = $this->Application->Phrase('lu_ferror_reset_denied'); if( strlen($username) ){ $user_current_object->FieldErrors['Login']['pseudo']='reset_denied'; } if( strlen($email) ){ $user_current_object->FieldErrors['Email']['pseudo']='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'); $mod_object =& $this->Application->recallObject('mod.'.'In-Commerce'); $m_cat_id = $mod_object->GetDBField('RootCat'); $event->SetRedirectParam('pass', 'm'); //$event->SetRedirectParam('m_cat_id', $m_cat_id); $this->Application->SetVar('m_cat_id', $m_cat_id); } } function OnResetPasswordConfirmed(&$event){ $passed_key = $this->Application->GetVar('user_key'); $user_object = &$this->Application->recallObject('u.forgot'); $user_current_object = &$this->Application->recallObject('u'); if (strlen(trim($passed_key)) == 0) { $event->redirect_params = array('opener' => 's', 'pass' => 'all'); $event->redirect = false; $user_current_object->ErrorMsgs['code_is_not_valid'] = $this->Application->Phrase('lu_code_is_not_valid'); $user_current_object->FieldErrors['PwResetConfirm']['pseudo'] = '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 > 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", time()); $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->ErrorMsgs['code_expired'] = $this->Application->Phrase('lu_code_expired'); $user_current_object->FieldErrors['PwResetConfirm']['pseudo'] = 'code_expired'; $event->redirect = false; } } else { $user_current_object->ErrorMsgs['code_is_not_valid'] = $this->Application->Phrase('lu_code_is_not_valid'); $user_current_object->FieldErrors['PwResetConfirm']['pseudo'] = '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; } } } function OnCheckExpiredMembership(&$event) { $sql = 'SELECT PortalUserId FROM '.TABLE_PREFIX.'UserGroup WHERE MembershipExpires IS NOT NULL AND MembershipExpires < '.mktime(); $user_ids = $this->Conn->GetCol($sql); if(is_array($user_ids) && count($user_ids) > 0) { 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 < '.mktime(); $this->Conn->Query($sql); $pre_expiration = mktime() + $this->Application->ConfigValue('User_MembershipExpirationReminder') * 3600 * 24; $sql = 'SELECT PortalUserId, GroupId FROM '.TABLE_PREFIX.'UserGroup WHERE MembershipExpires IS NOT NULL AND MembershipExpires < '.$pre_expiration.' AND ExpirationReminderSent = 0'; $res = $this->Conn->Query($sql); if(is_array($res) && count($res) > 0) { $conditions = Array(); foreach($res 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); } } } ?> \ No newline at end of file Property changes on: trunk/core/units/users/users_event_handler.php ___________________________________________________________________ Modified: cvs2svn:cvs-rev ## -1 +1 ## -1.23 \ No newline at end of property +1.24 \ No newline at end of property