Page MenuHomeIn-Portal Phabricator

in-portal
No OneTemporary

File Metadata

Created
Sun, Feb 2, 7:37 PM

in-portal

Index: trunk/kernel/units/users/users_event_handler.php
===================================================================
--- trunk/kernel/units/users/users_event_handler.php (revision 2309)
+++ trunk/kernel/units/users/users_event_handler.php (revision 2310)
@@ -1,705 +1,720 @@
<?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');
+ }
+ }
+
/**
* 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 )
{
$sql = 'SELECT GroupId FROM %s WHERE (PortalUserId = %s) AND ( (MembershipExpires IS NULL) OR ( MembershipExpires >= UNIX_TIMESTAMP() ) )';
$sql = sprintf($sql, TABLE_PREFIX.'UserGroup', $user_id);
$groups = $this->Conn->GetCol($sql);
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);
}
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;
}
}
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->Loaded)
{
$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.19
\ No newline at end of property
+1.20
\ No newline at end of property
Index: trunk/kernel/units/general/inp_login_event_handler.php
===================================================================
--- trunk/kernel/units/general/inp_login_event_handler.php (revision 2309)
+++ trunk/kernel/units/general/inp_login_event_handler.php (nonexistent)
@@ -1,23 +0,0 @@
-<?php
-
- class InpLoginEventHandler extends kEventHandler
- {
- function OnSessionExpire()
- {
- if( $this->Application->IsAdmin() )
- {
- $location = $this->Application->BaseURL().ADMIN_DIR.'/index.php?expired=1';
- header('Location: '.$location);
- exit;
- }
- else
- {
- $this->Application->Redirect('index');
- }
- }
-
-
- }
-
-
-?>
\ No newline at end of file
Property changes on: trunk/kernel/units/general/inp_login_event_handler.php
___________________________________________________________________
Deleted: cvs2svn:cvs-rev
## -1 +0,0 ##
-1.5
\ No newline at end of property
Deleted: svn:executable
## -1 +0,0 ##
-*
\ No newline at end of property
Index: trunk/kernel/units/general/my_application.php
===================================================================
--- trunk/kernel/units/general/my_application.php (revision 2309)
+++ trunk/kernel/units/general/my_application.php (revision 2310)
@@ -1,81 +1,80 @@
<?php
k4_include_once(MODULES_PATH.'/kernel/units/general/inp_db_event_handler.php');
class MyApplication extends kApplication {
function RegisterDefaultClasses()
{
parent::RegisterDefaultClasses();
$this->registerClass('Inp1Parser',MODULES_PATH.'/kernel/units/general/inp1_parser.php','Inp1Parser');
$this->registerClass('InpSession',MODULES_PATH.'/kernel/units/general/inp_ses_storage.php','Session');
$this->registerClass('InpSessionStorage',MODULES_PATH.'/kernel/units/general/inp_ses_storage.php','SessionStorage');
$this->registerClass('kCatDBItem',MODULES_PATH.'/kernel/units/general/cat_dbitem.php');
$this->registerClass('kCatDBList',MODULES_PATH.'/kernel/units/general/cat_dblist.php');
$this->registerClass('kCatDBEventHandler',MODULES_PATH.'/kernel/units/general/cat_event_handler.php');
- $this->registerClass('InpLoginEventHandler',MODULES_PATH.'/kernel/units/general/inp_login_event_handler.php','login_EventHandler');
$this->registerClass('InpDBEventHandler',MODULES_PATH.'/kernel/units/general/inp_db_event_handler.php','kDBEventHandler');
$this->registerClass('InpTempTablesHandler',MODULES_PATH.'/kernel/units/general/inp_temp_handler.php','kTempTablesHandler');
$this->registerClass('InpCustomFieldsHelper',MODULES_PATH.'/kernel/units/general/custom_fields.php','InpCustomFieldsHelper');
$this->registerClass('kCountryStatesHelper',MODULES_PATH.'/kernel/units/general/country_states.php','CountryStatesHelper');
}
/**
* Checks if user is logged in, and creates
* user object if so. User object can be recalled
* later using "u" prefix. Also you may
* get user id by getting "u_id" variable.
*
* @access private
*/
function ValidateLogin()
{
$session =& $this->recallObject('Session');
$user_id = $session->GetField('PortalUserId');
if (!$user_id) $user_id = -2;
$this->SetVar('u_id', $user_id);
$this->StoreVar('user_id', $user_id);
}
function RunScheduledEvents()
{
$events = Array('ls:OnCheckExpiredPaidListings', 'u:OnCheckExpiredMembership');
$run_interval = 60 * 30; // in seconds
if(rand(0, 100) < 90)
{
return;
}
$sql = 'SELECT Data FROM '.TABLE_PREFIX.'Cache WHERE VarName = "LastMaintainRun"';
$last_maintain = $this->DB->GetOne($sql);
if($last_maintain && $last_maintain > mktime() - $run_interval)
{
return;
}
elseif($last_maintain)
{
$sql = 'UPDATE '.TABLE_PREFIX.'Cache SET Data = "'.mktime().'"
WHERE VarName = "LastMaintainRun"';
}
else
{
$sql = 'INSERT INTO '.TABLE_PREFIX.'Cache (VarName, Data, Cached)
VALUES ("LastMaintainRun", "'.mktime().'", "'.mktime().'")';
}
$this->DB->Query($sql);
foreach($events as $scheduled_event)
{
$event = new kEvent($scheduled_event);
$this->HandleEvent($event);
unset($event);
}
}
}
?>
\ No newline at end of file
Property changes on: trunk/kernel/units/general/my_application.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.11
\ No newline at end of property
+1.12
\ No newline at end of property
Index: trunk/admin/index.php
===================================================================
--- trunk/admin/index.php (revision 2309)
+++ trunk/admin/index.php (revision 2310)
@@ -1,154 +1,156 @@
<?php
##############################################################
##In-portal ##
##############################################################
## In-portal ##
## Intechnic Corporation ##
## All Rights Reserved, 1998-2002 ##
## ##
## No portion of this code may be copied, reproduced or ##
## otherwise redistributed without proper written ##
## consent of Intechnic Corporation. Violation will ##
## result in revocation of the license and support ##
## privileges along maximum prosecution allowed by law. ##
##############################################################
$pathtoroot = "";
if(!strlen($pathtoroot))
{
$path=dirname(realpath(__FILE__));
if(strlen($path))
{
/* determine the OS type for path parsing */
$pos = strpos($path,":");
if ($pos === false)
{
$gOS_TYPE="unix";
$pathchar = "/";
}
else
{
$gOS_TYPE="win";
$pathchar="\\";
}
$p = $path.$pathchar;
/*Start looking for the root flag file */
while(!strlen($pathtoroot) && strlen($p))
{
$sub = substr($p,strlen($pathchar)*-1);
if($sub==$pathchar)
{
$filename = $p."root.flg";
}
else
$filename = $p.$pathchar."root.flg";
if(file_exists($filename))
{
$pathtoroot = $p;
}
else
{
$parent = realpath($p.$pathchar."..".$pathchar);
if($parent!=$p)
{
$p = $parent;
}
else
$p = "";
}
}
if(!strlen($pathtoroot))
$pathtoroot = ".".$pathchar;
}
else
{
$pathtoroot = ".".$pathchar;
}
}
if (!file_exists($pathtoroot."/config.php")) {
echo "In-Portal is probably not installed, or configuration file is missing.<br>";
echo "Please use the installation script to fix the problem.<br><br>";
echo "<a href='install.php'>Go to installation script</a><br><br>";
flush();
die();
}
$sub = substr($pathtoroot,strlen($pathchar)*-1);
if($sub!=$pathchar)
{
$pathtoroot = $pathtoroot.$pathchar;
}
//echo "<PRE>"; print_r($_POST); echo "</PRE>";
require_once($pathtoroot."/kernel/startup.php");
$rootURL="http://".ThisDomain().$objConfig->Get("Site_Path");
$admin = substr($path,strlen($pathtoroot));
$objConfig->Set("AdminDirectory",$admin,0,TRUE);
$objConfig->Save();
//echo "Setting admin to $admin <br>\n";
$localURL=$rootURL."kernel/";
$adminURL = $rootURL.$admin;
$imagesURL = $adminURL."/images";
$browseURL = $adminURL."/browse";
$cssURL = $adminURL."/include";
// !admin_login() - admin, but not logged in
if (!admin_login() || GetVar('logout') || GetVar('expired') )
{
- if(!headers_sent())
- setcookie("sid"," ",time()-3600);
+ if( !headers_sent() )
+ {
+ setcookie('sid"','', time()-3600, $objConfig->Get("Site_Path").'/'.$admin );
+ }
$objSession->Logout();
require_once($pathtoroot.$admin."/login.php");
}
$envar = "env=" . BuildEnv();
require_once ($pathtoroot.$admin."/include/elements.php");
require_once ($pathtoroot."kernel/admin/include/navmenu.php");
$pathtolocal = $pathtoroot;
$charset = GetRegionalOption('Charset');
?>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=<?php echo $charset; ?>">
<meta name="generator" content="kwrite">
<link rel="stylesheet" type="text/css" href="include/style.css">
<title>In-portal Administration</title>
</head>
<script type="text/javascript">
window.name = 'main_frame';
</script>
<script language="JavaScript1.2">
lala = navigator.appVersion.substring(0,1);
if (navigator.appName == "Netscape") {
if (lala != "5") {
document.write("<frameset rows='96,*' framespacing='0' scrolling='no' frameborder='0'>");
} else {
document.write("<frameset rows='95,*' framespacing='0' scrolling='no' frameborder='0'>");
}
} else {
document.write("<frameset rows='94,*' framespacing='0' scrolling='no' frameborder='0'>");
}
</script>
<!--<frameset rows="92,*" border="0">-->
<frame src="head.php?<?php echo $envar; ?>" name="head" scrolling="no" noresize>
<frameset cols="200,*" border="0">
<frame src="tree/tree.php?<?php echo $envar; ?>" name="menu" target="_main" noresize scrolling="auto" marginwidth="0" marginheight="0">
<frame src="subitems.php?<?php echo $envar."&section=in-portal:root"; ?>" name="main" marginwidth="0" marginheight="0" frameborder="NO" noresize scrolling="auto">
</frameset>
</frameset>
<noframes>
<body bgcolor="#ffffff">
<p></p>
</body>
</noframes>
</html>
\ No newline at end of file
Property changes on: trunk/admin/index.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.7
\ No newline at end of property
+1.8
\ No newline at end of property
Index: trunk/core/kernel/session/login_event_handler.php
===================================================================
--- trunk/core/kernel/session/login_event_handler.php (revision 2309)
+++ trunk/core/kernel/session/login_event_handler.php (nonexistent)
@@ -1,12 +0,0 @@
-<?php
-
- class LoginEventHandler extends kEventHandler
- {
- function OnSessionExpire()
- {
- $this->Application->Redirect('logout');
- }
- }
-
-
-?>
\ No newline at end of file
Property changes on: trunk/core/kernel/session/login_event_handler.php
___________________________________________________________________
Deleted: cvs2svn:cvs-rev
## -1 +0,0 ##
-1.4
\ No newline at end of property
Deleted: svn:executable
## -1 +0,0 ##
-*
\ No newline at end of property
Index: trunk/core/kernel/session/session.php
===================================================================
--- trunk/core/kernel/session/session.php (revision 2309)
+++ trunk/core/kernel/session/session.php (revision 2310)
@@ -1,639 +1,639 @@
<?php
/*
The session works the following way:
1. When a visitor loads a page from the site the script checks if cookies_on varibale has been passed to it as a cookie.
2. If it has been passed, the script tries to get Session ID (SID) from the request:
3. Depending on session mode the script is getting SID differently.
The following modes are available:
smAUTO - Automatic mode: if cookies are on at the client side, the script relays only on cookies and
ignore all other methods of passing SID.
If cookies are off at the client side, the script relays on SID passed through query string
and referal passed by the client. THIS METHOD IS NOT 100% SECURE, as long as attacker may
get SID and substitude referal to gain access to user' session. One of the faults of this method
is that the session is only created when the visitor clicks the first link on the site, so
there is NO session at the first load of the page. (Actually there is a session, but it gets lost
after the first click because we do not use SID in query string while we are not sure if we need it)
smCOOKIES_ONLY - Cookies only: in this mode the script relays solely on cookies passed from the browser
and ignores all other methods. In this mode there is no way to use sessions for clients
without cookies support or cookies support disabled. The cookies are stored with the
full domain name and path to base-directory of script installation.
smGET_ONLY - GET only: the script will not set any cookies and will use only SID passed in
query string using GET, it will also check referal. The script will set SID at the
first load of the page
smCOOKIES_AND_GET - Combined mode: the script will use both cookies and GET right from the start. If client has
cookies enabled, the script will check SID stored in cookie and passed in query string, and will
use this SID only if both cookie and query string matches. However if cookies are disabled on the
client side, the script will work the same way as in GET_ONLY mode.
4. After the script has the SID it tries to load it from the Storage (default is database)
5. If such SID is found in the database, the script checks its expiration time. If session is not expired, it updates
its expiration, and resend the cookie (if applicable to session mode)
6. Then the script loads all the data (session variables) pertaining to the SID.
Usage:
$session =& new Session(smAUTO); //smAUTO is default, you could just leave the brackets empty, or provide another mode
$session->SetCookieDomain('my.domain.com');
$session->SetCookiePath('/myscript');
$session->SetCookieName('my_sid_cookie');
$session->SetGETName('sid');
$session->InitSession();
...
//link output:
echo "<a href='index.php?'". ( $session->NeedQueryString() ? 'sid='.$session->SID : '' ) .">My Link</a>";
*/
//Implements session storage in the database
class SessionStorage extends kDBBase {
var $Expiration;
var $SessionTimeout=0;
var $OriginalData=Array();
var $TimestampField;
var $SessionDataTable;
var $DataValueField;
var $DataVarField;
function Init($prefix,$special)
{
parent::Init($prefix,$special);
$this->setTableName('sessions');
$this->setIDField('sid');
$this->TimestampField = 'expire';
$this->SessionDataTable = 'SessionData';
$this->DataValueField = 'value';
$this->DataVarField = 'var';
}
function setSessionTimeout($new_timeout)
{
$this->SessionTimeout = $new_timeout;
}
function StoreSession(&$session)
{
$query = ' INSERT INTO '.$this->TableName.' ('.$this->IDField.', '.$this->TimestampField.')'.
' VALUES ('.$this->Conn->qstr($session->SID).', '.$session->Expiration.')';
$this->Conn->Query($query);
}
function DeleteSession(&$session)
{
$query = ' DELETE FROM '.$this->TableName.' WHERE '.$this->IDField.' = '.$this->Conn->qstr($session->SID);
$this->Conn->Query($query);
$query = ' DELETE FROM '.$this->SessionDataTable.' WHERE '.$this->IDField.' = '.$this->Conn->qstr($session->SID);
$this->Conn->Query($query);
$this->OriginalData = Array();
}
function UpdateSession(&$session, $timeout=0)
{
$query = ' UPDATE '.$this->TableName.' SET '.$this->TimestampField.' = '.$session->Expiration.' WHERE '.$this->IDField.' = '.$this->Conn->qstr($session->SID);
$this->Conn->Query($query);
}
function LocateSession($sid)
{
$query = ' SELECT '.$this->TimestampField.' FROM '.$this->TableName.' WHERE '.$this->IDField.' = '.$this->Conn->qstr($sid);
$result = $this->Conn->GetOne($query);
if($result===false) return false;
$this->Expiration = $result;
return true;
}
function GetExpiration()
{
return $this->Expiration;
}
function LoadData(&$session)
{
$query = 'SELECT '.$this->DataValueField.','.$this->DataVarField.' FROM '.$this->SessionDataTable.' WHERE '.$this->IDField.' = '.$this->Conn->qstr($session->SID);
$this->OriginalData = $this->Conn->GetCol($query, $this->DataVarField);
return $this->OriginalData;
}
/**
* Enter description here...
*
* @param Session $session
* @param string $var_name
*/
function GetField(&$session, $var_name)
{
return $this->Conn->GetOne('SELECT '.$var_name.' FROM '.$this->TableName.' WHERE `'.$this->IDField.'` = '.$this->Conn->qstr($session->GetID()) );
}
function SetField(&$session, $var_name, $value)
{
return $this->Conn->Query('UPDATE '.$this->TableName.' SET '.$var_name.' = '.$this->Conn->qstr($value).' WHERE '.$this->IDField.' = '.$this->Conn->qstr($session->GetID()) );
}
function SaveData(&$session)
{
if(!$session->SID) return false; // can't save without sid
$ses_data = $session->Data->GetParams();
$replace = '';
foreach ($ses_data as $key => $value)
{
if ( isset($this->OriginalData[$key]) && $this->OriginalData[$key] == $value)
{
continue; //skip unchanged session data
}
else
{
$replace .= sprintf("(%s, %s, %s),",
$this->Conn->qstr($session->SID),
$this->Conn->qstr($key),
$this->Conn->qstr($value));
}
}
$replace = rtrim($replace, ',');
if ($replace != '') {
$query = ' REPLACE INTO '.$this->SessionDataTable. ' ('.$this->IDField.', '.$this->DataVarField.', '.$this->DataValueField.') VALUES '.$replace;
$this->Conn->Query($query);
}
}
function RemoveFromData(&$session, $var)
{
$query = 'DELETE FROM '.$this->SessionDataTable.' WHERE '.$this->IDField.' = '.$this->Conn->qstr($session->SID).
' AND '.$this->DataVarField.' = '.$this->Conn->qstr($var);
$this->Conn->Query($query);
unset($this->OriginalData[$var]);
}
function GetExpiredSIDs()
{
$query = ' SELECT '.$this->IDField.' FROM '.$this->TableName.' WHERE '.$this->TimestampField.' > '.time();
return $this->Conn->GetCol($query);
}
function DeleteExpired()
{
$expired_sids = $this->GetExpiredSIDs();
if($expired_sids)
{
$where_clause=' WHERE '.$this->IDField.' IN ("'.implode('","',$expired_sids).'")';
$sql = 'DELETE FROM '.$this->SessionDataTable.$where_clause;
$this->Conn->Query($sql);
$sql = 'DELETE FROM '.$this->TableName.$where_clause;
$this->Conn->Query($sql);
}
return $expired_sids;
}
}
define('smAUTO', 1);
define('smCOOKIES_ONLY', 2);
define('smGET_ONLY', 3);
define('smCOOKIES_AND_GET', 4);
class Session extends kBase {
var $Checkers;
var $Mode;
var $GETName = 'sid';
var $CookiesEnabled = true;
var $CookieName = 'sid';
var $CookieDomain;
var $CookiePath;
var $CookieSecure = 0;
var $SessionTimeout = 3600;
var $Expiration;
var $SID;
var $Storage;
var $CachedNeedQueryString = null;
var $Data;
function Session($mode=smAUTO)
{
parent::kBase();
$this->SetMode($mode);
}
function SetMode($mode)
{
$this->Mode = $mode;
}
function SetCookiePath($path)
{
$this->CookiePath = $path;
}
function SetCookieDomain($domain)
{
$this->CookieDomain = $domain;
}
function SetGETName($get_name)
{
$this->GETName = $get_name;
}
function SetCookieName($cookie_name)
{
$this->CookieName = $cookie_name;
}
function InitStorage()
{
$this->Storage =& $this->Application->recallObject('SessionStorage');
$this->Storage->setSessionTimeout($this->SessionTimeout);
}
function Init($prefix,$special)
{
parent::Init($prefix,$special);
$this->CheckIfCookiesAreOn();
$this->Checkers = Array();
$this->InitStorage();
$this->Data =& new Params();
$tmp_sid = $this->GetPassedSIDValue();
if( !(defined('IS_INSTALL') && IS_INSTALL) )
{
$expired_sids = $this->DeleteExpired();
if( ( $expired_sids && in_array($tmp_sid,$expired_sids) ) || ( $tmp_sid && !$this->Check() ) )
{
$this->SetSession();
- $this->Application->HandleEvent($event, 'login:OnSessionExpire');
+ $this->Application->HandleEvent($event, 'u:OnSessionExpire');
}
}
if ($this->Check()) {
$this->SID = $this->GetPassedSIDValue();
$this->Refresh();
$this->LoadData();
}
else {
$this->SetSession();
}
}
function CheckReferer()
{
$path = preg_replace("/admin$/", '', $this->CookiePath); // removing /admin for compatability with in-portal (in-link/admin/add_link.php)
$reg = '#^'.preg_quote(PROTOCOL.$this->CookieDomain.$path).'#';
return preg_match($reg, $_SERVER['HTTP_REFERER']) || (defined('IS_POPUP') && IS_POPUP);
}
function CheckIfCookiesAreOn()
{
if ($this->Mode == smGET_ONLY || (defined('INPORTAL_ENV')&&INPORTAL_ENV && defined('ADMIN')&&ADMIN && !$this->Application->GetVar('front')) )
{
//we don't need to bother checking if we would not use it
$this->CookiesEnabled = false;
return;
}
$http_query =& $this->Application->recallObject('HTTPQuery');
$cookies_on = isset($http_query->Cookie['cookies_on']); // not good here
if (!$cookies_on) {
//If referer is our server, but we don't have our cookies_on, it's definetly off
if ($this->CheckReferer() && !$this->Application->GetVar('admin')) {
$this->CookiesEnabled = false;
}
else {
//Otherwise we still suppose cookies are on, because may be it's the first time user visits the site
//So we send cookies on to get it next time (when referal will tell us if they are realy off
setcookie(
'cookies_on',
1,
time()+31104000, //one year should be enough
$this->CookiePath,
$this->CookieDomain,
$this->CookieSecure
);
}
}
else
$this->CookiesEnabled = true;
return $this->CookiesEnabled;
}
function Check()
{
// we should check referer if cookies are disabled, and in combined mode
// auto mode would detect cookies, get only mode would turn it off - so we would get here
// and we don't care about referal in cookies only mode
if ( $this->Mode != smCOOKIES_ONLY && (!$this->CookiesEnabled || $this->Mode == smCOOKIES_AND_GET) ) {
if (!$this->CheckReferer())
return false;
}
$sid = $this->GetPassedSIDValue();
if (empty($sid)) return false;
//try to load session by sid, if everything is fine
$result = $this->LoadSession($sid);
return $result;
}
function LoadSession($sid)
{
if( $this->Storage->LocateSession($sid) ) {
//if we have session with such SID - get its expiration
$this->Expiration = $this->Storage->GetExpiration();
//If session has expired
if ($this->Expiration < time()) return false;
//Otherwise it's ok
return true;
}
else //fake or deleted due to expiration SID
return false;
}
function GetPassedSIDValue($use_cache = 1)
{
if (!empty($this->CachedSID) && $use_cache) return $this->CachedSID;
$http_query =& $this->Application->recallObject('HTTPQuery');
$get_sid = getArrayValue($http_query->Get, $this->GETName);
if ($this->Application->GetVar('admin') == 1 && $get_sid) {
$sid = $get_sid;
}
else {
switch ($this->Mode) {
case smAUTO:
//Cookies has the priority - we ignore everything else
$sid=$this->CookiesEnabled ? getArrayValue($http_query->Cookie,$this->CookieName) : $get_sid;
break;
case smCOOKIES_ONLY:
$sid = $http_query->Cookie[$this->CookieName];
break;
case smGET_ONLY:
$sid = $get_sid;
break;
case smCOOKIES_AND_GET:
$cookie_sid = $http_query->Cookie[$this->CookieName];
//both sids should match if cookies are enabled
if (!$this->CookiesEnabled || ($cookie_sid == $get_sid))
{
$sid = $get_sid; //we use get here just in case cookies are disabled
}
else
{
$sid = '';
}
break;
}
}
if ($this->Application->GetVar('front')) {
$this->CookiesEnabled = false;
}
$this->CachedSID = $sid;
return $this->CachedSID;
}
/**
* Returns session id
*
* @return int
* @access public
*/
function GetID()
{
return $this->SID;
}
/**
* Generates new session id
*
* @return int
* @access private
*/
function GenerateSID()
{
list($usec, $sec) = explode(" ",microtime());
$sid_part_1 = substr($usec, 4, 4);
$sid_part_2 = mt_rand(1,9);
$sid_part_3 = substr($sec, 6, 4);
$digit_one = substr($sid_part_1, 0, 1);
if ($digit_one == 0) {
$digit_one = mt_rand(1,9);
$sid_part_1 = ereg_replace("^0","",$sid_part_1);
$sid_part_1=$digit_one.$sid_part_1;
}
$this->setSID($sid_part_1.$sid_part_2.$sid_part_3);
return $this->SID;
}
/**
* Set's new session id
*
* @param int $new_sid
* @access private
*/
function setSID($new_sid)
{
$this->SID=$new_sid;
$this->Application->SetVar($this->GETName,$new_sid);
}
function SetSession()
{
$this->GenerateSID();
$this->Expiration = time() + $this->SessionTimeout;
switch ($this->Mode) {
case smAUTO:
if ($this->CookiesEnabled) {
$this->SetSessionCookie();
}
break;
case smGET_ONLY:
break;
case smCOOKIES_ONLY:
case smCOOKIES_AND_GET:
$this->SetSessionCookie();
break;
}
$this->Storage->StoreSession($this);
}
function SetSessionCookie()
{
setcookie(
$this->CookieName,
$this->SID,
$this->Expiration,
$this->CookiePath,
$this->CookieDomain,
$this->CookieSecure
);
}
/**
* Refreshes session expiration time
*
* @access private
*/
function Refresh()
{
if ($this->CookiesEnabled) $this->SetSessionCookie(); //we need to refresh the cookie
$this->Storage->UpdateSession($this);
}
function Destroy()
{
$this->Storage->DeleteSession($this);
$this->Data =& new Params();
$this->SID = '';
if ($this->CookiesEnabled) $this->SetSessionCookie(); //will remove the cookie due to value (sid) is empty
$this->SetSession(); //will create a new session
}
function NeedQueryString($use_cache = 1)
{
if ($this->CachedNeedQueryString != null && $use_cache) return $this->CachedNeedQueryString;
switch ($this->Mode) {
case smAUTO:
if ($this->CookiesEnabled) {
$res = 0;
}
else {
$res = 1;
}
break;
case smCOOKIES_ONLY:
break;
case smGET_ONLY:
case smCOOKIES_AND_GET:
$res = 1;
break;
}
$this->CachedNeedQueryString = $res;
return $res;
}
function LoadData()
{
$this->Data->AddParams($this->Storage->LoadData($this));
}
function PrintSession($comment='')
{
if( $this->Application->isDebugMode() && dbg_ConstOn('DBG_SHOW_SESSIONDATA') )
{
global $debugger;
$debugger->appendHTML('SessionStorage ('.$comment.'):');
$session_data = $this->Data->GetParams();
ksort($session_data);
foreach($session_data as $session_key => $session_value)
{
if( IsSerialized($session_value) )
{
$session_data[$session_key] = unserialize($session_value);
}
}
$debugger->dumpVars($session_data);
// to insert after HTTPQuery if it's visible
$new_row = dbg_ConstOn('DBG_SHOW_HTTPQUERY') ? 4 : 2;
//$debugger->moveAfterRow($new_row,2);
}
}
function SaveData()
{
if( $this->Application->GetVar('t') != 'help' )
{
$this->StoreVar('last_template', basename($_SERVER['PHP_SELF']).'|'.substr($this->Application->BuildEnv($this->Application->GetVar('t'), Array('m_opener' => 'u'), 'all', true), strlen(ENV_VAR_NAME)+1 ));
}
$this->StoreVar('last_env', substr($this->Application->BuildEnv($this->Application->GetVar('t'),Array('pass'=>'all')), strlen(ENV_VAR_NAME)+1 ));
$this->PrintSession('after save');
$this->Storage->SaveData($this);
}
function StoreVar($name, $value)
{
$this->Data->Set($name, $value);
}
function StoreVarDefault($name, $value)
{
$tmp = $this->RecallVar($name);
if($tmp === false || $tmp == '')
{
$this->StoreVar($name, $value);
}
}
function RecallVar($name,$default=false)
{
$ret = $this->Data->Get($name);
return ($ret===false) ? $default : $ret;
}
function RemoveVar($name)
{
$this->Storage->RemoveFromData($this, $name);
$this->Data->Remove($name);
}
function GetField($var_name)
{
return $this->Storage->GetField($this, $var_name);
}
function SetField($var_name, $value)
{
$this->Storage->SetField($this, $var_name, $value);
}
/**
* Deletes expired sessions
*
* @return Array expired sids if any
* @access private
*/
function DeleteExpired()
{
return $this->Storage->DeleteExpired();
}
}
?>
\ No newline at end of file
Property changes on: trunk/core/kernel/session/session.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.10
\ No newline at end of property
+1.11
\ No newline at end of property
Index: trunk/core/kernel/utility/http_query.php
===================================================================
--- trunk/core/kernel/utility/http_query.php (revision 2309)
+++ trunk/core/kernel/utility/http_query.php (revision 2310)
@@ -1,478 +1,485 @@
<?php
class HTTPQuery extends Params {
/**
* $_POST vars
*
* @var Array
* @access private
*/
var $Post;
/**
* $_GET vars
*
* @var Array
* @access private
*/
var $Get;
/**
* $_COOKIE vars
*
* @var Array
* @access private
*/
var $Cookie;
/**
* $_SERVER vars
*
* @var Array
* @access private
*/
var $Server;
/**
* $_ENV vars
*
* @var Array
* @access private
*/
var $Env;
/**
* Order in what write
* all vars together in
* the same array
*
* @var string
*/
var $Order;
/**
* Uploaded files info
*
* @var Array
* @access private
*/
var $Files;
var $specialsToRemove = Array();
var $Admin = false;
/**
* Loads info from $_POST, $_GET and
* related arrays into common place
*
* @param string $order
* @return HTTPQuery
* @access public
*/
function HTTPQuery($order='CGPF')
{
parent::Params();
$this->Order = $order;
$this->Admin = defined('ADMIN') && ADMIN;
$this->AddAllVars();
$this->specialsToRemove = $this->Get('remove_specials');
if($this->specialsToRemove)
{
$this->_Params = $this->removeSpecials($this->_Params);
}
ini_set('magic_quotes_gpc', 0);
}
function removeSpecials($array)
{
$ret = Array();
$removed = false;
foreach($this->specialsToRemove as $prefix_special => $flag)
{
if($flag)
{
$removed = true;
list($prefix,$special) = explode('.',$prefix_special, 2);
foreach ($array as $key => $val) {
$new_key = preg_match("/^".$prefix."[._]{1}".$special."(.*)/", $key, $regs) ? $prefix.$regs[1] : $key;
$ret[$new_key] = is_array($val) ? $this->removeSpecials($val) : $val;
}
}
}
return $removed ? $ret : $array;
}
/**
* All all requested vars to
* common storage place
*
* @access private
*/
function AddAllVars()
{
for ($i=0; $i < strlen($this->Order); $i++)
{
$current = $this->Order[$i];
switch ($current) {
case 'G':
$this->Get =$this->AddVars($_GET);
$this->processQueryString();
break;
case 'P':
$this->Post = $this->AddVars($_POST);
$this->convertPostEvents();
break;
case 'C':
$this->Cookie = $this->AddVars($_COOKIE);
break;
case 'E';
$this->Env = $this->AddVars($_ENV);
break;
case 'S';
$this->Server = $this->AddVars($_SERVER);
break;
case 'F';
$this->convertFiles();
$this->Files = $this->MergeVars($_FILES, false); //do not strip slashes!
break;
}
}
}
function convertFiles()
{
if (!$_FILES)
{
return false;
}
$file_keys = Array('error','name','size','tmp_name','type');
foreach($_FILES as $file_name => $file_info)
{
if( is_array($file_info['error']) )
{
$tmp[$file_name] = $this->getArrayLevel( $file_info['error'], $file_name );
}
else
{
$normal_files[$file_name] = $file_info;
}
}
$files = $_FILES;
$_FILES = Array();
foreach($tmp as $prefix => $prefix_files)
{
$anchor =& $_FILES;
foreach($prefix_files['keys'] as $key)
{
$anchor =& $anchor[$key];
}
foreach($prefix_files['value'] as $field_name)
{
unset($inner_anchor);
unset($copy);
$work_copy = $prefix_files['keys'];
foreach($file_keys as $file_key)
{
$inner_anchor =& $files[$prefix][$file_key];
if (isset($copy))
{
$work_copy = $copy;
}
else
{
$copy = $work_copy;
}
array_shift($work_copy);
foreach($work_copy as $prefix_file_key)
{
$inner_anchor =& $inner_anchor[$prefix_file_key];
}
$anchor[$field_name][$file_key] = $inner_anchor[$field_name];
}
}
}
// keys: img_temp, 0, values: LocalPath, ThumbPath
}
function getArrayLevel(&$level, $prefix='')
{
$ret['keys'] = $prefix ? Array($prefix) : Array();
$ret['value'] = Array();
foreach($level as $level_key => $level_value)
{
if( is_array($level_value) )
{
$ret['keys'][] = $level_key;
$tmp = $this->getArrayLevel($level_value);
$ret['keys'] = array_merge($ret['keys'], $tmp['keys']);
$ret['value'] = array_merge($ret['value'], $tmp['value']);
}
else
{
$ret['value'][] = $level_key;
}
}
return $ret;
}
/**
* Owerwrites GET events with POST events in case if they are set and not empty
*
*/
function convertPostEvents()
{
$events = $this->Get('events');
if( is_array($events) )
{
foreach ($events as $prefix_special => $event_name)
{
if($event_name) $this->Set($prefix_special.'_event', $event_name);
}
}
}
/**
* Process QueryString only, create
* events, ids, based on config
* set template name and sid in
* desired application variables.
*
* @access private
*/
function processQueryString()
{
// env=SID:TEMPLATE:m-1-1-1-1:l0-0-0:n-0-0-0:bb-0-0-1-1-1-0
$env_var =& $this->Get(ENV_VAR_NAME);
if($env_var)
{
$sid = $this->Get('sid');
- if (defined('MOD_REWRITE') && MOD_REWRITE && $sid) $env_var = rtrim($sid.$env_var, '/');
+ if (defined('MOD_REWRITE') && MOD_REWRITE && $sid && !$this->Get('admin') )
+ {
+ //$env_var = rtrim($sid.$env_var, '/');
+ $split_by = defined('INPORTAL_ENV') ? '-' : ':';
+ $env_var = explode($split_by, $env_var, 2);
+ $env_var[0] = $sid;
+ $env_var = rtrim( implode($split_by, $env_var), '/');
+ }
$env_var = str_replace('\:','_&+$$+&_',$env_var); // replace escaped "=" with spec-chars :)
$parts=explode(':',$env_var);
if (defined('MOD_REWRITE') && MOD_REWRITE) $env_var = str_replace('/', ':', $env_var);
if (defined('INPORTAL_ENV')) {
$sub_parts = array_shift($parts);
list($sid, $t) = explode('-', $sub_parts, 2);
// Save Session ID
if($sid) {
$this->Set('sid',$sid);
$this->Get['sid'] = $sid;
}
// Save Template Name
$t=$this->getTemplateName( trim($t, '/') );
if(!$t) $t='index';
$this->Set('t', trim($t, '/') );
}
else {
// Save Session ID
$sid=array_shift($parts);
if($sid) $this->Set('sid',$sid);
// Save Template Name
$t=$this->getTemplateName( array_shift($parts) );
if(!$t) $t='index';
$this->Set('t', trim($t, '/') );
}
if($parts)
{
$query_maps=Array();
$event_manger =& $this->Application->recallObject('EventManager');
$passed = Array();
foreach($parts as $mixed_part)
{
//In-portal old style env conversion - adds '-' between prefix and first var
$mixed_part = str_replace('_&+$$+&_',':',$mixed_part);
$mixed_part = preg_replace("/^([a-zA-Z]+)([0-9]+)-(.*)/", "$1-$2-$3", $mixed_part);
$escaped_part = str_replace('\-', '_&+$$+&_', $mixed_part);
$escaped_part = explode('-', $escaped_part);
$mixed_part = array();
foreach ($escaped_part as $escaped_val) {
$mixed_part[] = str_replace('_&+$$+&_', '-', $escaped_val);
}
$prefix_special=array_shift($mixed_part); // l.pick, l
list($prefix)=explode('.',$prefix_special);
$query_maps[$prefix_special]=$this->Application->getUnitOption($prefix,'QueryString');
// if config is not defined for prefix in QueryString, then don't process it
if( $query_maps[$prefix_special] )
{
array_push($passed, $prefix);
foreach($query_maps[$prefix_special] as $index => $var_name)
{
// l_id, l_page, l_bla-bla-bla
$val = $mixed_part[$index-1];
if ($val == '') $val = false;
$this->Set($prefix_special.'_'.$var_name, $val);
}
}
else
{
unset($query_maps[$prefix_special]);
}
}
$this->Set('passed', implode(',', $passed));
$event_manger->setQueryMaps($query_maps);
}
}
else
{
$t=$this->getTemplateName('index');
$this->Set('t',$t);
}
}
/**
* Decides what template name to
* use from $_GET or from $_POST
*
* @param string $querystring_template
* @return string
* @access private
*/
function getTemplateName($querystring_template)
{
$t_from_post = $this->Get('t');
$t= $t_from_post ? $t_from_post : $querystring_template;
if ( is_numeric($t) ) {
$t = $this->Application->DB->GetOne('SELECT CONCAT(FilePath, \'/\', FileName) FROM '.TABLE_PREFIX.'ThemeFiles
WHERE FileId = '.$t);
}
$t = preg_replace("/\.tpl$/", '', $t);
return $t;
}
/**
* Saves variables from array specified
* into common variable storage place
*
* @param Array $array
* @return Array
* @access private
*/
function AddVars($array)
{
$array = $this->StripSlashes($array);
foreach($array as $key => $value)
{
$this->Set($key,$value);
}
return $array;
}
function MergeVars($array, $strip_slashes=true)
{
if ($strip_slashes) $array = $this->StripSlashes($array);
foreach($array as $key => $value)
{
$this->_Params = array_merge_recursive2($this->_Params, Array($key=>$value));
}
return $array;
}
function StripSlashes($array)
{
//if( !get_magic_quotes_gpc() ) return $array;
foreach($array as $key=>$value)
{
if( is_array($value) )
{
$array[$key] = $this->StripSlashes($value);
}
else
{
if( get_magic_quotes_gpc() ) $value = stripslashes($value);
if(!$this->Admin) $value = htmlspecialchars($value);
$array[$key] = $value;
}
//$array[$key]=is_array($value)?$this->StripSlashes($value):stripslashes($value);
}
return $array;
}
/**
* Returns the hash of http params
* matching the mask with values
*
* @param string $mask
* @return Array
* @access public
*/
function GetSelectedValues($mask)
{
return $this->Application->ExtractByMask($this->Vars, $mask);
}
/**
* Returns the sprintf'ed by format list of
* http params matching the mask and set to on
*
* @param string $mask
* @param string $format
* @return string
* @access public
*/
function GetSelectedIDs($mask, $format)
{
if ($mask == '') return;
$result = '';
foreach ($this->GetParams() as $name => $val)
{
if (eregi($mask, $name, $regs) && $val == 'on') {
$result.= sprintf($format, $regs[1]);
}
}
return $result;
}
/**
* Returns the sprintf'ed by format list of
* http params matching the mask and set to on
*
* @param string $mask
* @param string $value_mask
* @return Array
* @access public
*/
function GetSelectedIDsArray($mask, $value_mask="%s,")
{
$str = $this->GetSelectedIDs($mask, $value_mask);
$str = rtrim($str, ',');
if (!empty($str)) {
$ids = split(',', $str);
if ($ids !== false)
return $ids;
else return Array();
}
else return Array();
}
}
?>
\ No newline at end of file
Property changes on: trunk/core/kernel/utility/http_query.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.6
\ No newline at end of property
+1.7
\ No newline at end of property
Index: trunk/core/units/users/users_event_handler.php
===================================================================
--- trunk/core/units/users/users_event_handler.php (revision 2309)
+++ trunk/core/units/users/users_event_handler.php (revision 2310)
@@ -1,705 +1,720 @@
<?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');
+ }
+ }
+
/**
* 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 )
{
$sql = 'SELECT GroupId FROM %s WHERE (PortalUserId = %s) AND ( (MembershipExpires IS NULL) OR ( MembershipExpires >= UNIX_TIMESTAMP() ) )';
$sql = sprintf($sql, TABLE_PREFIX.'UserGroup', $user_id);
$groups = $this->Conn->GetCol($sql);
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);
}
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;
}
}
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->Loaded)
{
$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.19
\ No newline at end of property
+1.20
\ No newline at end of property
Index: trunk/core/units/general/inp_login_event_handler.php
===================================================================
--- trunk/core/units/general/inp_login_event_handler.php (revision 2309)
+++ trunk/core/units/general/inp_login_event_handler.php (nonexistent)
@@ -1,23 +0,0 @@
-<?php
-
- class InpLoginEventHandler extends kEventHandler
- {
- function OnSessionExpire()
- {
- if( $this->Application->IsAdmin() )
- {
- $location = $this->Application->BaseURL().ADMIN_DIR.'/index.php?expired=1';
- header('Location: '.$location);
- exit;
- }
- else
- {
- $this->Application->Redirect('index');
- }
- }
-
-
- }
-
-
-?>
\ No newline at end of file
Property changes on: trunk/core/units/general/inp_login_event_handler.php
___________________________________________________________________
Deleted: cvs2svn:cvs-rev
## -1 +0,0 ##
-1.5
\ No newline at end of property
Deleted: svn:executable
## -1 +0,0 ##
-*
\ No newline at end of property
Index: trunk/core/units/general/my_application.php
===================================================================
--- trunk/core/units/general/my_application.php (revision 2309)
+++ trunk/core/units/general/my_application.php (revision 2310)
@@ -1,81 +1,80 @@
<?php
k4_include_once(MODULES_PATH.'/kernel/units/general/inp_db_event_handler.php');
class MyApplication extends kApplication {
function RegisterDefaultClasses()
{
parent::RegisterDefaultClasses();
$this->registerClass('Inp1Parser',MODULES_PATH.'/kernel/units/general/inp1_parser.php','Inp1Parser');
$this->registerClass('InpSession',MODULES_PATH.'/kernel/units/general/inp_ses_storage.php','Session');
$this->registerClass('InpSessionStorage',MODULES_PATH.'/kernel/units/general/inp_ses_storage.php','SessionStorage');
$this->registerClass('kCatDBItem',MODULES_PATH.'/kernel/units/general/cat_dbitem.php');
$this->registerClass('kCatDBList',MODULES_PATH.'/kernel/units/general/cat_dblist.php');
$this->registerClass('kCatDBEventHandler',MODULES_PATH.'/kernel/units/general/cat_event_handler.php');
- $this->registerClass('InpLoginEventHandler',MODULES_PATH.'/kernel/units/general/inp_login_event_handler.php','login_EventHandler');
$this->registerClass('InpDBEventHandler',MODULES_PATH.'/kernel/units/general/inp_db_event_handler.php','kDBEventHandler');
$this->registerClass('InpTempTablesHandler',MODULES_PATH.'/kernel/units/general/inp_temp_handler.php','kTempTablesHandler');
$this->registerClass('InpCustomFieldsHelper',MODULES_PATH.'/kernel/units/general/custom_fields.php','InpCustomFieldsHelper');
$this->registerClass('kCountryStatesHelper',MODULES_PATH.'/kernel/units/general/country_states.php','CountryStatesHelper');
}
/**
* Checks if user is logged in, and creates
* user object if so. User object can be recalled
* later using "u" prefix. Also you may
* get user id by getting "u_id" variable.
*
* @access private
*/
function ValidateLogin()
{
$session =& $this->recallObject('Session');
$user_id = $session->GetField('PortalUserId');
if (!$user_id) $user_id = -2;
$this->SetVar('u_id', $user_id);
$this->StoreVar('user_id', $user_id);
}
function RunScheduledEvents()
{
$events = Array('ls:OnCheckExpiredPaidListings', 'u:OnCheckExpiredMembership');
$run_interval = 60 * 30; // in seconds
if(rand(0, 100) < 90)
{
return;
}
$sql = 'SELECT Data FROM '.TABLE_PREFIX.'Cache WHERE VarName = "LastMaintainRun"';
$last_maintain = $this->DB->GetOne($sql);
if($last_maintain && $last_maintain > mktime() - $run_interval)
{
return;
}
elseif($last_maintain)
{
$sql = 'UPDATE '.TABLE_PREFIX.'Cache SET Data = "'.mktime().'"
WHERE VarName = "LastMaintainRun"';
}
else
{
$sql = 'INSERT INTO '.TABLE_PREFIX.'Cache (VarName, Data, Cached)
VALUES ("LastMaintainRun", "'.mktime().'", "'.mktime().'")';
}
$this->DB->Query($sql);
foreach($events as $scheduled_event)
{
$event = new kEvent($scheduled_event);
$this->HandleEvent($event);
unset($event);
}
}
}
?>
\ No newline at end of file
Property changes on: trunk/core/units/general/my_application.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.11
\ No newline at end of property
+1.12
\ No newline at end of property

Event Timeline