Page MenuHomeIn-Portal Phabricator

in-portal
No OneTemporary

File Metadata

Created
Sat, Feb 1, 11:16 AM

in-portal

Index: trunk/kernel/units/users/users_event_handler.php
===================================================================
--- trunk/kernel/units/users/users_event_handler.php (revision 2377)
+++ trunk/kernel/units/users/users_event_handler.php (revision 2378)
@@ -1,717 +1,717 @@
<?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);
}
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)
+ 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.21
\ No newline at end of property
+1.22
\ No newline at end of property
Index: trunk/core/kernel/db/db_tag_processor.php
===================================================================
--- trunk/core/kernel/db/db_tag_processor.php (revision 2377)
+++ trunk/core/kernel/db/db_tag_processor.php (revision 2378)
@@ -1,1245 +1,1243 @@
<?php
class kDBTagProcessor extends TagProcessor {
/**
* Description
*
* @var kDBConnection
* @access public
*/
var $Conn;
function kDBTagProcessor()
{
parent::kBase();
$this->Conn =& $this->Application->GetADODBConnection();
}
/**
* Returns true if "new" button was pressed in toolbar
*
* @param Array $params
* @return bool
*/
function IsNewMode($params)
{
$object =& $this->Application->recallObject( $this->getPrefixSpecial(), $this->Prefix, $params );
return $object->GetID() <= 0;
}
/**
* Returns view menu name for current prefix
*
* @param Array $params
* @return string
*/
function GetItemName($params)
{
$item_name = $this->Application->getUnitOption($this->Prefix,'ViewMenuPhrase');
return $this->Application->Phrase($item_name);
}
function ViewMenu($params)
{
$block_params = $params;
unset($block_params['block']);
$block_params['name'] = $params['block'];
$list =& $this->GetList($params);
$block_params['PrefixSpecial'] = $list->getPrefixSpecial();
return $this->Application->ParseBlock($block_params);
}
function SearchKeyword($params)
{
$list =& $this->GetList($params);
return $this->Application->RecallVar($list->getPrefixSpecial().'_search_keyword');
}
/**
* Draw filter menu content (for ViewMenu) based on filters defined in config
*
* @param Array $params
* @return string
*/
function DrawFilterMenu($params)
{
$block_params = $this->prepareTagParams($params);
$block_params['name'] = $params['spearator_block'];
$separator = $this->Application->ParseBlock($block_params);
$filter_menu = $this->Application->getUnitOption($this->Prefix,'FilterMenu');
// Params: label, filter_action, filter_status
$block_params['name'] = $params['item_block'];
$view_filter = $this->Application->RecallVar($this->getPrefixSpecial().'_view_filter');
if($view_filter === false)
{
$event_params = Array('prefix'=>$this->Prefix,'special'=>$this->Special,'name'=>'OnRemoveFilters');
$this->Application->HandleEvent( new kEvent($event_params) );
$view_filter = $this->Application->RecallVar($this->getPrefixSpecial().'_view_filter');
}
$view_filter = unserialize($view_filter);
$filters = Array();
$prefix_special = $this->getPrefixSpecial();
foreach($filter_menu['Filters'] as $filter_key => $filter_params)
{
if(!$filter_params)
{
$filters[] = $separator;
continue;
}
$block_params['label'] = addslashes( $this->Application->Phrase($filter_params['label']) );
if( getArrayValue($view_filter,$filter_key) )
{
$submit = 0;
$status = 1;
}
else
{
$submit = 1;
$status = 0;
}
$block_params['filter_action'] = 'set_filter("'.$prefix_special.'","'.$filter_key.'","'.$submit.'");';
$block_params['filter_status'] = $status;
$filters[] = $this->Application->ParseBlock($block_params);
}
return implode('', $filters);
}
function IterateGridFields($params)
{
$mode = $params['mode'];
$def_block = $params['block'];
$grids = $this->Application->getUnitOption($this->Prefix,'Grids');
$grid_config = $grids[$params['grid']]['Fields'];
$std_params['pass_params']='true';
$std_params['PrefixSpecial']=$this->getPrefixSpecial();
$o = '';
foreach ($grid_config as $field => $options) {
$block_params = Array();
$block_params['name'] = isset($options[$mode.'_block']) ? $options[$mode.'_block'] : $def_block;
$block_params['field'] = $field;
$block_params['sort_field'] = isset($options['sort_field']) ? $options['sort_field'] : $field;
$block_params = array_merge($std_params, $block_params, $options);
$o.= $this->Application->ParseBlock($block_params, 1);
}
return $o;
}
/**
* Prints list content using block specified
*
* @param Array $params
* @return string
* @access public
*/
function PrintList($params)
{
// $list =& $this->Application->recallObject( $this->getPrefixSpecial(), $this->Prefix.'_List',$params);
$list =& $this->GetList($params);
$id_field = $this->Application->getUnitOption($this->Prefix,'IDField');
$list->Query();
$o = '';
$list->GoFirst();
$block_params=$this->prepareTagParams($params);
$block_params['name'] = $this->SelectParam($params, 'render_as,block');
$block_params['pass_params'] = 'true';
while (!$list->EOL())
{
$this->Application->SetVar( $this->getPrefixSpecial().'_id', $list->GetDBField($id_field) ); // for edit/delete links using GET
$o.= $this->Application->ParseBlock($block_params, 1);
$list->GoNext();
}
$this->Application->SetVar( $this->getPrefixSpecial().'_id', '');
return $o;
}
function InitList($params)
{
$list_name = $params['list_name'];
$names_mapping = $this->Application->GetVar('NamesToSpecialMapping');
if( !getArrayValue($names_mapping,$list_name) )
{
$list =& $this->GetList($params);
}
}
function BuildListSpecial($params)
{
return $this->Special;
}
/**
* Enter description here...
*
* @param unknown_type $params
* @return kDBList
*/
function &GetList($params)
{
$list_name = $this->SelectParam($params, 'list_name,name');
if (!$list_name) {
$list_name = $this->Application->Parser->GetParam('list_name');
}
$requery = getArrayValue($params, 'requery');
if ($list_name && !$requery){
$names_mapping = $this->Application->GetVar('NamesToSpecialMapping');
$special = getArrayValue($names_mapping, $list_name);
if(!$special)
{
$special = $this->BuildListSpecial($params);
}
}
else
{
$special = $this->BuildListSpecial($params);
}
$prefix_special = rtrim($this->Prefix.'.'.$special, '.');
$params['skip_counting'] = true;
$list =& $this->Application->recallObject( $prefix_special, $this->Prefix.'_List',$params);
$list->Query();
$this->Special = $special;
if ($list_name) {
$names_mapping[$list_name] = $special;
$this->Application->SetVar('NamesToSpecialMapping', $names_mapping);
}
return $list;
}
function ListMarker($params)
{
$list =& $this->GetList($params);
return $list->getPrefixSpecial();
}
function SubmitName($params)
{
$list =& $this->GetList($params);
$prefix_special = $list->getPrefixSpecial();
return 'events['.$prefix_special.']['.$params['event'].']';
}
function CombinedSortingDropDownName($params)
{
$list =& $this->GetList($params);
$prefix_special = $list->getPrefixSpecial();
return $prefix_special.'_CombinedSorting';
}
function SortingSelected($params)
{
$list =& $this->GetList($params);
$user_sorting_start = $this->getUserSortIndex();
$sorting = strtolower($list->GetOrderField($user_sorting_start).'|'.$list->GetOrderDirection($user_sorting_start));
if ($sorting == strtolower($params['sorting'])) return $params['selected'];
}
/**
* Prints list content using block specified
*
* @param Array $params
* @return string
* @access public
*/
function PrintList2($params)
{
$per_page = $this->SelectParam($params, 'per_page,max_items');
if ($per_page !== false) $params['per_page'] = $per_page;
$list =& $this->GetList($params);
$o = '';
$direction = (isset($params['direction']) && $params['direction']=="H")?"H":"V";
$columns = (isset($params['columns'])) ? $params['columns'] : 1;
$id_field = (isset($params['id_field'])) ? $params['id_field'] : $this->Application->getUnitOption($this->Prefix, 'IDField');
if ($columns>1 && $direction=="V") {
$list->Records = $this->LinearToVertical($list->Records, $columns, $list->GetPerPage());
$list->SelectedCount=count($list->Records);
ksort($list->Records);
}
$list->GoFirst();
$block_params=$this->prepareTagParams($params);
$block_params['name']=$this->SelectParam($params, 'render_as,block');
$block_params['pass_params']='true';
$block_start_row_params=$this->prepareTagParams($params);
$block_start_row_params['name'] = $this->SelectParam($params, 'row_start_render_as,block_row_start,row_start_block');
$block_end_row_params=$this->prepareTagParams($params);
$block_end_row_params['name'] = $this->SelectParam($params, 'row_end_render_as,block_row_end,row_end_block');
$block_empty_cell_params = $this->prepareTagParams($params);
$block_empty_cell_params['name'] = $this->SelectParam($params, 'empty_cell_render_as,block_empty_cell,empty_cell_block');
$i=0;
$backup_id=$this->Application->GetVar($this->Prefix."_id");
$displayed = array();
while (!$list->EOL())
{
$this->Application->SetVar( $this->getPrefixSpecial().'_id', $list->GetDBField($id_field) ); // for edit/delete links using GET
$this->Application->SetVar( $this->Prefix.'_id', $list->GetDBField($id_field) );
if ($i % $columns == 0) {
$o.= $block_start_row_params['name'] ? $this->Application->ParseBlock($block_start_row_params, 1) : '<tr>';
}
if (!$list->getCurrentRecord()){
$o.= $block_empty_cell_params['name'] ? $this->Application->ParseBlock($block_params, 1) : '<td>&nbsp;</td>';
}
else {
$o.= $this->Application->ParseBlock($block_params, 1);
array_push($displayed, $list->GetDBField($id_field));
}
if (($i+1) % $columns == 0) {
$o.= $block_end_row_params['name'] ? $this->Application->ParseBlock($block_end_row_params, 1) : '</tr>';
}
$list->GoNext();
$i++;
}
$cur_displayed = $this->Application->GetVar($this->Prefix.'_displayed_ids');
if (!$cur_displayed) {
$cur_displayed = Array();
}
else {
$cur_displayed = explode(',', $cur_displayed);
}
$displayed = array_unique(array_merge($displayed, $cur_displayed));
$this->Application->SetVar($this->Prefix.'_displayed_ids', implode(',',$displayed));
$this->Application->SetVar( $this->Prefix.'_id', $backup_id);
$this->Application->SetVar( $this->getPrefixSpecial().'_id', '');
if (isset($params['more_link_render_as'])) {
$block_params = $params;
$params['render_as'] = $params['more_link_render_as'];
$o .= $this->MoreLink($params);
}
return $o;
}
function MoreLink($params)
{
$per_page = $this->SelectParam($params, 'per_page,max_items');
if ($per_page !== false) $params['per_page'] = $per_page;
$list =& $this->GetList($params);
if ($list->PerPage < $list->RecordsCount) {
$block_params = array();
$block_params['name'] = $this->SelectParam($params, 'render_as,block');
return $this->Application->ParseBlock($block_params, 1);
}
}
function NotLastItem($params)
{
$list =& $this->Application->recallObject($this->getPrefixSpecial());
return ($list->CurrentIndex < min($list->PerPage, $list->RecordsCount)-1);
}
function PageLink($params)
{
$t = isset($params['template']) ? $param['template'] : '';
if (!$t) $t = $this->Application->GetVar('t');
if (isset($params['page'])) {
$this->Application->SetVar($this->getPrefixSpecial().'_Page', $params['page']);
}
$pass = Array('pass' => 'all,'.$this->getPrefixSpecial());
// $pass = Array('pass' => 'all');
$http_query =& $this->Application->recallObject('HTTPQuery');
$get = $http_query->Get;
unset($get['env']);
// $pass = array_merge($get, $pass);
return $this->Application->HREF($t, '', $pass);
}
function ColumnWidth($params)
{
$columns = $this->Application->Parser->GetParam('columns');
return round(100/$columns).'%';
}
/**
* Append prefix and special to tag
* params (get them from tagname) like
* they were really passed as params
*
* @param Array $tag_params
* @return Array
* @access protected
*/
function prepareTagParams($tag_params=Array())
{
$ret=$tag_params;
$ret['Prefix']=$this->Prefix;
$ret['Special']=$this->Special;
$ret['PrefixSpecial']=$this->getPrefixSpecial();
return $ret;
}
function GetISO($currency)
{
if ($currency == 'selected') {
$iso = $this->Application->RecallVar('curr_iso');
}
elseif ($currency == 'primary' || $currency == '') {
$iso = $this->Application->GetPrimaryCurrency();
}
else { //explicit currency
$iso = $currency;
}
return $iso;
}
function ConvertCurrency($value, $iso)
{
$converter =& $this->Application->recallObject('kCurrencyRates');
// convery primary currency to selected (if they are the same, converter will just return)
$value = $converter->Convert($value, 'PRIMARY', $iso);
return $value;
}
function AddCurrencySymbol($value, $iso)
{
$this->Application->setUnitOption('curr', 'AutoLoad', false);
$currency =& $this->Application->recallObject('curr.-'.$iso);
- if (!$currency->Loaded) {
- $currency->Load($iso, 'ISO');
- }
+ if( !$currency->isLoaded() ) $currency->Load($iso, 'ISO');
$symbol = $currency->GetDBField('Symbol');
if (!$symbol) $symbol = $currency->GetDBField('ISO').'&nbsp;';
if ($currency->GetDBField('SymbolPosition') == 0) {
$value = $symbol.$value;
}
if ($currency->GetDBField('SymbolPosition') == 1) {
$value = $value.$symbol;
}
return $value;
}
/**
* Get's requested field value
*
* @param Array $params
* @return string
* @access public
*/
function Field($params)
{
$field = $this->SelectParam($params, 'name,field');
if( !$this->Application->IsAdmin() ) $params['no_special'] = 'no_special';
$object =& $this->Application->recallObject($this->getPrefixSpecial(),$this->Prefix, $params);
if ( getArrayValue($params, 'db') !== false )
{
$value = $object->GetDBField($field);
}
else
{
if (isset($params['currency'])) {
$iso = $this->GetISO($params['currency']);
$original = $object->GetDBField($field);
$value = $this->ConvertCurrency($original, $iso);
$object->SetDBField($field, $value);
$object->Fields[$field]['converted'] = true;
}
$format = getArrayValue($params, 'format');
if( !$format || $format == '$format' )
{
$format = null;
}
else
{
if(preg_match("/_regional_(.*)/", $format, $regs))
{
$lang =& $this->Application->recallObject('lang.current');
$format = $lang->GetDBField($regs[1]);
}
}
$value = $object->GetField($field, $format);
if (isset($params['currency'])) {
$value = $this->AddCurrencySymbol($value, $iso);
$params['no_special'] = 1;
}
}
if( getArrayValue($params,'nl2br' ) ) $value = nl2br($value);
if( !$this->HasParam($params, 'no_special') ) $value = htmlspecialchars($value);
if( getArrayValue($params,'checked' ) ) $value = ($value == 1) ? 'checked' : '';
if( getArrayValue($params,'as_label') ) $value = $this->Application->Phrase($value);
$first_chars = $this->SelectParam($params,'first_chars,cut_first');
if($first_chars)
{
$needs_cut = strlen($value) > $first_chars;
$value = substr($value,0,$first_chars);
if($needs_cut) $value .= ' ...';
}
if ($value != '') $this->Application->Parser->DataExists = true;
if (isset($params['currency'])) {
//restoring value in original currency, for other Field tags to work properly
$object->SetDBField($field, $original);
}
return $value;
}
/**
* Checks if parameter is passed
* Note: works like Tag and line simple method too
*
* @param Array $params
* @param string $param_name
* @return bool
*/
function HasParam($params, $param_name = null)
{
if( !isset($param_name) )
{
$param_name = $this->SelectParam($params, 'name');
$params = $this->Application->Parser->Params;
}
$value = getArrayValue($params, $param_name);
return $value && ($value != '$'.$param_name);
}
function PhraseField($params)
{
$field_label = $this->Field($params);
$translation = $this->Application->Phrase( $field_label );
return $translation;
}
function Error($params)
{
$field = $params['field'];
$object =& $this->Application->recallObject($this->getPrefixSpecial(), $this->Prefix, $params);
$msg = $object->GetErrorMsg($field, false);
return $msg;
}
function HasError($params)
{
if ($params['field'] == 'any') {
$object =& $this->Application->recallObject($this->getPrefixSpecial());
return $object->HasErrors();
}
else {
return $this->Error($params) != '';
}
}
function IsRequired($params)
{
$field = $params['field'];
$object =& $this->Application->recallObject($this->getPrefixSpecial(),$this->Prefix, $params);
$options = $object->GetFieldOptions($field);
return getArrayValue($options,'required');
}
function PredefinedOptions($params)
{
$field = $params['field'];
$object =& $this->Application->recallObject($this->getPrefixSpecial(),$this->Prefix, $params);
$value = $object->GetDBField($field);
$options = $object->GetFieldOptions($field);
$block_params = $this->prepareTagParams($params);
$block_params['name'] = $this->SelectParam($params, 'render_as,block');
$block_params['field'] = $params['field'];
$block_params['pass_params'] = 'true';
$selected_param_name = getArrayValue($params,'selected_param');
if(!$selected_param_name) $selected_param_name = $params['selected'];
$selected = $params['selected'];
$o = '';
if( $this->HasParam($params,'no_empty') && !getArrayValue($options['options'],'') ) array_shift($options['options']);
foreach ($options['options'] as $key => $val) {
$block_params['key'] = $key;
$block_params['option'] = $val;
$block_params['field_name'] = $this->InputName($params);
$block_params[$selected_param_name] = ( $key == $value ? ' '.$selected : '');
$block_params['PrefixSpecial'] = $this->getPrefixSpecial();
$o .= $this->Application->ParseBlock($block_params, 1);
}
return $o;
}
function Format($params)
{
$field = $params['field'];
$object =& $this->Application->recallObject($this->getPrefixSpecial(),$this->Prefix, $params);
$options = $object->GetFieldOptions($field);
$formatter_class = getArrayValue($options,'formatter');
if($formatter_class)
{
$formatter =& $this->Application->recallObject($formatter_class);
$human_format = getArrayValue($params,'human');
$edit_size = getArrayValue($params,'edit_size');
$sample = getArrayValue($params,'sample');
if($sample)
{
return $formatter->GetSample($field, $options, $object);
}
elseif($human_format || $edit_size)
{
$format = $formatter->HumanFormat($options['format']);
return $edit_size ? strlen($format) : $format;
}
}
return $options['format'];
}
/**
* Print grid pagination using
* block names specified
*
* @param Array $params
* @return string
* @access public
*/
function PrintPages($params)
{
$list =& $this->GetList($params);
$prefix_special = $list->getPrefixSpecial();
$total_pages = $list->GetTotalPages();
if ($total_pages) $this->Application->Parser->DataExists = true;
$o = '';
// what are these 2 lines for?
$this->Application->SetVar($prefix_special.'_event','');
$this->Application->SetVar($prefix_special.'_id','');
$current_page = $this->Application->RecallVar($prefix_special.'_Page');
$block_params = $this->prepareTagParams($params);
$split = ( isset($params['split'] ) ? $params['split'] : 10 );
$split_start = $current_page - ceil($split/2);
if ($split_start < 1){
$split_start = 1;
}
$split_end = $split_start + $split-1;
if ($split_end > $total_pages) {
$split_end = $total_pages;
$split_start = max($split_end - $split + 1, 1);
}
if ($current_page > 1){
$prev_block_params = $this->prepareTagParams();
if ($total_pages > $split){
$prev_block_params['page'] = max($current_page-$split, 1);
$prev_block_params['name'] = $this->SelectParam($params, 'prev_page_split_render_as,prev_page_split_block');
if ($prev_block_params['name']){
$o .= $this->Application->ParseBlock($prev_block_params, 1);
}
}
$prev_block_params['name'] = 'page';
$prev_block_params['page'] = $current_page-1;
$prev_block_params['name'] = $this->SelectParam($params, 'prev_page_render_as,block_prev_page,prev_page_block');
if ($prev_block_params['name']) {
$this->Application->SetVar($this->getPrefixSpecial().'_Page', $current_page-1);
$o .= $this->Application->ParseBlock($prev_block_params, 1);
}
}
else {
if ( $no_prev_page_block = $this->SelectParam($params, 'no_prev_page_render_as,block_no_prev_page') ) {
$block_params['name'] = $no_prev_page_block;
$o .= $this->Application->ParseBlock($block_params, 1);
}
}
$separator_params['name'] = $this->SelectParam($params, 'separator_render_as,block_separator');
for ($i = $split_start; $i <= $split_end; $i++)
{
if ($i == $current_page) {
$block = $this->SelectParam($params, 'current_render_as,active_render_as,block_current,active_block');
}
else {
$block = $this->SelectParam($params, 'link_render_as,inactive_render_as,block_link,inactive_block');
}
$block_params['name'] = $block;
$block_params['page'] = $i;
$this->Application->SetVar($this->getPrefixSpecial().'_Page', $i);
$o .= $this->Application->ParseBlock($block_params, 1);
if ($this->SelectParam($params, 'separator_render_as,block_separator')
&& $i < $split_end)
{
$o .= $this->Application->ParseBlock($separator_params, 1);
}
}
if ($current_page < $total_pages){
$next_block_params = $this->prepareTagParams();
$next_block_params['page']=$current_page+1;
$next_block_params['name'] = $this->SelectParam($params, 'next_page_render_as,block_next_page,next_page_block');
if ($next_block_params['name']){
$this->Application->SetVar($this->getPrefixSpecial().'_Page', $current_page+1);
$o .= $this->Application->ParseBlock($next_block_params, 1);
}
if ($total_pages > $split){
$next_block_params['page']=min($current_page+$split, $total_pages);
$next_block_params['name'] = $this->SelectParam($params, 'next_page_split_render_as,next_page_split_block');
if ($next_block_params['name']){
$o .= $this->Application->ParseBlock($next_block_params, 1);
}
}
}
return $o;
}
/**
* Print grid pagination using
* block names specified
*
* @param Array $params
* @return string
* @access public
*/
function PaginationBar($params)
{
return $this->PrintPages($params);
}
/**
* Returns input field name to
* be placed on form (for correct
* event processing)
*
* @param Array $params
* @return string
* @access public
*/
function InputName($params)
{
$prefix_special=$this->getPrefixSpecial();
$object =& $this->Application->recallObject($prefix_special);
if ( $formatter = getArrayValue($object->Fields, $params['field'], 'formatter') ) {
if ( $formatter == 'kMultiLanguage' ) {
$formatter =& $this->Application->recallObject($formatter);
$params['field'] = $formatter->LangFieldName($params['field']);
}
}
if ( $idfield = getArrayValue($params, 'IdField') ) {
$id = $object->GetDBField($idfield);
}
else {
$id = $object->GetID();
}
return $prefix_special.'['.$id.']['.$params['field'].']';
}
/**
* Returns index where 1st changable sorting field begins
*
* @return int
* @access private
*/
function getUserSortIndex()
{
$list_sortings = $this->Application->getUnitOption($this->Prefix, 'ListSortings');
$sorting_prefix = getArrayValue($list_sortings, $this->Special) ? $this->Special : '';
$user_sorting_start = 0;
if ( $forced_sorting = getArrayValue($list_sortings, $sorting_prefix, 'ForcedSorting') ) {
$user_sorting_start = count($forced_sorting);
}
return $user_sorting_start;
}
/**
* Returns order direction for given field
*
*
*
* @param Array $params
* @return string
* @access public
*/
function Order($params)
{
$field = $params['field'];
$user_sorting_start = $this->getUserSortIndex();
$list =& $this->GetList($params);
if ($list->GetOrderField($user_sorting_start) == $field)
{
return strtolower($list->GetOrderDirection($user_sorting_start));
}
elseif($list->GetOrderField($user_sorting_start+1) == $field)
{
return '2_'.strtolower($list->GetOrderDirection($user_sorting_start+1));
}
else
{
return 'no';
}
}
/**
* Get's information of sorting field at "pos" position,
* like sorting field name (type="field") or sorting direction (type="direction")
*
* @param Array $params
* @return mixed
*/
function OrderInfo($params)
{
$user_sorting_start = $this->getUserSortIndex() + --$params['pos'];
$list =& $this->GetList($params);
// $object =& $this->Application->recallObject( $this->getPrefixSpecial() );
if($params['type'] == 'field') return $list->GetOrderField($user_sorting_start);
if($params['type'] == 'direction') return $list->GetOrderDirection($user_sorting_start);
}
/**
* Checks if sorting field/direction matches passed field/direction parameter
*
* @param Array $params
* @return bool
*/
function IsOrder($params)
{
$params['type'] = isset($params['field']) ? 'field' : 'direction';
$value = $this->OrderInfo($params);
if( isset($params['field']) ) return $params['field'] == $value;
if( isset($params['direction']) ) return $params['direction'] == $value;
}
/**
* Returns list perpage
*
* @param Array $params
* @return int
*/
function PerPage($params)
{
$object =& $this->Application->recallObject( $this->getPrefixSpecial() );
return $object->PerPage;
}
/**
* Checks if list perpage matches value specified
*
* @param Array $params
* @return bool
*/
function PerPageEquals($params)
{
$object =& $this->Application->recallObject( $this->getPrefixSpecial() );
return $object->PerPage == $params['value'];
}
function SaveEvent($params)
{
// SaveEvent is set during onbuild, but we may need it before any other tag calls onBuild
$prefix_special = $this->getPrefixSpecial();
$item = $this->Application->recallObject($prefix_special);
return $this->Application->GetVar($prefix_special.'_SaveEvent');
}
function NextId($params)
{
$prefix_special=$this->getPrefixSpecial();
$ids = explode(',', $this->Application->RecallVar($prefix_special.'_selected_ids'));
$item = $this->Application->recallObject($prefix_special);
$cur_id = $item->GetId();
$i = array_search($cur_id,$ids);
if ($i !== false) {
return $i < count($ids)-1 ? $ids[$i+1] : '';
}
return '';
}
function PrevId($params)
{
$prefix_special=$this->getPrefixSpecial();
$ids = explode(',', $this->Application->RecallVar($prefix_special.'_selected_ids'));
$item = $this->Application->recallObject($prefix_special);
$cur_id = $item->GetId();
$i = array_search($cur_id,$ids);
if ($i !== false) {
return $i > 0 ? $ids[$i-1] : '';
}
return '';
}
function IsSingle($params)
{
return ($this->NextId($params) === '' && $this->PrevId($params) === '');
}
function IsLast($params)
{
return ($this->NextId($params) === '');
}
function IsFirst($params)
{
return ($this->PrevId($params) === '');
}
/**
* Checks if field value is equal to proposed one
*
* @param Array $params
* @return bool
*/
function FieldEquals($params)
{
$object =& $this->Application->recallObject($this->getPrefixSpecial(),$this->Prefix, $params);
$ret = $object->GetDBField($this->SelectParam($params, 'name,field')) == $params['value'];
// if( getArrayValue($params,'inverse') ) $ret = !$ret;
return $ret;
}
function ItemIcon($params)
{
$object =& $this->Application->recallObject($this->getPrefixSpecial(),$this->Prefix, $params);
$grids = $this->Application->getUnitOption($this->Prefix,'Grids');
$icons =& $grids[ $params['grid'] ]['Icons'];
$key = '';
$status_fields = $this->Application->getUnitOption($this->Prefix,'StatusField');
if(!$status_fields) return $icons['default'];
foreach($status_fields as $status_field)
{
$key .= $object->GetDBField($status_field).'_';
}
$key = rtrim($key,'_');
$value = ($key !== false) ? $key : 'default';
return isset($icons[$value]) ? $icons[$value] : $icons['default'];
}
/**
* Generates bluebar title + initializes prefixes used on page
*
* @param Array $params
* @return string
*/
function SectionTitle($params)
{
$title_presets = $this->Application->getUnitOption($this->Prefix,'TitlePresets');
$title_info = getArrayValue($title_presets, $params['title_preset'] );
if($title_info === false) return $params['title'];
if( getArrayValue($title_presets,'default') )
{
// use default labels + custom labels specified in preset used
$title_info = array_merge_recursive2($title_presets['default'], $title_info);
}
$title = $title_info['format'];
// 1. get objects in use for title construction
$objects = Array();
$object_status = Array();
$status_labels = Array();
$prefixes = getArrayValue($title_info,'prefixes');
$all_tag_params = getArrayValue($title_info,'tag_params');
if($prefixes)
{
$tag_params = Array();
foreach($prefixes as $prefix_special)
{
$prefix_data = $this->Application->processPrefix($prefix_special);
$prefix_data['prefix_special'] = rtrim($prefix_data['prefix_special'],'.');
if($all_tag_params)
{
$tag_params = getArrayValue($all_tag_params, $prefix_data['prefix_special']);
if(!$tag_params) $tag_params = Array();
}
$tag_params = array_merge_recursive2($params, $tag_params);
$objects[ $prefix_data['prefix_special'] ] =& $this->Application->recallObject($prefix_data['prefix_special'], $prefix_data['prefix'], $tag_params);
$object_status[ $prefix_data['prefix_special'] ] = $objects[ $prefix_data['prefix_special'] ]->GetID() ? 'edit' : 'new';
// a. set object's status field (adding item/editing item) for each object in title
if( getArrayValue($title_info[ $object_status[ $prefix_data['prefix_special'] ].'_status_labels' ],$prefix_data['prefix_special']) )
{
$status_labels[ $prefix_data['prefix_special'] ] = $title_info[ $object_status[ $prefix_data['prefix_special'] ].'_status_labels' ][ $prefix_data['prefix_special'] ];
$title = str_replace('#'.$prefix_data['prefix_special'].'_status#', $status_labels[ $prefix_data['prefix_special'] ], $title);
}
// b. setting object's titlefield value (in titlebar ONLY) to default in case if object beeing created with no titlefield filled in
if( $object_status[ $prefix_data['prefix_special'] ] == 'new' )
{
$new_value = $this->getInfo( $objects[ $prefix_data['prefix_special'] ], 'titlefield' );
if(!$new_value && getArrayValue($title_info['new_titlefield'],$prefix_data['prefix_special']) ) $new_value = $this->Application->Phrase($title_info['new_titlefield'][ $prefix_data['prefix_special'] ]);
$title = str_replace('#'.$prefix_data['prefix_special'].'_titlefield#', $new_value, $title);
}
}
}
// 2. replace phrases if any found in format string
$title = $this->Application->ReplaceLanguageTags($title,false);
// 3. find and replace any replacement vars
preg_match_all('/#(.*_.*)#/Uis',$title,$rets);
if($rets[1])
{
$replacement_vars = array_keys( array_flip($rets[1]) );
foreach($replacement_vars as $replacement_var)
{
$var_info = explode('_',$replacement_var,2);
$object =& $objects[ $var_info[0] ];
$new_value = $this->getInfo($object,$var_info[1]);
$title = str_replace('#'.$replacement_var.'#', $new_value, $title);
}
}
$cut_first = getArrayValue($params,'cut_first');
if( $cut_first && strlen($title) > $cut_first && !preg_match('/<a href="(.*)">(.*)<\/a>/',$title) ) $title = substr($title, 0, $cut_first).' ...';
return $title;
}
function getInfo(&$object, $info_type)
{
switch ($info_type)
{
case 'titlefield':
$field = $this->Application->getUnitOption($object->Prefix,'TitleField');
return $field !== false ? $object->GetField($field) : 'TitleField Missing';
break;
case 'recordcount':
$of_phrase = $this->Application->Phrase('la_of');
return $object->NoFilterCount != $object->RecordsCount ? $object->RecordsCount.' '.$of_phrase.' '.$object->NoFilterCount : $object->RecordsCount;
break;
default:
break;
}
}
/**
* Parses block depending on its element type.
* For radio and select elements values are taken from 'value_list_field' in key1=value1,key2=value2
* format. key=value can be substituted by <SQL>SELECT f1 AS OptionName, f2 AS OptionValue... FROM <PREFIX>TableName </SQL>
* where prefix is TABLE_PREFIX
*
* @param Array $params
* @return string
*/
function ConfigFormElement($params)
{
$object =& $this->Application->recallObject( $this->getPrefixSpecial() );
$field = $params['field'];
$helper =& $this->Application->recallObject('InpCustomFieldsHelper');
$element_type = $object->GetDBField($params['element_type_field']);
if($element_type == 'label') $element_type = 'text';
$params['name'] = $params['blocks_prefix'].$element_type;
switch($element_type)
{
case 'select':
case 'radio':
$field_options = $object->GetFieldOptions($field, 'options');
$field_options['options'] = $helper->GetValuesHash( $object->GetDBField($params['value_list_field']) );
$object->SetFieldOptions($field, $field_options);
break;
case 'textarea':
$params['field_params'] = $helper->ParseConfigSQL($object->GetDBField($params['value_list_field']));
break;
case 'password':
case 'text':
case 'checkbox':
default:
break;
}
return $this->Application->ParseBlock($params, 1);
}
/**
* Get's requested custom field value
*
* @param Array $params
* @return string
* @access public
*/
function CustomField($params)
{
$prefix = $this->Prefix;
$object =& $this->Application->recallObject( $prefix );
$field = $this->SelectParam($params, 'name,field');
$lang_id = $this->Application->GetVar('m_lang');
$sql = ' SELECT cv.l'.$lang_id.'_Value FROM '.TABLE_PREFIX.'CustomField cf
LEFT JOIN '.TABLE_PREFIX.'CustomMetaData cv
ON cf.CustomFieldId = cv.CustomFieldId
WHERE cf.Type = '.$this->Application->getUnitOption($prefix, 'ItemType').'
AND cv.ResourceId = '.$object->GetDBField('ResourceId').'
AND cf.FieldName = "'.$field.'"';
return $this->Conn->GetOne($sql);
}
function CustomFieldLabel($params)
{
$prefix = $this->Prefix;
$object =& $this->Application->recallObject( $prefix );
$field = $this->SelectParam($params, 'name,field');
$sql = ' SELECT FieldLabel FROM '.TABLE_PREFIX.'CustomField WHERE FieldName = "'.$field.'"';
return $this->Application->Phrase($this->Conn->GetOne($sql));
}
/**
* transposes 1-dimensional array elements for vertical alignment according to given columns and per_page parameters
*
* @param array $arr
* @param int $columns
* @param int $per_page
* @return array
*/
function LinearToVertical(&$arr, $columns, $per_page)
{
$rows=$columns;
$cols=min(ceil($per_page/$columns), ceil(sizeof($arr)/$columns));
$imatrix=array();
for ($row=0; $row<$rows; $row++) {
for ($col=0; $col<$cols; $col++){
$imatrix[$col*$rows+$row]=$arr[$row*$cols+$col];
}
}
ksort($imatrix);
reset($imatrix);
return $imatrix;
}
/**
* If data was modfied & is in TempTables mode, then parse block with name passed;
* remove modification mark if not in TempTables mode
*
* @param Array $params
* @return string
* @access public
* @author Alexey
*/
function SaveWarning($params)
{
$main_prefix = getArrayValue($params, 'main_prefix');
if($main_prefix && $main_prefix != '$main_prefix')
{
$top_prefix = $main_prefix;
}
else
{
$top_prefix = $this->Application->GetTopmostPrefix($this->Prefix);
}
$temp_tables = $this->Application->GetVar($top_prefix.'_mode') == 't';
$modified = $this->Application->RecallVar($top_prefix.'_modified');
if($temp_tables && $modified)
{
return $this->Application->ParseBlock($params);
}
$this->Application->RemoveVar($top_prefix.'_modified');
return '';
}
/**
* Returns list record count queries (on all pages)
*
* @param Array $params
* @return int
*/
function TotalRecords($params)
{
$list =& $this->GetList($params);
if (!$list->Counted) $list->CountRecs();
return $list->RecordsCount;
}
}
?>
\ No newline at end of file
Property changes on: trunk/core/kernel/db/db_tag_processor.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.16
\ No newline at end of property
+1.17
\ No newline at end of property
Index: trunk/core/kernel/db/dbitem.php
===================================================================
--- trunk/core/kernel/db/dbitem.php (revision 2377)
+++ trunk/core/kernel/db/dbitem.php (revision 2378)
@@ -1,820 +1,830 @@
<?php
/**
* DBItem
*
* Desciption
* @package kernel4
*/
class kDBItem extends kDBBase {
/**
* Description
*
* @var array Associative array of current item' field values
* @access public
*/
var $FieldValues;
/**
* Unformatted field values, before parse
*
* @var Array
* @access private
*/
var $DirtyFieldValues = Array();
var $FieldErrors;
var $ErrorMsgs = Array();
/**
* If set to true, Update will skip Validation before running
*
* @var array Associative array of current item' field values
* @access public
*/
var $IgnoreValidation = false;
var $Loaded = false;
/**
* Holds item' primary key value
*
* @var int Value of primary key field for current item
* @access public
*/
var $ID;
function kDBItem()
{
parent::kDBBase();
$this->ErrorMsgs['required'] = 'Field is required';
$this->ErrorMsgs['unique'] = 'Field value must be unique';
$this->ErrorMsgs['value_out_of_range'] = 'Field is out of range, possible values from %s to %s';
$this->ErrorMsgs['length_out_of_range'] = 'Field is out of range';
$this->ErrorMsgs['bad_type'] = 'Incorrect data format, please use %s';
$this->ErrorMsgs['bad_date_format'] = 'Incorrect date format, please use (%s) ex. (%s)';
}
function SetDirtyField($field_name, $field_value)
{
$this->DirtyFieldValues[$field_name] = $field_value;
}
function GetDirtyField($field_name)
{
return $this->DirtyFieldValues[$field_name];
}
/**
* Set's default values for all fields
*
* @access public
*/
function SetDefaultValues()
{
parent::SetDefaultValues();
foreach ($this->Fields as $field => $params) {
if ( isset($params['default']) ) {
$this->SetDBField($field, $params['default']);
}
else {
$this->SetDBField($field, NULL);
}
}
}
/**
* Sets current item field value
* (applies formatting)
*
* @access public
* @param string $name Name of the field
* @param mixed $value Value to set the field to
* @return void
*/
function SetField($name,$value)
{
$options = $this->GetFieldOptions($name);
$parsed = $value;
if ($value == '') $parsed = NULL;
if (isset($options['formatter'])) {
$formatter =& $this->Application->recallObject($options['formatter']);
// $parsed = $formatter->Parse($value, $options, $err);
$parsed = $formatter->Parse($value, $name, $this);
}
$this->SetDBField($name,$parsed);
}
/**
* Sets current item field value
* (doesn't apply formatting)
*
* @access public
* @param string $name Name of the field
* @param mixed $value Value to set the field to
* @return void
*/
function SetDBField($name,$value)
{
$this->FieldValues[$name] = $value;
/*if (isset($this->Fields[$name]['formatter'])) {
$formatter =& $this->Application->recallObject($this->Fields[$name]['formatter']);
$formatter->UpdateSubFields($name, $value, $this->Fields[$name], $this);
}*/
}
/**
* Set's field error, if pseudo passed not found then create it with message text supplied.
* Don't owerrite existing pseudo translation.
*
* @param string $field
* @param string $pseudo
* @param string $error_label
*/
function SetError($field, $pseudo, $error_label = '')
{
$error_msg = $this->Application->Phrase($error_label);
if( !($error_msg && getArrayValue($this->ErrorMsgs,$pseudo)) )
{
$this->ErrorMsgs[$pseudo] = $error_msg;
}
$this->FieldErrors[$field]['pseudo'] = $pseudo;
}
/**
* Return current item' field value by field name
* (doesn't apply formatter)
*
* @access public
* @param string $name field name to return
* @return mixed
*/
function GetDBField($name)
{
return $this->FieldValues[$name];
}
function HasField($name)
{
return isset($this->FieldValues[$name]);
}
function GetFieldValues()
{
return $this->FieldValues;
}
/**
* Sets item' fields corresponding to elements in passed $hash values.
*
* The function sets current item fields to values passed in $hash, by matching $hash keys with field names
* of current item. If current item' fields are unknown {@link kDBItem::PrepareFields()} is called before acutally setting the fields
*
* @access public
* @param Array $hash
* @param Array $set_fields Optional param, field names in target object to set, other fields will be skipped
* @return void
*/
function SetFieldsFromHash($hash, $set_fields=null)
{
// used in formatter which work with multiple fields together
foreach($hash as $field_name => $field_value)
{
if( eregi("^[0-9]+$", $field_name) || !array_key_exists($field_name,$this->Fields) ) continue;
if ( is_array($set_fields) && !in_array($field_name, $set_fields) ) continue;
$this->SetDirtyField($field_name, $field_value);
}
// formats all fields using associated formatters
foreach ($hash as $field_name => $field_value)
{
if( eregi("^[0-9]+$", $field_name) || !array_key_exists($field_name,$this->Fields) ) continue;
if ( is_array($set_fields) && !in_array($field_name, $set_fields) ) continue;
$this->SetField($field_name,$field_value);
}
}
function SetDBFieldsFromHash($hash, $set_fields=null)
{
foreach ($hash as $field_name => $field_value)
{
if( eregi("^[0-9]+$", $field_name) || !array_key_exists($field_name,$this->Fields) ) continue;
if ( is_array($set_fields) && !in_array($field_name, $set_fields) ) continue;
$this->SetDBField($field_name, $field_value);
}
}
/**
* Returns part of SQL WHERE clause identifing the record, ex. id = 25
*
* @access public
* @param string $method Child class may want to know who called GetKeyClause, Load(), Update(), Delete() send its names as method
* @return void
* @see kDBItem::Load()
* @see kDBItem::Update()
* @see kDBItem::Delete()
*/
function GetKeyClause($method=null)
{
return '`'.$this->TableName.'`.'.$this->IDField.' = '.$this->Conn->qstr($this->ID);
}
/**
* Loads item from the database by given id
*
* @access public
* @param int $id Primery Key Id to load
* @param string $id_field_name Optional parameter to load item by given Id field
* @return bool True if item has been loaded, false otherwise
*/
function Load($id, $id_field_name=null)
{
if (is_array($id)) {
$keys = $id;
foreach ($keys as $field => $value) {
$sqls[] = '`'.$this->TableName.'`.'.$field.' = '.$this->Conn->qstr($value);
}
$keys_sql = '('.implode(') AND (', $sqls).')';
}
if (isset($id_field_name)) $this->SetIDField($id_field_name);
if (!isset($id) && !isset($keys_sql)) return false;
if( !$this->raiseEvent('OnBeforeItemLoad',$id) ) return false;
$this->ID = $id;
$q = $this->GetSelectSQL().' WHERE '.(isset($keys_sql) ? $keys_sql : $this->GetKeyClause('load'));
if ($this->DisplayQueries) {
echo get_class($this)." Load SQL: $q<br>";
}
$this->FieldValues = array_merge_recursive2( $this->FieldValues, $this->Conn->GetRow($q) );
if ($this->FieldValues === false) {
//Error handling could be here
return false;
}
if (isset($keys_sql)) {
$this->setID($this->FieldValues[$this->IDField]);
}
else {
$this->setID($id);
}
$this->UpdateFormattersSubFields(); // used for updating separate virtual date/time fields from DB timestamp (for example)
$this->raiseEvent('OnAfterItemLoad');
$this->Loaded = true;
return true;
}
/**
* Builds select sql, SELECT ... FROM parts only
*
* @access public
* @return string
*/
function GetSelectSQL()
{
$sql = $this->addCalculatedFields($this->SelectClause);
return parent::GetSelectSQL($sql);
}
function UpdateFormattersMasterFields()
{
foreach ($this->Fields as $field => $options) {
if (isset($options['formatter'])) {
$formatter =& $this->Application->recallObject($options['formatter']);
$formatter->UpdateMasterFields($field, $this->GetDBField($field), $options, $this);
}
}
}
function SkipField($field_name, $force_id=false)
{
$skip = false;
$skip = $skip || ( isset($this->VirtualFields[$field_name]) ); //skipping 'virtual' field
$skip = $skip || ( !getArrayValue($this->FieldValues, $field_name) && getArrayValue($this->Fields[$field_name], 'skip_empty') ); //skipping 'virtual' field
// $skip = $skip || ($field_name == $this->IDField && !$force_id); //skipping Primary Key
// $table_name = preg_replace("/^(.*)\./", "$1", $field_name);
// $skip = $skip || ($table_name && ($table_name != $this->TableName)); //skipping field from other tables
$skip = $skip || ( !isset($this->Fields[$field_name]) ); //skipping field not in Fields (nor virtual, nor real)
return $skip;
}
/**
* Updates previously loaded record with current item' values
*
* @access public
* @param int Primery Key Id to update
* @return bool
*/
function Update($id=null, $system_update=false)
{
if( isset($id) ) $this->setID($id);
if( !$this->raiseEvent('OnBeforeItemUpdate') ) return false;
if( !isset($this->ID) ) return false;
// Validate before updating
if( !$this->IgnoreValidation && !$this->Validate() ) return false;
if( !$this->raiseEvent('OnAfterItemValidate') ) return false;
//Nothing to update
if(!$this->FieldValues) return true;
$sql = sprintf('UPDATE %s SET ',$this->TableName);
foreach ($this->FieldValues as $field_name => $field_value)
{
if ($this->SkipField($field_name)) continue;
$real_field_name = eregi_replace("^.*\.", '',$field_name); //removing table names from field names
//Adding part of SET clause for current field, escaping data with ADODB' qstr
if (is_null( $this->FieldValues[$field_name] )) {
if (isset($this->Fields[$field_name]['not_null']) && $this->Fields[$field_name]['not_null']) {
$sql .= '`'.$real_field_name.'` = '.$this->Conn->qstr($this->Fields[$field_name]['default']).', ';
}
else {
$sql .= '`'.$real_field_name.'` = NULL, ';
}
}
else {
$sql.= sprintf('`%s`=%s, ', $real_field_name, $this->Conn->qstr($this->FieldValues[$field_name], 0));
}
}
$sql = ereg_replace(", $", '', $sql); //Removing last comma and space
$sql.= sprintf(' WHERE %s', $this->GetKeyClause('update')); //Adding WHERE clause with Primary Key
if ($this->DisplayQueries) echo "Sql: $sql<br>";
if ($this->Conn->ChangeQuery($sql) === false) { //Executing query and checking results
if ($this->DisplayQueries)
{
echo "Error executing statement: ".$adodbConnection->ErrorMsg()."<br>";
}
return false;
}
$affected = $this->Conn->getAffectedRows();
if (!$system_update && $affected == 1){
$this->setModifiedFlag();
}
$this->raiseEvent('OnAfterItemUpdate');
return true;
}
/**
* Validate all item fields based on
* constraints set in each field options
* in config
*
* @return bool
* @access private
*/
function Validate()
{
$this->UpdateFormattersMasterFields(); //order is critical - should be called BEFORE checking errors
$global_res = true;
foreach ($this->Fields as $field => $params) {
$res = true;
$res = $res && $this->ValidateType($field, $params);
$res = $res && $this->ValidateRange($field, $params);
$res = $res && $this->ValidateUnique($field, $params);
$res = $res && $this->ValidateRequired($field, $params);
// If Formatter has set some error messages during values parsing
$error_field = isset($params['error_field']) ? $params['error_field'] : $field;
if (isset($this->FieldErrors[$error_field]['pseudo']) && $this->FieldErrors[$error_field] != '') {
$global_res = false;
}
$global_res = $global_res && $res;
}
if (!$global_res && $this->Application->isDebugMode() )
{
global $debugger;
$error_msg = "Validation failed in prefix <b>".$this->Prefix."</b>, FieldErrors follow (look at items with 'pseudo' key set)<br>
You may ignore this notice if submitted data really has a validation error ";
trigger_error( $error_msg, E_USER_NOTICE);
$debugger->dumpVars($this->FieldErrors);
}
return $global_res;
}
function HasErrors()
{
$global_res = false;
foreach ($this->Fields as $field => $params) {
// If Formatter has set some error messages during values parsing
if (isset($this->FieldErrors[$field]['pseudo']) && $this->FieldErrors[$field] != '') {
$global_res = true;
}
}
return $global_res;
}
/**
* Check if value in field matches field type specified in config
*
* @param string $field field name
* @param Array $params field options from config
* @return bool
*/
function ValidateType($field, $params)
{
$res = true;
$val = $this->FieldValues[$field];
$error_field = isset($params['error_field']) ? $params['error_field'] : $field;
if ( $val != '' &&
isset($params['type']) &&
preg_match("#int|integer|double|float|real|numeric|string#", $params['type'])
) {
$res = is_numeric($val);
if($params['type']=='string' || $res)
{
$f = 'is_'.$params['type'];
settype($val, $params['type']);
$res = $f($val) && ($val==$this->FieldValues[$field]);
}
if (!$res)
{
$this->FieldErrors[$error_field]['pseudo'] = 'bad_type';
$this->FieldErrors[$error_field]['params'] = $params['type'];
}
}
return $res;
}
/**
* Check if value is set for required field
*
* @param string $field field name
* @param Array $params field options from config
* @return bool
* @access private
*/
function ValidateRequired($field, $params)
{
$res = true;
$error_field = isset($params['error_field']) ? $params['error_field'] : $field;
if ( getArrayValue($params,'required') )
{
$res = ( (string) $this->FieldValues[$field] != '');
}
$options = $this->GetFieldOptions($field);
if (!$res && getArrayValue($options, 'formatter') != 'kUploadFormatter') $this->FieldErrors[$error_field]['pseudo'] = 'required';
return $res;
}
/**
* Validates that current record has unique field combination among other table records
*
* @param string $field field name
* @param Array $params field options from config
* @return bool
* @access private
*/
function ValidateUnique($field, $params)
{
$res = true;
$error_field = isset($params['error_field']) ? $params['error_field'] : $field;
$unique_fields = getArrayValue($params,'unique');
if($unique_fields !== false)
{
$where = Array();
array_push($unique_fields,$field);
foreach($unique_fields as $unique_field)
{
$where[] = '`'.$unique_field.'` = '.$this->Conn->qstr( $this->GetDBField($unique_field) );
}
$sql = 'SELECT COUNT(*) FROM %s WHERE ('.implode(') AND (',$where).') AND ('.$this->IDField.' <> '.(int)$this->ID.')';
$res_temp = $this->Conn->GetOne( sprintf($sql, $this->TableName ) );
$res_live = $this->Conn->GetOne( sprintf($sql, kTempTablesHandler::GetLiveName($this->TableName) ) );
$res = ($res_temp == 0) && ($res_live == 0);
if(!$res) $this->FieldErrors[$error_field]['pseudo'] = 'unique';
}
return $res;
}
/**
* Check if field value is in range specified in config
*
* @param string $field field name
* @param Array $params field options from config
* @return bool
* @access private
*/
function ValidateRange($field, $params)
{
$res = true;
$val = $this->FieldValues[$field];
$error_field = isset($params['error_field']) ? $params['error_field'] : $field;
if ( isset($params['type']) && preg_match("#int|integer|double|float|real#", $params['type']) && strlen($val) > 0 ) {
if ( isset($params['max_value_inc'])) {
$res = $res && $val <= $params['max_value_inc'];
$max_val = $params['max_value_inc'].' (inclusive)';
}
if ( isset($params['min_value_inc'])) {
$res = $res && $val >= $params['min_value_inc'];
$min_val = $params['min_value_inc'].' (inclusive)';
}
if ( isset($params['max_value_exc'])) {
$res = $res && $val < $params['max_value_exc'];
$max_val = $params['max_value_exc'].' (exclusive)';
}
if ( isset($params['min_value_exc'])) {
$res = $res && $val > $params['min_value_exc'];
$min_val = $params['min_value_exc'].' (exclusive)';
}
}
if (!$res) {
$this->FieldErrors[$error_field]['pseudo'] = 'value_out_of_range';
if ( !isset($min_val) ) $min_val = '-&infin;';
if ( !isset($max_val) ) $max_val = '&infin;';
$this->FieldErrors[$error_field]['params'] = Array( $min_val, $max_val );
return $res;
}
if ( isset($params['max_len'])) {
$res = $res && strlen($val) <= $params['max_len'];
}
if ( isset($params['min_len'])) {
$res = $res && strlen($val) >= $params['min_len'];
}
if (!$res) {
$this->FieldErrors[$error_field]['pseudo'] = 'length_out_of_range';
$this->FieldErrors[$error_field]['params'] = Array( getArrayValue($params,'min_len'), getArrayValue($params,'max_len') );
return $res;
}
return $res;
}
/**
* Return error message for field
*
* @param string $field
* @return string
* @access public
*/
function GetErrorMsg($field, $force_escape = null)
{
if( !isset($this->FieldErrors[$field]) ) return '';
$err = getArrayValue($this->FieldErrors[$field], 'pseudo');
if( isset($this->Fields[$field]['error_msgs'][$err]) )
{
$msg = $this->Fields[$field]['error_msgs'][$err];
$msg = $this->Application->ReplaceLanguageTags($msg, $force_escape);
}
else
{
if( !isset($this->ErrorMsgs[$err]) ) return $err;
$msg = $this->ErrorMsgs[$err];
}
if ( isset($this->FieldErrors[$field]['params']) )
{
return vsprintf($msg, $this->FieldErrors[$field]['params']);
}
return $msg;
}
/**
* Creates a record in the database table with current item' values
*
* @param mixed $force_id Set to TRUE to force creating of item's own ID or to value to force creating of passed id. Do not pass 1 for true, pass exactly TRUE!
* @access public
* @return bool
*/
function Create($force_id=false, $system_create=false)
{
if( !$this->raiseEvent('OnBeforeItemCreate') ) return false;
// Validating fields before attempting to create record
if( !$this->IgnoreValidation && !$this->Validate() ) return false;
if( !$this->raiseEvent('OnAfterItemValidate') ) return false;
if (is_int($force_id)) {
$this->FieldValues[$this->IDField] = $force_id;
}
elseif (!$force_id || !is_bool($force_id)) {
$this->FieldValues[$this->IDField] = $this->generateID();
}
$fields_sql = '';
$values_sql = '';
foreach ($this->FieldValues as $field_name => $field_value)
{
if ($this->SkipField($field_name, $force_id)) continue;
$fields_sql .= sprintf('`%s`, ',$field_name); //Adding field name to fields block of Insert statement
//Adding field' value to Values block of Insert statement, escaping it with ADODB' qstr
if (is_null( $this->FieldValues[$field_name] )) {
if (isset($this->Fields[$field_name]['not_null']) && $this->Fields[$field_name]['not_null']) {
$values_sql .= $this->Conn->qstr($this->Fields[$field_name]['default']).', ';
}
else {
$values_sql .= 'NULL, ';
}
}
else
{
$values_sql .= sprintf('%s, ',$this->Conn->qstr($this->FieldValues[$field_name], 0));
}
}
//Cutting last commas and spaces
$fields_sql = ereg_replace(", $", '', $fields_sql);
$values_sql = ereg_replace(", $", '', $values_sql);
$sql = sprintf('INSERT INTO %s (%s) VALUES (%s)', $this->TableName, $fields_sql, $values_sql); //Formatting query
//Executing the query and checking the result
if ($this->Conn->ChangeQuery($sql) === false)
{
if($this->DisplayQueries)
{
echo "Error executing statement: ".$this->Conn->getErrorMsg().'<br>';
}
return false;
}
$insert_id = $this->Conn->getInsertID();
if($insert_id == 0) $insert_id = $this->FieldValues[$this->IDField];
$this->setID($insert_id);
if (!$system_create){
$this->setModifiedFlag();
}
$this->raiseEvent('OnAfterItemCreate');
return true;
}
/**
* Deletes the record from databse
*
* @access public
* @return bool
*/
function Delete($id=null)
{
if( isset($id) ) {
$this->setID($id);
}
if( !$this->raiseEvent('OnBeforeItemDelete') ) return false;
$q = 'DELETE FROM '.$this->TableName.' WHERE '.$this->GetKeyClause('Delete');
if ($this->DisplayQueries)
{
echo get_class($this).' Delete SQL: '.$q.'<br>';
}
$ret = $this->Conn->ChangeQuery($q);
$this->setModifiedFlag();
$this->raiseEvent('OnAfterItemDelete');
return $ret;
}
/**
* Sets new name for item in case if it is beeing copied
* in same table
*
* @param array $master Table data from TempHandler
* @param int $foreign_key ForeignKey value to filter name check query by
* @access private
*/
function NameCopy($master=null, $foreign_key=null)
{
$title_field = $this->Application->getUnitOption($this->Prefix, 'TitleField');
if (!$title_field || isset($this->CalculatedFields[$title_field]) ) return;
$new_name = $this->GetDBField($title_field);
$original_checked = false;
do {
if ( preg_match('/Copy ([0-9]*) *of (.*)/', $new_name, $regs) ) {
$new_name = 'Copy '.($regs[1]+1).' of '.$regs[2];
}
elseif ($original_checked) {
$new_name = 'Copy of '.$new_name;
}
// if we are cloning in temp table this will look for names in temp table,
// since object' TableName contains correct TableName (for temp also!)
// if we are cloning live - look in live
$query = 'SELECT '.$title_field.' FROM '.$this->TableName.'
WHERE '.$title_field.' = '.$this->Conn->qstr($new_name);
if (getArrayValue($master, 'ForeignKey') && isset($foreign_key)) {
$query .= ' AND '.$master['ForeignKey'].' = '.$foreign_key;
}
$res = $this->Conn->GetOne($query);
/*// if not found in live table, check in temp table if applicable
if ($res === false && $object->Special == 'temp') {
$query = 'SELECT '.$name_field.' FROM '.$this->GetTempName($master['TableName']).'
WHERE '.$name_field.' = '.$this->Conn->qstr($new_name);
$res = $this->Conn->GetOne($query);
}*/
$original_checked = true;
} while ($res !== false);
$this->SetDBField($title_field, $new_name);
}
function raiseEvent($name, $id=null)
{
if( !isset($id) ) $id = $this->GetID();
$event = new kEvent( Array('name'=>$name,'prefix'=>$this->Prefix,'special'=>$this->Special) );
$event->setEventParam('id', $id);
$this->Application->HandleEvent($event);
return $event->status == erSUCCESS ? true : false;
}
/**
* Set's new ID for item
*
* @param int $new_id
* @access public
*/
function setID($new_id)
{
$this->ID=$new_id;
$this->SetDBField($this->IDField,$new_id);
}
/**
* Generate and set new temporary id
*
* @access private
*/
function setTempID()
{
$new_id = (int)$this->Conn->GetOne('SELECT MIN('.$this->IDField.') FROM '.$this->TableName);
if($new_id > 0) $new_id = 0;
--$new_id;
$this->Conn->Query('UPDATE '.$this->TableName.' SET `'.$this->IDField.'` = '.$new_id.' WHERE `'.$this->IDField.'` = '.$this->GetID());
$this->SetID($new_id);
}
/**
* Set's modification flag for main prefix of current prefix to true
*
* @access private
* @author Alexey
*/
function setModifiedFlag()
{
$main_prefix = $this->Application->GetTopmostPrefix($this->Prefix);
$this->Application->StoreVar($main_prefix.'_modified', '1');
}
/**
* Returns ID of currently processed record
*
* @return int
* @access public
*/
function GetID()
{
return $this->ID;
}
/**
* Generates ID for new items before inserting into database
*
* @return int
* @access private
*/
function generateID()
{
return 0;
}
+
+ /**
+ * Returns true if item was loaded successfully by Load method
+ *
+ * @return bool
+ */
+ function isLoaded()
+ {
+ return $this->Loaded;
+ }
}
?>
\ No newline at end of file
Property changes on: trunk/core/kernel/db/dbitem.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.8
\ No newline at end of property
+1.9
\ No newline at end of property
Index: trunk/core/units/users/users_event_handler.php
===================================================================
--- trunk/core/units/users/users_event_handler.php (revision 2377)
+++ trunk/core/units/users/users_event_handler.php (revision 2378)
@@ -1,717 +1,717 @@
<?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);
}
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)
+ 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.21
\ No newline at end of property
+1.22
\ No newline at end of property

Event Timeline