Page MenuHomeIn-Portal Phabricator

in-portal
No OneTemporary

File Metadata

Created
Mon, Feb 3, 7:12 AM

in-portal

This file is larger than 256 KB, so syntax highlighting was skipped.
Index: branches/RC/core/kernel/session/session.php
===================================================================
--- branches/RC/core/kernel/session/session.php (revision 10004)
+++ branches/RC/core/kernel/session/session.php (revision 10005)
@@ -1,970 +1,984 @@
<?php
/*
The session works the following way:
1. When a visitor loads a page from the site the script checks if cookies_on varibale has been passed to it as a cookie.
2. If it has been passed, the script tries to get Session ID (SID) from the request:
3. Depending on session mode the script is getting SID differently.
The following modes are available:
smAUTO - Automatic mode: if cookies are on at the client side, the script relays only on cookies and
ignore all other methods of passing SID.
If cookies are off at the client side, the script relays on SID passed through query string
and referal passed by the client. THIS METHOD IS NOT 100% SECURE, as long as attacker may
get SID and substitude referal to gain access to user' session. One of the faults of this method
is that the session is only created when the visitor clicks the first link on the site, so
there is NO session at the first load of the page. (Actually there is a session, but it gets lost
after the first click because we do not use SID in query string while we are not sure if we need it)
smCOOKIES_ONLY - Cookies only: in this mode the script relays solely on cookies passed from the browser
and ignores all other methods. In this mode there is no way to use sessions for clients
without cookies support or cookies support disabled. The cookies are stored with the
full domain name and path to base-directory of script installation.
smGET_ONLY - GET only: the script will not set any cookies and will use only SID passed in
query string using GET, it will also check referal. The script will set SID at the
first load of the page
smCOOKIES_AND_GET - Combined mode: the script will use both cookies and GET right from the start. If client has
cookies enabled, the script will check SID stored in cookie and passed in query string, and will
use this SID only if both cookie and query string matches. However if cookies are disabled on the
client side, the script will work the same way as in GET_ONLY mode.
4. After the script has the SID it tries to load it from the Storage (default is database)
5. If such SID is found in the database, the script checks its expiration time. If session is not expired, it updates
its expiration, and resend the cookie (if applicable to session mode)
6. Then the script loads all the data (session variables) pertaining to the SID.
Usage:
$session = new Session(smAUTO); //smAUTO is default, you could just leave the brackets empty, or provide another mode
$session->SetCookieDomain('my.domain.com');
$session->SetCookiePath('/myscript');
$session->SetCookieName('my_sid_cookie');
$session->SetGETName('sid');
$session->InitSession();
...
//link output:
echo "<a href='index.php?'". ( $session->NeedQueryString() ? 'sid='.$session->SID : '' ) .">My Link</a>";
*/
//Implements session storage in the database
class SessionStorage extends kDBBase {
var $Expiration;
var $SessionTimeout=0;
var $DirectVars = Array();
var $ChangedDirectVars = Array();
var $PersistentVars = Array ();
var $OriginalData=Array();
var $TimestampField;
var $SessionDataTable;
var $DataValueField;
var $DataVarField;
function Init($prefix,$special)
{
parent::Init($prefix,$special);
$this->setTableName('sessions');
$this->setIDField('sid');
$this->TimestampField = 'expire';
$this->SessionDataTable = 'SessionData';
$this->DataValueField = 'value';
$this->DataVarField = 'var';
}
function setSessionTimeout($new_timeout)
{
$this->SessionTimeout = $new_timeout;
}
function StoreSession(&$session, $additional_fields = Array())
{
if (defined('IS_INSTALL') && IS_INSTALL && !$this->Application->TableFound($this->TableName)) {
return false;
}
$fields_hash = Array (
$this->IDField => $session->SID,
$this->TimestampField => $session->Expiration
);
$this->Conn->doInsert($fields_hash, $this->TableName);
foreach ($additional_fields as $field_name => $field_value) {
$this->SetField($session, $field_name, $field_value);
}
}
function DeleteSession(&$session)
{
$query = ' DELETE FROM '.$this->TableName.' WHERE '.$this->IDField.' = '.$this->Conn->qstr($session->SID);
$this->Conn->Query($query);
$query = ' DELETE FROM '.$this->SessionDataTable.' WHERE '.$this->IDField.' = '.$this->Conn->qstr($session->SID);
$this->Conn->Query($query);
$this->OriginalData = Array();
}
function UpdateSession(&$session, $timeout=0)
{
$this->SetField($session, $this->TimestampField, $session->Expiration);
$query = ' UPDATE '.$this->TableName.' SET '.$this->TimestampField.' = '.$session->Expiration.' WHERE '.$this->IDField.' = '.$this->Conn->qstr($session->SID);
$this->Conn->Query($query);
}
function LocateSession($sid)
{
$query = ' SELECT * FROM '.$this->TableName.' WHERE '.$this->IDField.' = '.$this->Conn->qstr($sid);
$result = $this->Conn->GetRow($query);
if($result===false) return false;
$this->DirectVars = $result;
$this->Expiration = $result[$this->TimestampField];
return true;
}
function GetExpiration()
{
return $this->Expiration;
}
function LoadData(&$session)
{
$query = 'SELECT '.$this->DataValueField.','.$this->DataVarField.' FROM '.$this->SessionDataTable.' WHERE '.$this->IDField.' = '.$this->Conn->qstr($session->SID);
$this->OriginalData = $this->Conn->GetCol($query, $this->DataVarField);
return $this->OriginalData;
}
/**
* Enter description here...
*
* @param Session $session
* @param string $var_name
* @param mixed $default
*/
function GetField(&$session, $var_name, $default = false)
{
return isset($this->DirectVars[$var_name]) ? $this->DirectVars[$var_name] : $default;
//return $this->Conn->GetOne('SELECT '.$var_name.' FROM '.$this->TableName.' WHERE `'.$this->IDField.'` = '.$this->Conn->qstr($session->GetID()) );
}
function SetField(&$session, $var_name, $value)
{
$value_changed = !isset($this->DirectVars[$var_name]) || ($this->DirectVars[$var_name] != $value);
if ($value_changed) {
$this->DirectVars[$var_name] = $value;
$this->ChangedDirectVars[] = $var_name;
$this->ChangedDirectVars = array_unique($this->ChangedDirectVars);
}
//return $this->Conn->Query('UPDATE '.$this->TableName.' SET '.$var_name.' = '.$this->Conn->qstr($value).' WHERE '.$this->IDField.' = '.$this->Conn->qstr($session->GetID()) );
}
function SaveData(&$session)
{
if(!$session->SID) return false; // can't save without sid
$ses_data = $session->Data->GetParams();
$replace = '';
foreach ($ses_data as $key => $value)
{
if ( isset($this->OriginalData[$key]) && $this->OriginalData[$key] == $value)
{
continue; //skip unchanged session data
}
else
{
$replace .= sprintf("(%s, %s, %s),",
$this->Conn->qstr($session->SID),
$this->Conn->qstr($key),
$this->Conn->qstr($value));
}
}
$replace = rtrim($replace, ',');
if ($replace != '') {
$query = ' REPLACE INTO '.$this->SessionDataTable. ' ('.$this->IDField.', '.$this->DataVarField.', '.$this->DataValueField.') VALUES '.$replace;
$this->Conn->Query($query);
}
if ($this->ChangedDirectVars) {
$changes = array();
foreach ($this->ChangedDirectVars as $var) {
$changes[] = $var.' = '.$this->Conn->qstr($this->DirectVars[$var]);
}
$query = 'UPDATE '.$this->TableName.' SET '.implode(',', $changes).' WHERE '.$this->IDField.' = '.$this->Conn->qstr($session->GetID());
$this->Conn->Query($query);
}
}
function RemoveFromData(&$session, $var)
{
$query = 'DELETE FROM '.$this->SessionDataTable.' WHERE '.$this->IDField.' = '.$this->Conn->qstr($session->SID).
' AND '.$this->DataVarField.' = '.$this->Conn->qstr($var);
$this->Conn->Query($query);
unset($this->OriginalData[$var]);
}
function GetFromData(&$session, $var)
{
return getArrayValue($this->OriginalData, $var);
}
function GetExpiredSIDs()
{
$query = ' SELECT '.$this->IDField.' FROM '.$this->TableName.' WHERE '.$this->TimestampField.' > '.adodb_mktime();
return $this->Conn->GetCol($query);
}
function DeleteExpired()
{
$expired_sids = $this->GetExpiredSIDs();
if ($expired_sids) {
$where_clause=' WHERE '.$this->IDField.' IN ("'.implode('","',$expired_sids).'")';
$sql = 'DELETE FROM '.$this->SessionDataTable.$where_clause;
$this->Conn->Query($sql);
$sql = 'DELETE FROM '.$this->TableName.$where_clause;
$this->Conn->Query($sql);
// delete debugger ouputs left of expired sessions
foreach ($expired_sids as $expired_sid) {
$debug_file = KERNEL_PATH.'/../cache/debug_@'.$expired_sid.'@.txt';
if (file_exists($debug_file)) {
@unlink($debug_file);
}
}
}
return $expired_sids;
}
function LoadPersistentVars(&$session)
{
$user_id = $session->RecallVar('user_id');
if ($user_id != -2) {
// root & normal users
$sql = 'SELECT VariableValue, VariableName
FROM '.TABLE_PREFIX.'PersistantSessionData
WHERE PortalUserId = '.$user_id;
$this->PersistentVars = $this->Conn->GetCol($sql, 'VariableName');
}
else {
$this->PersistentVars = Array ();
}
}
function StorePersistentVar(&$session, $var_name, $var_value)
{
$user_id = $session->RecallVar('user_id');
if ($user_id == -2 || $user_id === false) {
// -2 (when not logged in), false (when after u:OnLogout event)
return ;
}
$this->PersistentVars[$var_name] = $var_value;
$key_clause = 'PortalUserId = '.$user_id.' AND VariableName = '.$this->Conn->qstr($var_name);
$sql = 'SELECT VariableValue
FROM '.TABLE_PREFIX.'PersistantSessionData
WHERE '.$key_clause;
$record_found = $this->Conn->GetOne($sql);
$fields_hash = Array (
'PortalUserId' => $user_id,
'VariableName' => $var_name,
'VariableValue' => $var_value,
);
if ($record_found) {
$this->Conn->doUpdate($fields_hash, TABLE_PREFIX.'PersistantSessionData', $key_clause);
}
else {
$this->Conn->doInsert($fields_hash, TABLE_PREFIX.'PersistantSessionData');
}
}
function RecallPersistentVar(&$session, $var_name, $default = false)
{
if (isset($this->PersistentVars[$var_name])) {
return $this->PersistentVars[$var_name];
}
elseif ($default == '_USE_DEFAULT_USER_DATA_') {
$default_user_id = $this->Application->ConfigValue('DefaultSettingsUserId');
if (!$default_user_id) $default_user_id = -1;
$sql = 'SELECT VariableValue, VariableName
FROM '.TABLE_PREFIX.'PersistantSessionData
WHERE VariableName = '.$this->Conn->qstr($var_name).' AND PortalUserId = '.$default_user_id;
$value = $this->Conn->GetOne($sql);
if ($value !== false) {
$this->PersistentVars[$var_name] = $value;
$this->StorePersistentVar($session, $var_name, $value); //storing it, so next time we don't load default user setting
}
return $value;
}
else return $default;
}
function RemovePersistentVar(&$session, $var_name)
{
unset($this->PersistentVars[$var_name]);
$user_id = $session->RecallVar('user_id');
if ($user_id != -2) {
$sql = 'DELETE FROM '.TABLE_PREFIX.'PersistantSessionData
WHERE PortalUserId = '.$user_id.' AND VariableName = '.$this->Conn->qstr($var_name);
$this->Conn->Query($sql);
}
}
}
define('smAUTO', 1);
define('smCOOKIES_ONLY', 2);
define('smGET_ONLY', 3);
define('smCOOKIES_AND_GET', 4);
class Session extends kBase {
var $Checkers;
var $Mode;
var $OriginalMode = null;
var $GETName = 'sid';
var $CookiesEnabled = true;
var $CookieName = 'sid';
var $CookieDomain;
var $CookiePath;
var $CookieSecure = 0;
var $SessionTimeout = 3600;
var $Expiration;
var $SID;
/**
* Enter description here...
*
* @var SessionStorage
*/
var $Storage;
var $CachedNeedQueryString = null;
var $Data;
function Session($mode=smAUTO)
{
parent::kBase();
$this->SetMode($mode);
}
function SetMode($mode)
{
$this->Mode = $mode;
$this->CachedNeedQueryString = null;
$this->CachedSID = null;
}
function SetCookiePath($path)
{
$this->CookiePath = $path;
}
function SetCookieDomain($domain)
{
$this->CookieDomain = '.'.ltrim($domain, '.');
}
function SetGETName($get_name)
{
$this->GETName = $get_name;
}
function SetCookieName($cookie_name)
{
$this->CookieName = $cookie_name;
}
function InitStorage($special)
{
$this->Storage =& $this->Application->recallObject('SessionStorage.'.$special);
$this->Storage->setSessionTimeout($this->SessionTimeout);
}
function Init($prefix,$special)
{
parent::Init($prefix,$special);
$this->CheckIfCookiesAreOn();
if ($this->CookiesEnabled) $_COOKIE['cookies_on'] = 1;
$this->Checkers = Array();
$this->InitStorage($special);
$this->Data = new Params();
$tmp_sid = $this->GetPassedSIDValue();
$check = $this->Check();
if( !(defined('IS_INSTALL') && IS_INSTALL) )
{
$expired_sids = $this->DeleteExpired();
if ( ( $expired_sids && in_array($tmp_sid,$expired_sids) ) || ( $tmp_sid && !$check ) ) {
$this->SetSession();
$this->Application->HandleEvent($event, 'u:OnSessionExpire');
return ;
}
}
if ($check) {
$this->SID = $this->GetPassedSIDValue();
$this->Refresh();
$this->LoadData();
}
else {
$this->SetSession();
}
if (!is_null($this->OriginalMode)) $this->SetMode($this->OriginalMode);
}
function IsHTTPSRedirect()
{
$http_referer = getArrayValue($_SERVER, 'HTTP_REFERER');
return (
( PROTOCOL == 'https://' && preg_match('#http:\/\/#', $http_referer) )
||
( PROTOCOL == 'http://' && preg_match('#https:\/\/#', $http_referer) )
);
}
function CheckReferer($for_cookies=0)
{
if (!$for_cookies) {
if ( !$this->Application->ConfigValue('SessionReferrerCheck') || $_SERVER['REQUEST_METHOD'] != 'POST') {
return true;
}
}
$path = preg_replace('/admin[\/]{0,1}$/', '', $this->CookiePath); // removing /admin for compatability with in-portal (in-link/admin/add_link.php)
$reg = '#^'.preg_quote(PROTOCOL.ltrim($this->CookieDomain, '.').$path).'#';
return preg_match($reg, getArrayValue($_SERVER, 'HTTP_REFERER') ) || (defined('IS_POPUP') && IS_POPUP);
}
/*function CheckDuplicateCookies()
{
if (isset($_SERVER['HTTP_COOKIE'])) {
$cookie_str = $_SERVER['HTTP_COOKIE'];
$cookies = explode('; ', $cookie_str);
$all_cookies = array();
foreach ($cookies as $cookie) {
list($name, $value) = explode('=', $cookie);
if (isset($all_cookies[$name])) {
//double cookie name!!!
$this->RemoveCookie($name);
}
else $all_cookies[$name] = $value;
}
}
}
function RemoveCookie($name)
{
$path = $_SERVER['PHP_SELF'];
$path_parts = explode('/', $path);
$cur_path = '';
setcookie($name, false, null, $cur_path);
foreach ($path_parts as $part) {
$cur_path .= $part;
setcookie($name, false, null, $cur_path);
$cur_path .= '/';
setcookie($name, false, null, $cur_path);
}
}*/
function CheckIfCookiesAreOn()
{
// $this->CheckDuplicateCookies();
if ($this->Mode == smGET_ONLY)
{
//we don't need to bother checking if we would not use it
$this->CookiesEnabled = false;
return;
}
$http_query =& $this->Application->recallObject('HTTPQuery');
$cookies_on = isset($http_query->Cookie['cookies_on']); // not good here
$get_sid = getArrayValue($http_query->Get, $this->GETName);
if ($this->IsHTTPSRedirect() && $get_sid) { //Redirect from http to https on different domain
$this->OriginalMode = $this->Mode;
$this->SetMode(smGET_ONLY);
}
if (!$cookies_on || $this->IsHTTPSRedirect()) {
//If referer is our server, but we don't have our cookies_on, it's definetly off
$is_install = defined('IS_INSTALL') && IS_INSTALL;
if (!$is_install && $this->CheckReferer(1) && !$this->Application->GetVar('admin') && !$this->IsHTTPSRedirect()) {
$this->CookiesEnabled = false;
}
else {
//Otherwise we still suppose cookies are on, because may be it's the first time user visits the site
//So we send cookies on to get it next time (when referal will tell us if they are realy off
$this->SetCookie('cookies_on', 1, adodb_mktime() + 31104000); //one year should be enough
}
}
else
$this->CookiesEnabled = true;
return $this->CookiesEnabled;
}
/**
* Sets cookie for current site using path and domain
*
* @param string $name
* @param mixed $value
* @param int $expires
*/
function SetCookie($name, $value, $expires = null)
{
setcookie($name, $value, $expires, $this->CookiePath, $this->CookieDomain, $this->CookieSecure);
}
function Check()
{
// we should check referer if cookies are disabled, and in combined mode
// auto mode would detect cookies, get only mode would turn it off - so we would get here
// and we don't care about referal in cookies only mode
if ( $this->Mode != smCOOKIES_ONLY && (!$this->CookiesEnabled || $this->Mode == smCOOKIES_AND_GET) ) {
if (!$this->CheckReferer())
return false;
}
$sid = $this->GetPassedSIDValue();
if (empty($sid)) return false;
//try to load session by sid, if everything is fine
$result = $this->LoadSession($sid);
return $result;
}
function LoadSession($sid)
{
if( $this->Storage->LocateSession($sid) ) {
//if we have session with such SID - get its expiration
$this->Expiration = $this->Storage->GetExpiration();
//If session has expired
if ($this->Expiration < adodb_mktime()) return false;
//Otherwise it's ok
return true;
}
else //fake or deleted due to expiration SID
return false;
}
function GetPassedSIDValue($use_cache = 1)
{
if (!empty($this->CachedSID) && $use_cache) return $this->CachedSID;
$http_query =& $this->Application->recallObject('HTTPQuery');
$get_sid = getArrayValue($http_query->Get, $this->GETName);
if ($this->Application->GetVar('admin') == 1 && $get_sid) {
$sid = $get_sid;
}
else {
switch ($this->Mode) {
case smAUTO:
//Cookies has the priority - we ignore everything else
$sid = $this->CookiesEnabled ? $this->GetSessionCookie() : $get_sid;
break;
case smCOOKIES_ONLY:
$sid = $this->GetSessionCookie();
break;
case smGET_ONLY:
$sid = $get_sid;
break;
case smCOOKIES_AND_GET:
$cookie_sid = $this->GetSessionCookie();
//both sids should match if cookies are enabled
if (!$this->CookiesEnabled || ($cookie_sid == $get_sid))
{
$sid = $get_sid; //we use get here just in case cookies are disabled
}
else
{
$sid = '';
}
break;
}
}
$this->CachedSID = $sid;
return $this->CachedSID;
}
/**
* Returns session id
*
* @return int
* @access public
*/
function GetID()
{
return $this->SID;
}
/**
* Generates new session id
*
* @return int
* @access private
*/
function GenerateSID()
{
list($usec, $sec) = explode(" ",microtime());
$sid_part_1 = substr($usec, 4, 4);
$sid_part_2 = mt_rand(1,9);
$sid_part_3 = substr($sec, 6, 4);
$digit_one = substr($sid_part_1, 0, 1);
if ($digit_one == 0) {
$digit_one = mt_rand(1,9);
$sid_part_1 = ereg_replace("^0","",$sid_part_1);
$sid_part_1=$digit_one.$sid_part_1;
}
$this->setSID($sid_part_1.$sid_part_2.$sid_part_3);
return $this->SID;
}
/**
* Set's new session id
*
* @param int $new_sid
* @access private
*/
function setSID($new_sid)
{
$this->SID=$new_sid;
$this->Application->SetVar($this->GETName,$new_sid);
}
function SetSession()
{
$this->GenerateSID();
$this->Expiration = adodb_mktime() + $this->SessionTimeout;
switch ($this->Mode) {
case smAUTO:
if ($this->CookiesEnabled) {
$this->SetSessionCookie();
}
break;
case smGET_ONLY:
break;
case smCOOKIES_ONLY:
case smCOOKIES_AND_GET:
$this->SetSessionCookie();
break;
}
$this->Storage->StoreSession($this);
if ($this->Application->IsAdmin() || $this->Special == 'admin') {
$this->StoreVar('admin', 1);
}
if ($this->Special != '') {
// front-session called from admin or otherwise, then save it's data
$this->SaveData();
}
$this->Application->resetCounters('UserSession');
}
/**
* Returns SID from cookie
*
* @return int
*/
function GetSessionCookie()
{
- return isset($this->Application->HttpQuery->Cookie[$this->CookieName]) ? $this->Application->HttpQuery->Cookie[$this->CookieName] : false;
+ $keep_session_on_browser_close = $this->Application->ConfigValue('KeepSessionOnBrowserClose');
+ if (isset($this->Application->HttpQuery->Cookie[$this->CookieName]) &&
+ ( $keep_session_on_browser_close ||
+ (
+ !$keep_session_on_browser_close &&
+ isset($this->Application->HttpQuery->Cookie[$this->CookieName.'_live'])
+ &&
+ $this->Application->HttpQuery->Cookie[$this->CookieName] == $this->Application->HttpQuery->Cookie[$this->CookieName.'_live']
+ )
+ )
+ ) {
+ return $this->Application->HttpQuery->Cookie[$this->CookieName];
+ }
+ return false;
}
/**
* Updates SID in cookie with new value
*
*/
function SetSessionCookie()
{
$this->SetCookie($this->CookieName, $this->SID, $this->Expiration);
+ $this->SetCookie($this->CookieName.'_live', $this->SID);
$_COOKIE[$this->CookieName] = $this->SID; // for compatibility with in-portal
}
/**
* Refreshes session expiration time
*
* @access private
*/
function Refresh()
{
if ($this->CookiesEnabled) $this->SetSessionCookie(); //we need to refresh the cookie
$this->Storage->UpdateSession($this);
}
function Destroy()
{
$this->Storage->DeleteSession($this);
$this->Data = new Params();
$this->SID = '';
if ($this->CookiesEnabled) $this->SetSessionCookie(); //will remove the cookie due to value (sid) is empty
$this->SetSession(); //will create a new session
}
function NeedQueryString($use_cache = 1)
{
if ($this->CachedNeedQueryString != null && $use_cache) return $this->CachedNeedQueryString;
$result = false;
switch ($this->Mode)
{
case smAUTO:
if (!$this->CookiesEnabled) $result = true;
break;
/*case smCOOKIES_ONLY:
break;*/
case smGET_ONLY:
case smCOOKIES_AND_GET:
$result = true;
break;
}
$this->CachedNeedQueryString = $result;
return $result;
}
function LoadData()
{
$this->Data->AddParams($this->Storage->LoadData($this));
}
function PrintSession($comment='')
{
if($this->Application->isDebugMode() && constOn('DBG_SHOW_SESSIONDATA')) {
// dump session data
$this->Application->Debugger->appendHTML('SessionStorage ('.$comment.'):');
$session_data = $this->Data->GetParams();
ksort($session_data);
foreach ($session_data as $session_key => $session_value) {
if (IsSerialized($session_value)) {
$session_data[$session_key] = unserialize($session_value);
}
}
$this->Application->Debugger->dumpVars($session_data);
}
if ($this->Application->isDebugMode() && constOn('DBG_SHOW_PERSISTENTDATA')) {
// dump persistent session data
if ($this->Storage->PersistentVars) {
$this->Application->Debugger->appendHTML('Persistant Session:');
$session_data = $this->Storage->PersistentVars;
ksort($session_data);
foreach ($session_data as $session_key => $session_value) {
if (IsSerialized($session_value)) {
$session_data[$session_key] = unserialize($session_value);
}
}
$this->Application->Debugger->dumpVars($session_data);
}
}
}
function SaveData()
{
if (!$this->Application->GetVar('skip_last_template') && $this->Application->GetVar('ajax') != 'yes') {
$this->SaveLastTemplate( $this->Application->GetVar('t') );
}
$this->PrintSession('after save');
$this->Storage->SaveData($this);
}
function SaveLastTemplate($t)
{
// save last_template
$wid = $this->Application->GetVar('m_wid');
$last_env = $this->getLastTemplateENV($t, Array('m_opener' => 'u'));
$last_template = basename($_SERVER['PHP_SELF']).'|'.substr($last_env, strlen(ENV_VAR_NAME) + 1);
$this->StoreVar(rtrim('last_template_'.$wid, '_'), $last_template);
$last_env = $this->getLastTemplateENV($t, null, false);
$last_template = basename($_SERVER['PHP_SELF']).'|'.substr($last_env, strlen(ENV_VAR_NAME) + 1);
$this->StoreVar(rtrim('last_template_popup_'.$wid, '_'), $last_template);
// save other last... variables for mistical purposes (customizations may be)
$this->StoreVar('last_url', $_SERVER['REQUEST_URI']); // needed by ord:StoreContinueShoppingLink
$this->StoreVar('last_env', substr($last_env, strlen(ENV_VAR_NAME)+1));
// save last_template in persistant session
if (!$wid) {
if ($this->Application->IsAdmin()) {
// only for main window, not popups, not login template, not temp mode (used in adm:MainFrameLink tag)
$temp_mode = false;
$passed = explode(',', $this->Application->GetVar('passed'));
foreach ($passed as $passed_prefix) {
if ($this->Application->GetVar($passed_prefix.'_mode')) {
$temp_mode = true;
break;
}
}
if (!$temp_mode) {
if (isset($this->Application->HttpQuery->Get['section'])) {
// check directly in GET, bacause LinkVar (session -> request) used on these vars
$last_template .= '&section='.$this->Application->GetVar('section').'&module='.$this->Application->GetVar('module');
}
$this->StorePersistentVar('last_template_popup', $last_template);
}
}
elseif ($this->Application->GetVar('admin') == 1) {
$admin_session =& $this->Application->recallObject('Session.admin');
/* @var $admin_ses Session */
$admin_session->StorePersistentVar('last_template_popup', '../'.$last_template);
}
}
}
function getLastTemplateENV($t, $params = null, $encode = true)
{
if (!isset($params)) {
$params = Array ();
}
$params['__URLENCODE__'] = 1; // uses "&" instead of "&amp;" for url part concatenation + replaces "\" to "%5C" (works in HTML)
$ret = $this->Application->BuildEnv($t, $params, 'all');
if (!$encode) {
// cancels 2nd part of replacements, that URLENCODE does
$ret = str_replace('%5C', '\\', $ret);
}
return $ret;
}
function StoreVar($name, $value)
{
$this->Data->Set($name, $value);
}
function StorePersistentVar($name, $value)
{
$this->Storage->StorePersistentVar($this, $name, $value);
}
function LoadPersistentVars()
{
$this->Storage->LoadPersistentVars($this);
}
function StoreVarDefault($name, $value)
{
$tmp = $this->RecallVar($name);
if($tmp === false || $tmp == '')
{
$this->StoreVar($name, $value);
}
}
function RecallVar($name, $default = false)
{
$ret = $this->Data->Get($name);
return ($ret === false) ? $default : $ret;
}
function RecallPersistentVar($name, $default = false)
{
return $this->Storage->RecallPersistentVar($this, $name, $default);
}
function RemoveVar($name)
{
$this->Storage->RemoveFromData($this, $name);
$this->Data->Remove($name);
}
function RemovePersistentVar($name)
{
return $this->Storage->RemovePersistentVar($this, $name);
}
/**
* Ignores session varible value set before
*
* @param string $name
*/
function RestoreVar($name)
{
return $this->StoreVar($name, $this->Storage->GetFromData($this, $name));
}
function GetField($var_name, $default = false)
{
return $this->Storage->GetField($this, $var_name, $default);
}
function SetField($var_name, $value)
{
$this->Storage->SetField($this, $var_name, $value);
}
/**
* Deletes expired sessions
*
* @return Array expired sids if any
* @access private
*/
function DeleteExpired()
{
return $this->Storage->DeleteExpired();
}
/**
* Allows to check if user in this session is logged in or not
*
* @return bool
*/
function LoggedIn()
{
$user_id = $this->RecallVar('user_id');
$ret = $user_id > 0;
if ($this->RecallVar('admin') == 1 && ($user_id == -1)) {
$ret = true;
}
return $ret;
}
}
?>
\ No newline at end of file
Property changes on: branches/RC/core/kernel/session/session.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.59.2.4
\ No newline at end of property
+1.59.2.5
\ No newline at end of property
Index: branches/RC/core/kernel/db/db_event_handler.php
===================================================================
--- branches/RC/core/kernel/db/db_event_handler.php (revision 10004)
+++ branches/RC/core/kernel/db/db_event_handler.php (revision 10005)
@@ -1,2213 +1,2228 @@
<?php
define('EH_CUSTOM_PROCESSING_BEFORE',1);
define('EH_CUSTOM_PROCESSING_AFTER',2);
/**
* Note:
* 1. When adressing variables from submit containing
* Prefix_Special as part of their name use
* $event->getPrefixSpecial(true) instead of
* $event->Prefix_Special as usual. This is due PHP
* is converting "." symbols in variable names during
* submit info "_". $event->getPrefixSpecial optional
* 1st parameter returns correct corrent Prefix_Special
* for variables beeing submitted such way (e.g. variable
* name that will be converted by PHP: "users.read_only_id"
* will be submitted as "users_read_only_id".
*
* 2. When using $this->Application-LinkVar on variables submitted
* from form which contain $Prefix_Special then note 1st item. Example:
* LinkVar($event->getPrefixSpecial(true).'_varname',$event->Prefix_Special.'_varname')
*
*/
/**
* EventHandler that is used to process
* any database related events
*
*/
class kDBEventHandler extends kEventHandler {
/**
* Description
*
* @var kDBConnection
* @access public
*/
var $Conn;
/**
* Adds ability to address db connection
*
* @return kDBEventHandler
* @access public
*/
function kDBEventHandler()
{
parent::kBase();
$this->Conn =& $this->Application->GetADODBConnection();
}
/**
* Checks permissions of user
*
* @param kEvent $event
*/
function CheckPermission(&$event)
{
if (!$this->Application->IsAdmin()) {
$allow_events = Array('OnSearch', 'OnSearchReset', 'OnNew');
if (in_array($event->Name, $allow_events)) {
// allow search on front
return true;
}
}
$section = $event->getSection();
if (!preg_match('/^CATEGORY:(.*)/', $section)) {
// only if not category item events
if ((substr($event->Name, 0, 9) == 'OnPreSave') || ($event->Name == 'OnSave')) {
if ($this->isNewItemCreate($event)) {
return $this->Application->CheckPermission($section.'.add', 1);
}
else {
return $this->Application->CheckPermission($section.'.add', 1) || $this->Application->CheckPermission($section.'.edit', 1);
}
}
}
if ($event->Name == 'OnPreCreate') {
// save category_id before item create (for item category selector not to destroy permission checking category)
$this->Application->LinkVar('m_cat_id');
}
return parent::CheckPermission($event);
}
/**
* Allows to override standart permission mapping
*
*/
function mapPermissions()
{
parent::mapPermissions();
$permissions = Array(
'OnLoad' => Array('self' => 'view', 'subitem' => 'view'),
'OnItemBuild' => Array('self' => 'view', 'subitem' => 'view'),
'OnBuild' => Array('self' => true),
'OnNew' => Array('self' => 'add', 'subitem' => 'add|edit'),
'OnCreate' => Array('self' => 'add', 'subitem' => 'add|edit'),
'OnUpdate' => Array('self' => 'edit', 'subitem' => 'add|edit'),
'OnSetPrimary' => Array('self' => 'add|edit', 'subitem' => 'add|edit'),
'OnDelete' => Array('self' => 'delete', 'subitem' => 'add|edit'),
'OnMassDelete' => Array('self' => 'delete', 'subitem' => 'add|edit'),
'OnMassClone' => Array('self' => 'add', 'subitem' => 'add|edit'),
'OnCut' => array('self'=>'edit', 'subitem' => 'edit'),
'OnCopy' => array('self'=>'edit', 'subitem' => 'edit'),
'OnPaste' => array('self'=>'edit', 'subitem' => 'edit'),
'OnSelectItems' => Array('self' => 'add|edit', 'subitem' => 'add|edit'),
'OnProcessSelected' => Array('self' => 'add|edit', 'subitem' => 'add|edit'),
'OnSelectUser' => Array('self' => 'add|edit', 'subitem' => 'add|edit'),
'OnMassApprove' => Array('self' => 'advanced:approve|edit', 'subitem' => 'advanced:approve|add|edit'),
'OnMassDecline' => Array('self' => 'advanced:decline|edit', 'subitem' => 'advanced:decline|add|edit'),
'OnMassMoveUp' => Array('self' => 'advanced:move_up|edit', 'subitem' => 'advanced:move_up|add|edit'),
'OnMassMoveDown' => Array('self' => 'advanced:move_down|edit', 'subitem' => 'advanced:move_down|add|edit'),
'OnPreCreate' => Array('self' => 'add|add.pending', 'subitem' => 'edit|edit.pending'),
'OnEdit' => Array('self' => 'edit|edit.pending', 'subitem' => 'edit|edit.pending'),
'OnExport' => Array('self' => 'view|advanced:export'),
'OnExportBegin' => Array('self' => 'view|advanced:export'),
'OnExportProgress' => Array('self' => 'view|advanced:export'),
// theese event do not harm, but just in case check them too :)
'OnCancelEdit' => Array('self' => true, 'subitem' => true),
'OnCancel' => Array('self' => true, 'subitem' => true),
'OnReset' => Array('self' => true, 'subitem' => true),
'OnSetSorting' => Array('self' => true, 'subitem' => true),
'OnSetSortingDirect' => Array('self' => true, 'subitem' => true),
'OnSetFilter' => Array('self' => true, 'subitem' => true),
'OnApplyFilters' => Array('self' => true, 'subitem' => true),
'OnRemoveFilters' => Array('self' => true, 'subitem' => true),
'OnSetFilterPattern' => Array('self' => true, 'subitem' => true),
'OnSetPerPage' => Array('self' => true, 'subitem' => true),
'OnSearch' => Array('self' => true, 'subitem' => true),
'OnSearchReset' => Array('self' => true, 'subitem' => true),
'OnGoBack' => Array('self' => true, 'subitem' => true),
// it checks permission itself since flash uploader does not send cookies
'OnUploadFile' => Array('self'=>true, 'subitem'=>true),
'OnViewFile' => Array('self'=>true, 'subitem'=>true),
'OnSaveWidths' => Array('self'=>true, 'subitem'=>true),
+
+ 'OnValidateMInputFields' => Array('self'=>'view'),
);
$this->permMapping = array_merge($this->permMapping, $permissions);
}
function mapEvents()
{
$events_map = Array(
'OnRemoveFilters' => 'FilterAction',
'OnApplyFilters' => 'FilterAction',
'OnMassApprove'=>'iterateItems',
'OnMassDecline'=>'iterateItems',
'OnMassMoveUp'=>'iterateItems',
'OnMassMoveDown'=>'iterateItems',
);
$this->eventMethods = array_merge($this->eventMethods, $events_map);
}
/**
* Returns ID of current item to be edited
* by checking ID passed in get/post as prefix_id
* or by looking at first from selected ids, stored.
* Returned id is also stored in Session in case
* it was explicitly passed as get/post
*
* @param kEvent $event
* @return int
*/
function getPassedID(&$event)
{
if ($event->getEventParam('raise_warnings') === false) {
$event->setEventParam('raise_warnings', 1);
}
if (preg_match('/^auto-(.*)/', $event->Special, $regs) && $this->Application->prefixRegistred($regs[1])) {
// <inp2:lang.auto-phrase_Field name="DateFormat"/> - returns field DateFormat value from language (LanguageId is extracted from current phrase object)
$main_object =& $this->Application->recallObject($regs[1]);
/* @var $main_object kDBItem */
$id_field = $this->Application->getUnitOption($event->Prefix, 'IDField');
return $main_object->GetDBField($id_field);
}
// 1. get id from post (used in admin)
$ret = $this->Application->GetVar($event->getPrefixSpecial(true).'_id');
if ($ret) {
return $ret;
}
// 2. get id from env (used in front)
$ret = $this->Application->GetVar($event->getPrefixSpecial().'_id');
if ($ret) {
return $ret;
}
// recall selected ids array and use the first one
$ids = $this->Application->GetVar($event->getPrefixSpecial().'_selected_ids');
if ($ids != '') {
$ids = explode(',',$ids);
if ($ids) {
$ret = array_shift($ids);
}
}
else { // if selected ids are not yet stored
$this->StoreSelectedIDs($event);
return $this->Application->GetVar($event->getPrefixSpecial(true).'_id'); // StoreSelectedIDs sets this variable
}
return $ret;
}
/**
* Prepares and stores selected_ids string
* in Session and Application Variables
* by getting all checked ids from grid plus
* id passed in get/post as prefix_id
*
* @param kEvent $event
* @param Array $ids
*
* @return Array ids stored
*/
function StoreSelectedIDs(&$event, $ids = null)
{
$wid = $this->Application->GetTopmostWid($event->Prefix);
$session_name = rtrim($event->getPrefixSpecial().'_selected_ids_'.$wid, '_');
if (isset($ids)) {
// save ids directly if they given
$this->Application->StoreVar($session_name, implode(',', $ids));
return $ids;
}
$ret = Array();
// May be we don't need this part: ?
$passed = $this->Application->GetVar($event->getPrefixSpecial(true).'_id');
if($passed !== false && $passed != '')
{
array_push($ret, $passed);
}
$ids = Array();
// get selected ids from post & save them to session
$items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) );
if($items_info)
{
$id_field = $this->Application->getUnitOption($event->Prefix,'IDField');
foreach($items_info as $id => $field_values)
{
if( getArrayValue($field_values,$id_field) ) array_push($ids,$id);
}
//$ids=array_keys($items_info);
}
$ret = array_unique(array_merge($ret, $ids));
$this->Application->SetVar($event->getPrefixSpecial().'_selected_ids', implode(',',$ret));
$this->Application->LinkVar($event->getPrefixSpecial().'_selected_ids', $session_name);
// This is critical - otherwise getPassedID will return last ID stored in session! (not exactly true)
// this smells... needs to be refactored
$first_id = getArrayValue($ret,0);
if (($first_id === false) && ($event->getEventParam('raise_warnings') == 1)) {
if ($this->Application->isDebugMode()) {
$this->Application->Debugger->appendTrace();
}
trigger_error('Requested ID for prefix <b>'.$event->getPrefixSpecial().'</b> <span class="debug_error">not passed</span>',E_USER_NOTICE);
}
$this->Application->SetVar($event->getPrefixSpecial(true).'_id', $first_id);
return $ret;
}
/**
* Returns stored selected ids as an array
*
* @param kEvent $event
* @param bool $from_session return ids from session (written, when editing was started)
* @return array
*/
function getSelectedIDs(&$event, $from_session = false)
{
if ($from_session) {
$wid = $this->Application->GetTopmostWid($event->Prefix);
$var_name = rtrim($event->getPrefixSpecial().'_selected_ids_'.$wid, '_');
$ret = $this->Application->RecallVar($var_name);
}
else {
$ret = $this->Application->GetVar($event->getPrefixSpecial().'_selected_ids');
}
return explode(',', $ret);
}
/**
* Returs associative array of submitted fields for current item
* Could be used while creating/editing single item -
* meaning on any edit form, except grid edit
*
* @param kEvent $event
*/
function getSubmittedFields(&$event)
{
$items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) );
$field_values = $items_info ? array_shift($items_info) : Array();
return $field_values;
}
/**
* Removes any information about current/selected ids
* from Application variables and Session
*
* @param kEvent $event
*/
function clearSelectedIDs(&$event)
{
$prefix_special = $event->getPrefixSpecial();
$ids = implode(',', $this->getSelectedIDs($event, true));
$event->setEventParam('ids', $ids);
$wid = $this->Application->GetTopmostWid($event->Prefix);
$session_name = rtrim($prefix_special.'_selected_ids_'.$wid, '_');
$this->Application->RemoveVar($session_name);
$this->Application->SetVar($prefix_special.'_selected_ids', '');
$this->Application->SetVar($prefix_special.'_id', ''); // $event->getPrefixSpecial(true).'_id' too may be
}
/*function SetSaveEvent(&$event)
{
$this->Application->SetVar($event->Prefix_Special.'_SaveEvent','OnUpdate');
$this->Application->LinkVar($event->Prefix_Special.'_SaveEvent');
}*/
/**
* Common builder part for Item & List
*
* @param kDBBase $object
* @param kEvent $event
* @access private
*/
function dbBuild(&$object, &$event)
{
$object->Configure( $event->getEventParam('populate_ml_fields') || $this->Application->getUnitOption($event->Prefix, 'PopulateMlFields') );
$this->PrepareObject($object, $event);
// force live table if specified or is original item
$live_table = $event->getEventParam('live_table') || $event->Special == 'original';
if( $this->UseTempTables($event) && !$live_table )
{
$object->SwitchToTemp();
}
// This strange constuction creates hidden field for storing event name in form submit
// It pass SaveEvent to next screen, otherwise after unsuccsefull create it will try to update rather than create
$current_event = $this->Application->GetVar($event->Prefix_Special.'_event');
// $this->Application->setEvent($event->Prefix_Special, $current_event);
$this->Application->setEvent($event->Prefix_Special, '');
$save_event = $this->UseTempTables($event) && $this->Application->GetTopmostPrefix($event->Prefix) == $event->Prefix ? 'OnSave' : 'OnUpdate';
$this->Application->SetVar($event->Prefix_Special.'_SaveEvent',$save_event);
}
/**
* Checks, that currently loaded item is allowed for viewing (non permission-based)
*
* @param kEvent $event
* @return bool
*/
function checkItemStatus(&$event)
{
$status_fields = $this->Application->getUnitOption($event->Prefix,'StatusField');
if (!$status_fields) {
return true;
}
$status_field = array_shift($status_fields);
if ($status_field == 'Status' || $status_field == 'Enabled') {
$object =& $event->getObject();
if (!$object->isLoaded()) {
return true;
}
return $object->GetDBField($status_field) == STATUS_ACTIVE;
}
return true;
}
/**
* Builds item (loads if needed)
*
* @param kEvent $event
* @access protected
*/
function OnItemBuild(&$event)
{
$object =& $event->getObject();
$this->dbBuild($object,$event);
$sql = $this->ItemPrepareQuery($event);
$sql = $this->Application->ReplaceLanguageTags($sql);
$object->setSelectSQL($sql);
// 2. loads if allowed
$auto_load = $this->Application->getUnitOption($event->Prefix,'AutoLoad');
$skip_autload = $event->getEventParam('skip_autoload');
if ($auto_load && !$skip_autload) {
$perm_status = true;
$user_id = $this->Application->RecallVar('user_id');
$event->setEventParam('top_prefix', $this->Application->GetTopmostPrefix($event->Prefix, true));
$status_checked = false;
if ($user_id == -1 || $this->CheckPermission($event)) {
// don't autoload item, when user doesn't have view permission
$this->LoadItem($event);
$status_checked = true;
if ($user_id != -1 && !$this->Application->IsAdmin() && !$this->checkItemStatus($event)) {
$perm_status = false;
}
}
else {
$perm_status = false;
}
if (!$perm_status) {
// when no permission to view item -> redirect to no pemrission template
if ($this->Application->isDebugMode()) {
$this->Application->Debugger->appendTrace();
}
trigger_error('ItemLoad Permission Failed for prefix ['.$event->getPrefixSpecial().'] in <strong>'.($status_checked ? 'checkItemStatus' : 'CheckPermission').'</strong>', E_USER_WARNING);
$next_template = $this->Application->IsAdmin() ? 'no_permission' : $this->Application->ConfigValue('NoPermissionTemplate');
$this->Application->Redirect($next_template, Array('next_template' => $this->Application->GetVar('t')));
}
}
$actions =& $this->Application->recallObject('kActions');
$actions->Set($event->Prefix_Special.'_GoTab', '');
$actions->Set($event->Prefix_Special.'_GoId', '');
}
/**
* Build subtables array from configs
*
* @param kEvent $event
*/
function OnTempHandlerBuild(&$event)
{
$object =& $this->Application->recallObject($event->getPrefixSpecial().'_TempHandler', 'kTempTablesHandler');
/* @var $object kTempTablesHandler */
$object->BuildTables( $event->Prefix, $this->getSelectedIDs($event) );
}
/**
* Enter description here...
*
* @param kEvent $event
* @return unknown
*/
function UseTempTables(&$event)
{
$object = &$event->getObject();
$top_prefix = $this->Application->GetTopmostPrefix($event->Prefix);
$var_names = Array (
$top_prefix,
rtrim($top_prefix.'_'.$event->Special, '_'),
rtrim($top_prefix.'.'.$event->Special, '.'),
);
$var_names = array_unique($var_names);
$temp_mode = false;
foreach ($var_names as $var_name) {
$value = $this->Application->GetVar($var_name.'_mode');
if (substr($value, 0, 1) == 't') {
$temp_mode = true;
break;
}
}
return $temp_mode;
}
/**
* Returns table prefix from event (temp or live)
*
* @param kEvent $event
* @return string
* @todo Needed? Should be refactored (by Alex)
*/
function TablePrefix(&$event)
{
return $this->UseTempTables($event) ? $this->Application->GetTempTablePrefix('prefix:'.$event->Prefix).TABLE_PREFIX : TABLE_PREFIX;
}
/**
* Load item if id is available
*
* @param kEvent $event
*/
function LoadItem(&$event)
{
$object =& $event->getObject();
$id = $this->getPassedID($event);
if ($object->Load($id)) {
$actions =& $this->Application->recallObject('kActions');
$actions->Set($event->Prefix_Special.'_id', $object->GetID() );
}
else {
$object->setID($id);
}
}
/**
* Builds list
*
* @param kEvent $event
* @access protected
*/
function OnListBuild(&$event)
{
$object =& $event->getObject();
/* @var $object kDBList */
$this->dbBuild($object,$event);
$sql = $this->ListPrepareQuery($event);
$sql = $this->Application->ReplaceLanguageTags($sql);
$object->setSelectSQL($sql);
$object->Counted = false; // when requery="1" should re-count records too!
$object->ClearOrderFields(); // prevents duplicate order fields, when using requery="1"
$object->linkToParent( $this->getMainSpecial($event) );
$this->AddFilters($event);
$this->SetCustomQuery($event); // new!, use this for dynamic queries based on specials for ex.
$this->SetPagination($event);
$this->SetSorting($event);
// $object->CalculateTotals(); // Now called in getTotals to avoid extra query
$actions =& $this->Application->recallObject('kActions');
$actions->Set('remove_specials['.$event->Prefix_Special.']', '0');
$actions->Set($event->Prefix_Special.'_GoTab', '');
}
/**
* Get's special of main item for linking with subitem
*
* @param kEvent $event
* @return string
*/
function getMainSpecial(&$event)
{
$special = $event->getEventParam('main_special');
if($special === false || $special == '$main_special')
{
$special = $event->Special;
}
return $special;
}
/**
* Apply any custom changes to list's sql query
*
* @param kEvent $event
* @access protected
* @see OnListBuild
*/
function SetCustomQuery(&$event)
{
}
/**
* Set's new perpage for grid
*
* @param kEvent $event
*/
function OnSetPerPage(&$event)
{
$per_page = $this->Application->GetVar($event->getPrefixSpecial(true).'_PerPage');
$this->Application->StoreVar($event->getPrefixSpecial().'_PerPage', $per_page);
$view_name = $this->Application->RecallVar($event->getPrefixSpecial().'_current_view');
$this->Application->StorePersistentVar($event->getPrefixSpecial().'_PerPage.'.$view_name, $per_page);
}
/**
* Set's correct page for list
* based on data provided with event
*
* @param kEvent $event
* @access private
* @see OnListBuild
*/
function SetPagination(&$event)
{
// get PerPage (forced -> session -> config -> 10)
$per_page = $this->getPerPage($event);
$object =& $event->getObject();
$object->SetPerPage($per_page);
$this->Application->StoreVarDefault($event->getPrefixSpecial().'_Page', 1);
$page = $this->Application->GetVar($event->getPrefixSpecial().'_Page');
if (!$page) {
$page = $this->Application->GetVar($event->getPrefixSpecial(true).'_Page');
}
if (!$page) {
$page = $this->Application->RecallVar($event->getPrefixSpecial().'_Page');
}
else {
$this->Application->StoreVar($event->getPrefixSpecial().'_Page', $page);
}
if( !$event->getEventParam('skip_counting') )
{
$pages = $object->GetTotalPages();
if($page > $pages)
{
$this->Application->StoreVar($event->getPrefixSpecial().'_Page', 1);
$page = 1;
}
}
/*$per_page = $event->getEventParam('per_page');
if ($per_page == 'list_next') {
$cur_page = $page;
$cur_per_page = $per_page;
$object->SetPerPage(1);
$object =& $this->Application->recallObject($event->Prefix);
$cur_item_index = $object->CurrentIndex;
$page = ($cur_page-1) * $cur_per_page + $cur_item_index + 1;
$object->SetPerPage(1);
}*/
$object->SetPage($page);
}
/**
* Returns current per-page setting for list
*
* @param kEvent $event
* @return int
*/
function getPerPage(&$event)
{
// 1. per-page is passed as tag parameter to PrintList, InitList, etc.
$per_page = $event->getEventParam('per_page');
/*if ($per_page == 'list_next') {
$per_page = '';
}*/
// 2. per-page variable name is store into config variable
$config_mapping = $this->Application->getUnitOption($event->Prefix, 'ConfigMapping');
if ($config_mapping) {
switch ( $per_page ){
case 'short_list' :
$per_page = $this->Application->ConfigValue($config_mapping['ShortListPerPage']);
break;
case 'default' :
$per_page = $this->Application->ConfigValue($config_mapping['PerPage']);
break;
}
}
if (!$per_page) {
// per-page is stored to persistent session
$view_name = $this->Application->RecallVar($event->getPrefixSpecial().'_current_view');
$storage_prefix = $event->getEventParam('same_special') ? $event->Prefix : $event->getPrefixSpecial();
$per_page = $this->Application->RecallPersistentVar($storage_prefix.'_PerPage.'.$view_name, '_USE_DEFAULT_USER_DATA_');
if (!$per_page) {
// per-page is stored to current session
$per_page = $this->Application->RecallVar($storage_prefix.'_PerPage');
}
if (!$per_page) {
if ($config_mapping) {
if (!isset($config_mapping['PerPage'])) {
trigger_error('Incorrect mapping of <span class="debug_error">PerPage</span> key in config for prefix <b>'.$event->Prefix.'</b>', E_USER_WARNING);
}
$per_page = $this->Application->ConfigValue($config_mapping['PerPage']);
}
if (!$per_page) {
// none of checked above per-page locations are useful, then try default value
$per_page = 10;
}
}
}
return $per_page;
}
/**
* Set's correct sorting for list
* based on data provided with event
*
* @param kEvent $event
* @access private
* @see OnListBuild
*/
function SetSorting(&$event)
{
$event->setPseudoClass('_List');
$object =& $event->getObject();
$storage_prefix = $event->getEventParam('same_special') ? $event->Prefix : $event->Prefix_Special;
$cur_sort1 = $this->Application->RecallVar($storage_prefix.'_Sort1');
$cur_sort1_dir = $this->Application->RecallVar($storage_prefix.'_Sort1_Dir');
$cur_sort2 = $this->Application->RecallVar($storage_prefix.'_Sort2');
$cur_sort2_dir = $this->Application->RecallVar($storage_prefix.'_Sort2_Dir');
$sorting_configs = $this->Application->getUnitOption($event->Prefix, 'ConfigMapping');
$list_sortings = $this->Application->getUnitOption($event->Prefix, 'ListSortings');
$sorting_prefix = getArrayValue($list_sortings, $event->Special) ? $event->Special : '';
$tag_sort_by = $event->getEventParam('sort_by');
if ($tag_sort_by) {
if ($tag_sort_by == 'random') {
$by = 'RAND()';
$dir = '';
}
else {
list($by, $dir) = explode(',', $tag_sort_by);
}
$object->AddOrderField($by, $dir);
}
if ($sorting_configs && isset ($sorting_configs['DefaultSorting1Field'])){
$list_sortings[$sorting_prefix]['Sorting'] = Array(
$this->Application->ConfigValue($sorting_configs['DefaultSorting1Field']) => $this->Application->ConfigValue($sorting_configs['DefaultSorting1Dir']),
$this->Application->ConfigValue($sorting_configs['DefaultSorting2Field']) => $this->Application->ConfigValue($sorting_configs['DefaultSorting2Dir']),
);
}
// Use default if not specified
if ( !$cur_sort1 || !$cur_sort1_dir)
{
if ( $sorting = getArrayValue($list_sortings, $sorting_prefix, 'Sorting') ) {
reset($sorting);
$cur_sort1 = key($sorting);
$cur_sort1_dir = current($sorting);
if (next($sorting)) {
$cur_sort2 = key($sorting);
$cur_sort2_dir = current($sorting);
}
}
}
if ( $forced_sorting = getArrayValue($list_sortings, $sorting_prefix, 'ForcedSorting') ) {
foreach ($forced_sorting as $field => $dir) {
$object->AddOrderField($field, $dir);
}
}
if($cur_sort1 != '' && $cur_sort1_dir != '')
{
$object->AddOrderField($cur_sort1, $cur_sort1_dir);
}
if($cur_sort2 != '' && $cur_sort2_dir != '')
{
$object->AddOrderField($cur_sort2, $cur_sort2_dir);
}
}
/**
* Add filters found in session
*
* @param kEvent $event
*/
function AddFilters(&$event)
{
$object =& $event->getObject();
$edit_mark = rtrim($this->Application->GetSID().'_'.$this->Application->GetTopmostWid($event->Prefix), '_');
// add search filter
$filter_data = $this->Application->RecallVar($event->getPrefixSpecial().'_search_filter');
if ($filter_data) {
$filter_data = unserialize($filter_data);
foreach ($filter_data as $filter_field => $filter_params) {
$filter_type = ($filter_params['type'] == 'having') ? HAVING_FILTER : WHERE_FILTER;
$filter_value = str_replace(EDIT_MARK, $edit_mark, $filter_params['value']);
$object->addFilter($filter_field, $filter_value, $filter_type, FLT_SEARCH);
}
}
// add custom filter
$view_name = $this->Application->RecallVar($event->getPrefixSpecial().'_current_view');
$custom_filters = $this->Application->RecallPersistentVar($event->getPrefixSpecial().'_custom_filter.'.$view_name);
if ($custom_filters) {
$grid_name = $event->getEventParam('grid');
$custom_filters = unserialize($custom_filters);
if (isset($custom_filters[$grid_name])) {
foreach ($custom_filters[$grid_name] as $field_name => $field_options) {
list ($filter_type, $field_options) = each($field_options);
if (isset($field_options['value']) && $field_options['value']) {
$filter_type = ($field_options['sql_filter_type'] == 'having') ? HAVING_FILTER : WHERE_FILTER;
$filter_value = str_replace(EDIT_MARK, $edit_mark, $field_options['value']);
$object->addFilter($field_name, $filter_value, $filter_type, FLT_CUSTOM);
}
}
}
}
$view_filter = $this->Application->RecallVar($event->getPrefixSpecial().'_view_filter');
if($view_filter)
{
$view_filter = unserialize($view_filter);
$temp_filter =& $this->Application->makeClass('kMultipleFilter');
$filter_menu = $this->Application->getUnitOption($event->Prefix,'FilterMenu');
$group_key = 0; $group_count = count($filter_menu['Groups']);
while($group_key < $group_count)
{
$group_info = $filter_menu['Groups'][$group_key];
$temp_filter->setType( constant('FLT_TYPE_'.$group_info['mode']) );
$temp_filter->clearFilters();
foreach ($group_info['filters'] as $flt_id)
{
$sql_key = getArrayValue($view_filter,$flt_id) ? 'on_sql' : 'off_sql';
if ($filter_menu['Filters'][$flt_id][$sql_key] != '')
{
$temp_filter->addFilter('view_filter_'.$flt_id, $filter_menu['Filters'][$flt_id][$sql_key]);
}
}
$object->addFilter('view_group_'.$group_key, $temp_filter, $group_info['type'] , FLT_VIEW);
$group_key++;
}
}
}
/**
* Set's new sorting for list
*
* @param kEvent $event
* @access protected
*/
function OnSetSorting(&$event)
{
$cur_sort1 = $this->Application->RecallVar($event->Prefix_Special.'_Sort1');
$cur_sort1_dir = $this->Application->RecallVar($event->Prefix_Special.'_Sort1_Dir');
$use_double_sorting = $this->Application->ConfigValue('UseDoubleSorting') !== false ? $this->Application->ConfigValue('UseDoubleSorting') : true;
if ($use_double_sorting) {
$cur_sort2 = $this->Application->RecallVar($event->Prefix_Special.'_Sort2');
$cur_sort2_dir = $this->Application->RecallVar($event->Prefix_Special.'_Sort2_Dir');
}
$passed_sort1 = $this->Application->GetVar($event->getPrefixSpecial(true).'_Sort1');
if ($cur_sort1 == $passed_sort1) {
$cur_sort1_dir = $cur_sort1_dir == 'asc' ? 'desc' : 'asc';
}
else {
if ($use_double_sorting) {
$cur_sort2 = $cur_sort1;
$cur_sort2_dir = $cur_sort1_dir;
}
$cur_sort1 = $passed_sort1;
$cur_sort1_dir = 'asc';
}
$this->Application->StoreVar($event->Prefix_Special.'_Sort1', $cur_sort1);
$this->Application->StoreVar($event->Prefix_Special.'_Sort1_Dir', $cur_sort1_dir);
if ($use_double_sorting) {
$this->Application->StoreVar($event->Prefix_Special.'_Sort2', $cur_sort2);
$this->Application->StoreVar($event->Prefix_Special.'_Sort2_Dir', $cur_sort2_dir);
}
}
/**
* Set sorting directly to session (used for category item sorting (front-end), grid sorting (admin, view menu)
*
* @param kEvent $event
*/
function OnSetSortingDirect(&$event)
{
$combined = $this->Application->GetVar($event->Prefix.'_CombinedSorting');
if ($combined) {
list($field, $dir) = explode('|', $combined);
$this->Application->StoreVar($event->Prefix.'_Sort1', $field);
$this->Application->StoreVar($event->Prefix.'_Sort1_Dir', $dir);
return ;
}
$field_pos = $this->Application->GetVar($event->Prefix.'_SortPos');
$this->Application->LinkVar($event->Prefix.'_Sort'.$field_pos, $event->Prefix.'_Sort'.$field_pos);
$this->Application->LinkVar($event->Prefix.'_Sort'.$field_pos.'_Dir', $event->Prefix.'_Sort'.$field_pos.'_Dir');
}
/**
* Reset grid sorting to default (from config)
*
* @param kEvent $event
*/
function OnResetSorting(&$event)
{
$this->Application->RemoveVar($event->Prefix_Special.'_Sort1');
$this->Application->RemoveVar($event->Prefix_Special.'_Sort1_Dir');
$this->Application->RemoveVar($event->Prefix_Special.'_Sort2');
$this->Application->RemoveVar($event->Prefix_Special.'_Sort2_Dir');
}
/**
* Creates needed sql query to load item,
* if no query is defined in config for
* special requested, then use default
* query
*
* @param kEvent $event
* @access protected
*/
function ItemPrepareQuery(&$event)
{
$sqls = $this->Application->getUnitOption($event->Prefix, 'ItemSQLs', Array ());
$special = array_key_exists($event->Special, $sqls) ? $event->Special : '';
if (!array_key_exists($special, $sqls)) {
// preferred special not found in ItemSQLs -> use analog from ListSQLs
return $this->ListPrepareQuery($event);
}
return $sqls[$special];
}
/**
* Creates needed sql query to load list,
* if no query is defined in config for
* special requested, then use default
* query
*
* @param kEvent $event
* @access protected
*/
function ListPrepareQuery(&$event)
{
$sqls = $this->Application->getUnitOption($event->Prefix, 'ListSQLs', Array ());
return $sqls[ array_key_exists($event->Special, $sqls) ? $event->Special : '' ];
}
/**
* Apply custom processing to item
*
* @param kEvent $event
*/
function customProcessing(&$event, $type)
{
}
/* Edit Events mostly used in Admin */
/**
* Creates new kDBItem
*
* @param kEvent $event
* @access protected
*/
function OnCreate(&$event)
{
$object =& $event->getObject( Array('skip_autoload' => true) );
/* @var $object kDBItem */
$items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) );
if ($items_info) {
list($id,$field_values) = each($items_info);
$object->SetFieldsFromHash($field_values);
}
$this->customProcessing($event,'before');
//look at kDBItem' Create for ForceCreateId description, it's rarely used and is NOT set by default
if( $object->Create($event->getEventParam('ForceCreateId')) )
{
if( $object->IsTempTable() ) $object->setTempID();
$this->customProcessing($event,'after');
$event->status=erSUCCESS;
$event->redirect_params = Array('opener'=>'u');
}
else
{
$event->status = erFAIL;
$event->redirect = false;
$this->Application->SetVar($event->Prefix_Special.'_SaveEvent','OnCreate');
$object->setID($id);
}
}
/**
* Updates kDBItem
*
* @param kEvent $event
* @access protected
*/
function OnUpdate(&$event)
{
$object =& $event->getObject( Array('skip_autoload' => true) );
$items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) );
if($items_info)
{
foreach($items_info as $id => $field_values)
{
$object->Load($id);
$object->SetFieldsFromHash($field_values);
$this->customProcessing($event, 'before');
if( $object->Update($id) )
{
$this->customProcessing($event, 'after');
$event->status=erSUCCESS;
}
else
{
$event->status=erFAIL;
$event->redirect=false;
break;
}
}
}
$event->redirect_params = Array('opener'=>'u');
}
/**
* Delete's kDBItem object
*
* @param kEvent $event
* @access protected
*/
function OnDelete(&$event)
{
if ($this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1)) {
return;
}
$temp =& $this->Application->recallObject($event->getPrefixSpecial().'_TempHandler', 'kTempTablesHandler');
/* @var $temp kTempTablesHandler */
$temp->DeleteItems($event->Prefix, $event->Special, Array($this->getPassedID($event)));
}
/**
* Prepares new kDBItem object
*
* @param kEvent $event
* @access protected
*/
function OnNew(&$event)
{
$object =& $event->getObject( Array('skip_autoload' => true) );
/* @var $object kDBItem */
$object->Clear(0);
$this->Application->SetVar($event->Prefix_Special.'_SaveEvent', 'OnCreate');
$table_info = $object->getLinkedInfo();
$object->SetDBField($table_info['ForeignKey'], $table_info['ParentId']);
$event->redirect = false;
}
/**
* Cancel's kDBItem Editing/Creation
*
* @param kEvent $event
* @access protected
*/
function OnCancel(&$event)
{
$object =& $event->getObject(Array('skip_autoload' => true));
$items_info = $this->Application->GetVar($event->getPrefixSpecial(true));
if ($items_info) {
$delete_ids = Array();
$temp =& $this->Application->recallObject($event->getPrefixSpecial().'_TempHandler', 'kTempTablesHandler');
foreach ($items_info as $id => $field_values) {
$object->Load($id);
// record created for using with selector (e.g. Reviews->Select User), and not validated => Delete it
if ($object->isLoaded() && !$object->Validate() && ($id <= 0) ) {
$delete_ids[] = $id;
}
}
if ($delete_ids) {
$temp->DeleteItems($event->Prefix, $event->Special, $delete_ids);
}
}
$event->redirect_params = Array('opener'=>'u');
}
/**
* Deletes all selected items.
* Automatically recurse into sub-items using temp handler, and deletes sub-items
* by calling its Delete method if sub-item has AutoDelete set to true in its config file
*
* @param kEvent $event
*/
function OnMassDelete(&$event)
{
if ($this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1)) {
return;
}
$event->status=erSUCCESS;
$temp =& $this->Application->recallObject($event->getPrefixSpecial().'_TempHandler', 'kTempTablesHandler');
$ids = $this->StoreSelectedIDs($event);
$event->setEventParam('ids', $ids);
$this->customProcessing($event, 'before');
$ids = $event->getEventParam('ids');
if($ids)
{
$temp->DeleteItems($event->Prefix, $event->Special, $ids);
}
$this->clearSelectedIDs($event);
}
/**
* Sets window id (of first opened edit window) to temp mark in uls
*
* @param kEvent $event
*/
function setTempWindowID(&$event)
{
$mode = $this->Application->GetVar($event->Prefix.'_mode');
if ($mode == 't') {
$wid = $this->Application->GetVar('m_wid');
$this->Application->SetVar($event->Prefix.'_mode', 't'.$wid);
}
}
/**
* Prepare temp tables and populate it
* with items selected in the grid
*
* @param kEvent $event
*/
function OnEdit(&$event)
{
$this->setTempWindowID($event);
$this->StoreSelectedIDs($event);
$var_name = $event->getPrefixSpecial().'_file_pending_actions'.$this->Application->GetVar('m_wid');
$this->Application->RemoveVar($var_name);
$temp =& $this->Application->recallObject($event->getPrefixSpecial().'_TempHandler', 'kTempTablesHandler');
/* @var $temp kTempTablesHandler */
$temp->PrepareEdit();
$event->redirect=false;
}
/**
* Saves content of temp table into live and
* redirects to event' default redirect (normally grid template)
*
* @param kEvent $event
*/
function OnSave(&$event)
{
$event->CallSubEvent('OnPreSave');
if ($event->status == erSUCCESS) {
$skip_master = false;
$temp =& $this->Application->recallObject($event->getPrefixSpecial().'_TempHandler', 'kTempTablesHandler');
if (!$this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1)) {
$live_ids = $temp->SaveEdit($event->getEventParam('master_ids') ? $event->getEventParam('master_ids') : Array());
// Deleteing files scheduled for delete
$var_name = $event->getPrefixSpecial().'_file_pending_actions'.$this->Application->GetVar('m_wid');
$schedule = $this->Application->RecallVar($var_name);
$schedule = $schedule ? unserialize($schedule) : array();
foreach ($schedule as $data) {
if ($data['action'] == 'delete') {
unlink($data['file']);
}
}
if ($live_ids) {
// ensure, that newly created item ids are avalable as if they were selected from grid
// NOTE: only works if main item has subitems !!!
$this->StoreSelectedIDs($event, $live_ids);
}
}
$this->clearSelectedIDs($event);
$event->redirect_params = Array('opener' => 'u');
$this->Application->RemoveVar($event->getPrefixSpecial().'_modified');
// all temp tables are deleted here => all after hooks should think, that it's live mode now
$this->Application->SetVar($event->Prefix.'_mode', '');
}
}
/**
* Cancels edit
* Removes all temp tables and clears selected ids
*
* @param kEvent $event
*/
function OnCancelEdit(&$event)
{
$temp =& $this->Application->recallObject($event->getPrefixSpecial().'_TempHandler', 'kTempTablesHandler');
$temp->CancelEdit();
$this->clearSelectedIDs($event);
$event->redirect_params = Array('opener'=>'u');
$this->Application->RemoveVar($event->getPrefixSpecial().'_modified');
}
/**
* Allows to determine if we are creating new item or editing already created item
*
* @param kEvent $event
* @return bool
*/
function isNewItemCreate(&$event)
{
$event->setEventParam('raise_warnings', 0);
$object =& $event->getObject();
return !$object->IsLoaded();
// $item_id = $this->getPassedID($event);
// return ($item_id == '') ? true : false;
}
/**
* Saves edited item into temp table
* If there is no id, new item is created in temp table
*
* @param kEvent $event
*/
function OnPreSave(&$event)
{
//$event->redirect = false;
// if there is no id - it means we need to create an item
if (is_object($event->MasterEvent)) {
$event->MasterEvent->setEventParam('IsNew',false);
}
if ($this->isNewItemCreate($event)) {
$event->CallSubEvent('OnPreSaveCreated');
if (is_object($event->MasterEvent)) {
$event->MasterEvent->setEventParam('IsNew',true);
}
return;
}
$object =& $event->getObject( Array('skip_autoload' => true) );
$items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) );
if ($items_info) {
foreach ($items_info as $id => $field_values) {
$object->SetDefaultValues();
$object->Load($id);
$object->SetFieldsFromHash($field_values);
$this->customProcessing($event, 'before');
if( $object->Update($id) )
{
$this->customProcessing($event, 'after');
$event->status=erSUCCESS;
}
else {
$event->status = erFAIL;
$event->redirect = false;
break;
}
}
}
}
/**
* Saves edited item in temp table and loads
* item with passed id in current template
* Used in Prev/Next buttons
*
* @param kEvent $event
*/
function OnPreSaveAndGo(&$event)
{
$event->CallSubEvent('OnPreSave');
if ($event->status == erSUCCESS) {
$event->SetRedirectParam($event->getPrefixSpecial(true).'_id', $this->Application->GetVar($event->Prefix_Special.'_GoId'));
}
}
/**
* Saves edited item in temp table and goes
* to passed tabs, by redirecting to it with OnPreSave event
*
* @param kEvent $event
*/
function OnPreSaveAndGoToTab(&$event)
{
$event->CallSubEvent('OnPreSave');
if ($event->status==erSUCCESS) {
$event->redirect=$this->Application->GetVar($event->getPrefixSpecial(true).'_GoTab');
}
}
/**
* Saves editable list and goes to passed tab,
* by redirecting to it with empty event
*
* @param kEvent $event
*/
function OnUpdateAndGoToTab(&$event)
{
$event->setPseudoClass('_List');
$event->CallSubEvent('OnUpdate');
if ($event->status==erSUCCESS) {
$event->redirect=$this->Application->GetVar($event->getPrefixSpecial(true).'_GoTab');
}
}
/**
* Prepare temp tables for creating new item
* but does not create it. Actual create is
* done in OnPreSaveCreated
*
* @param kEvent $event
*/
function OnPreCreate(&$event)
{
$this->setTempWindowID($event);
$this->clearSelectedIDs($event);
$object =& $event->getObject( Array('skip_autoload' => true) );
$temp =& $this->Application->recallObject($event->Prefix.'_TempHandler', 'kTempTablesHandler');
$temp->PrepareEdit();
$object->setID(0);
$this->Application->SetVar($event->getPrefixSpecial().'_id',0);
$this->Application->SetVar($event->getPrefixSpecial().'_PreCreate', 1);
$event->redirect=false;
}
/**
* Creates a new item in temp table and
* stores item id in App vars and Session on succsess
*
* @param kEvent $event
*/
function OnPreSaveCreated(&$event)
{
$items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) );
if($items_info) $field_values = array_shift($items_info);
$object =& $event->getObject( Array('skip_autoload' => true) );
$object->SetFieldsFromHash($field_values);
$this->customProcessing($event, 'before');
if( $object->Create() )
{
$this->customProcessing($event, 'after');
$event->redirect_params[$event->getPrefixSpecial(true).'_id'] = $object->GetId();
$event->status=erSUCCESS;
}
else
{
$event->status=erFAIL;
$event->redirect=false;
$object->setID(0);
}
}
function OnReset(&$event)
{
//do nothing - should reset :)
if ($this->isNewItemCreate($event)) {
// just reset id to 0 in case it was create
$object =& $event->getObject( Array('skip_autoload' => true) );
$object->setID(0);
$this->Application->SetVar($event->getPrefixSpecial().'_id',0);
}
}
/**
* Apply same processing to each item beeing selected in grid
*
* @param kEvent $event
* @access private
*/
function iterateItems(&$event)
{
if ($this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1)) {
return;
}
$object =& $event->getObject( Array('skip_autoload' => true) );
$ids = $this->StoreSelectedIDs($event);
if ($ids) {
$status_field = array_shift( $this->Application->getUnitOption($event->Prefix,'StatusField') );
foreach ($ids as $id) {
$object->Load($id);
switch ($event->Name) {
case 'OnMassApprove':
$object->SetDBField($status_field, 1);
break;
case 'OnMassDecline':
$object->SetDBField($status_field, 0);
break;
case 'OnMassMoveUp':
$object->SetDBField('Priority', $object->GetDBField('Priority') + 1);
break;
case 'OnMassMoveDown':
$object->SetDBField('Priority', $object->GetDBField('Priority') - 1);
break;
}
if ($object->Update()) {
$event->status = erSUCCESS;
}
else {
$event->status = erFAIL;
$event->redirect = false;
break;
}
}
}
$this->clearSelectedIDs($event);
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function OnMassClone(&$event)
{
if ($this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1)) {
return;
}
$event->status = erSUCCESS;
$temp =& $this->Application->recallObject($event->getPrefixSpecial().'_TempHandler', 'kTempTablesHandler');
$ids = $this->StoreSelectedIDs($event);
if ($ids) {
$temp->CloneItems($event->Prefix, $event->Special, $ids);
}
$this->clearSelectedIDs($event);
}
function check_array($records, $field, $value)
{
foreach ($records as $record) {
if ($record[$field] == $value) {
return true;
}
}
return false;
}
function OnPreSavePopup(&$event)
{
$object =& $event->getObject();
$this->RemoveRequiredFields($object);
$event->CallSubEvent('OnPreSave');
$this->finalizePopup($event);
}
/* End of Edit events */
// III. Events that allow to put some code before and after Update,Load,Create and Delete methods of item
/**
* Occurse before loading item, 'id' parameter
* allows to get id of item beeing loaded
*
* @param kEvent $event
* @access public
*/
function OnBeforeItemLoad(&$event)
{
}
/**
* Occurse after loading item, 'id' parameter
* allows to get id of item that was loaded
*
* @param kEvent $event
* @access public
*/
function OnAfterItemLoad(&$event)
{
}
/**
* Occurse before creating item
*
* @param kEvent $event
* @access public
*/
function OnBeforeItemCreate(&$event)
{
}
/**
* Occurse after creating item
*
* @param kEvent $event
* @access public
*/
function OnAfterItemCreate(&$event)
{
}
/**
* Occurse before updating item
*
* @param kEvent $event
* @access public
*/
function OnBeforeItemUpdate(&$event)
{
}
/**
* Occurse after updating item
*
* @param kEvent $event
* @access public
*/
function OnAfterItemUpdate(&$event)
{
}
/**
* Occurse before deleting item, id of item beeing
* deleted is stored as 'id' event param
*
* @param kEvent $event
* @access public
*/
function OnBeforeItemDelete(&$event)
{
}
/**
* Occurse after deleting item, id of deleted item
* is stored as 'id' param of event
*
* @param kEvent $event
* @access public
*/
function OnAfterItemDelete(&$event)
{
}
/**
* Occurs after successful item validation
*
* @param kEvent $event
*/
function OnAfterItemValidate(&$event)
{
}
/**
* Occures after an item has been copied to temp
* Id of copied item is passed as event' 'id' param
*
* @param kEvent $event
*/
function OnAfterCopyToTemp(&$event)
{
}
/**
* Occures before an item is deleted from live table when copying from temp
* (temp handler deleted all items from live and then copy over all items from temp)
* Id of item being deleted is passed as event' 'id' param
*
* @param kEvent $event
*/
function OnBeforeDeleteFromLive(&$event)
{
}
/**
* Occures before an item is copied to live table (after all foreign keys have been updated)
* Id of item being copied is passed as event' 'id' param
*
* @param kEvent $event
*/
function OnBeforeCopyToLive(&$event)
{
}
/**
* !!! NOT FULLY IMPLEMENTED - SEE TEMP HANDLER COMMENTS (search by event name)!!!
* Occures after an item has been copied to live table
* Id of copied item is passed as event' 'id' param
*
* @param kEvent $event
*/
function OnAfterCopyToLive(&$event)
{
}
/**
* Occures before an item is cloneded
* Id of ORIGINAL item is passed as event' 'id' param
* Do not call object' Update method in this event, just set needed fields!
*
* @param kEvent $event
*/
function OnBeforeClone(&$event)
{
}
/**
* Occures after an item has been cloned
* Id of newly created item is passed as event' 'id' param
*
* @param kEvent $event
*/
function OnAfterClone(&$event)
{
}
/**
* Ensures that popup will be closed automatically
* and parent window will be refreshed with template
* passed
*
* @param kEvent $event
* @access public
*/
function finalizePopup(&$event)
{
$event->SetRedirectParam('opener', 'u');
/*return ;
// 2. substitute opener
$opener_stack = $this->Application->RecallVar('opener_stack');
$opener_stack = $opener_stack ? unserialize($opener_stack) : Array();
//array_pop($opener_stack);
$t = $this->Application->RecallVar('return_template');
$this->Application->RemoveVar('return_template');
// restore original "m" prefix all params, that have values before opening selector
$return_m = $this->Application->RecallVar('return_m');
$this->Application->RemoveVar('return_m');
$this->Application->HttpQuery->parseEnvPart($return_m);
$pass_events = $event->getEventParam('pass_events');
$redirect_params = array_merge_recursive2($event->redirect_params, Array('m_opener' => 'u', '__URLENCODE__' => 1));
$new_level = 'index.php|'.ltrim($this->Application->BuildEnv($t, $redirect_params, 'all', $pass_events), ENV_VAR_NAME.'=');
array_push($opener_stack, $new_level);
$this->Application->StoreVar('opener_stack', serialize($opener_stack));*/
}
/**
* Create search filters based on search query
*
* @param kEvent $event
* @access protected
*/
function OnSearch(&$event)
{
$event->setPseudoClass('_List');
$search_helper =& $this->Application->recallObject('SearchHelper');
$search_helper->performSearch($event);
}
/**
* Clear search keywords
*
* @param kEvent $event
* @access protected
*/
function OnSearchReset(&$event)
{
$search_helper =& $this->Application->recallObject('SearchHelper');
$search_helper->resetSearch($event);
}
/**
* Set's new filter value (filter_id meaning from config)
*
* @param kEvent $event
*/
function OnSetFilter(&$event)
{
$filter_id = $this->Application->GetVar('filter_id');
$filter_value = $this->Application->GetVar('filter_value');
$view_filter = $this->Application->RecallVar($event->getPrefixSpecial().'_view_filter');
$view_filter = $view_filter ? unserialize($view_filter) : Array();
$view_filter[$filter_id] = $filter_value;
$this->Application->StoreVar( $event->getPrefixSpecial().'_view_filter', serialize($view_filter) );
}
function OnSetFilterPattern(&$event)
{
$filters = $this->Application->GetVar($event->getPrefixSpecial(true).'_filters');
if (!$filters) return ;
$view_filter = $this->Application->RecallVar($event->getPrefixSpecial().'_view_filter');
$view_filter = $view_filter ? unserialize($view_filter) : Array();
$filters = explode(',', $filters);
foreach ($filters as $a_filter) {
list($id, $value) = explode('=', $a_filter);
$view_filter[$id] = $value;
}
$this->Application->StoreVar( $event->getPrefixSpecial().'_view_filter', serialize($view_filter) );
$event->redirect = false;
}
/**
* Add/Remove all filters applied to list from "View" menu
*
* @param kEvent $event
*/
function FilterAction(&$event)
{
$view_filter = Array();
$filter_menu = $this->Application->getUnitOption($event->Prefix,'FilterMenu');
switch ($event->Name)
{
case 'OnRemoveFilters':
$filter_value = 1;
break;
case 'OnApplyFilters':
$filter_value = 0;
break;
}
foreach($filter_menu['Filters'] as $filter_key => $filter_params)
{
if(!$filter_params) continue;
$view_filter[$filter_key] = $filter_value;
}
$this->Application->StoreVar( $event->getPrefixSpecial().'_view_filter', serialize($view_filter) );
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function OnPreSaveAndOpenTranslator(&$event)
{
$this->Application->SetVar('allow_translation', true);
$object =& $event->getObject();
$this->RemoveRequiredFields($object);
$event->CallSubEvent('OnPreSave');
if ($event->status == erSUCCESS) {
$resource_id = $this->Application->GetVar('translator_resource_id');
if ($resource_id) {
$t_prefixes = explode(',', $this->Application->GetVar('translator_prefixes'));
$cdata =& $this->Application->recallObject($t_prefixes[1], null, Array('skip_autoload' => true));
$cdata->Load($resource_id, 'ResourceId');
if (!$cdata->isLoaded()) {
$cdata->SetDBField('ResourceId', $resource_id);
$cdata->Create();
}
$this->Application->SetVar($cdata->getPrefixSpecial().'_id', $cdata->GetID());
}
$event->redirect = $this->Application->GetVar('translator_t');
$event->redirect_params = Array('pass'=>'all,trans,'.$this->Application->GetVar('translator_prefixes'),
$event->getPrefixSpecial(true).'_id' => $object->GetID(),
'trans_event' => 'OnLoad',
'trans_prefix' => $this->Application->GetVar('translator_prefixes'),
'trans_field' => $this->Application->GetVar('translator_field'),
'trans_multi_line' => $this->Application->GetVar('translator_multi_line'),
);
// 1. SAVE LAST TEMPLATE TO SESSION (really needed here, because of tweaky redirect)
$last_template = $this->Application->RecallVar('last_template');
preg_match('/index4\.php\|'.$this->Application->GetSID().'-(.*):/U', $last_template, $rets);
$this->Application->StoreVar('return_template', $this->Application->GetVar('t'));
}
}
function RemoveRequiredFields(&$object)
{
// making all field non-required to achieve successful presave
foreach($object->Fields as $field => $options)
{
if(isset($options['required']))
{
unset($object->Fields[$field]['required']);
}
}
}
/**
* Saves selected user in needed field
*
* @param kEvent $event
*/
function OnSelectUser(&$event)
{
$items_info = $this->Application->GetVar('u');
if ($items_info) {
$user_id = array_shift( array_keys($items_info) );
$object =& $event->getObject();
$this->RemoveRequiredFields($object);
$is_new = !$object->isLoaded();
$is_main = substr($this->Application->GetVar($event->Prefix.'_mode'), 0, 1) == 't';
if ($is_new) {
$new_event = $is_main ? 'OnPreCreate' : 'OnNew';
$event->CallSubEvent($new_event);
$event->redirect = true;
}
$object->SetDBField($this->Application->RecallVar('dst_field'), $user_id);
if ($is_new) {
$object->Create();
if (!$is_main && $object->IsTempTable()) {
$object->setTempID();
}
}
else {
$object->Update();
}
}
$event->SetRedirectParam($event->getPrefixSpecial().'_id', $object->GetID());
$this->finalizePopup($event);
}
/** EXPORT RELATED **/
/**
* Shows export dialog
*
* @param kEvent $event
*/
function OnExport(&$event)
{
$this->StoreSelectedIDs($event);
$selected_ids = $this->getSelectedIDs($event);
if (implode(',', $selected_ids) == '') {
// K4 fix when no ids found bad selected ids array is formed
$selected_ids = false;
}
$this->Application->StoreVar($event->Prefix.'_export_ids', $selected_ids ? implode(',', $selected_ids) : '' );
$export_t = $this->Application->GetVar('export_template');
$this->Application->LinkVar('export_finish_t');
$this->Application->LinkVar('export_progress_t');
$this->Application->StoreVar('export_oroginal_special', $event->Special);
$export_helper =& $this->Application->recallObject('CatItemExportHelper');
$event->redirect = $export_t ? $export_t : $export_helper->getModuleFolder($event).'/export';
list($index_file, $env) = explode('|', $this->Application->RecallVar('last_template'));
$finish_url = $this->Application->BaseURL('/admin').$index_file.'?'.ENV_VAR_NAME.'='.$env;
$this->Application->StoreVar('export_finish_url', $finish_url);
$redirect_params = Array(
$this->Prefix.'.export_event' => 'OnNew',
'pass' => 'all,'.$this->Prefix.'.export');
$event->setRedirectParams($redirect_params);
}
/**
* Apply some special processing to
* object beeing recalled before using
* it in other events that call prepareObject
*
* @param Object $object
* @param kEvent $event
* @access protected
*/
function prepareObject(&$object, &$event)
{
if ($event->Special == 'export' || $event->Special == 'import')
{
$export_helper =& $this->Application->recallObject('CatItemExportHelper');
$export_helper->prepareExportColumns($event);
}
}
/**
* Returns specific to each item type columns only
*
* @param kEvent $event
* @return Array
*/
function getCustomExportColumns(&$event)
{
return Array();
}
/**
* Export form validation & processing
*
* @param kEvent $event
*/
function OnExportBegin(&$event)
{
$export_helper =& $this->Application->recallObject('CatItemExportHelper');
/* @var $export_helper kCatDBItemExportHelper */
$export_helper->OnExportBegin($event);
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function OnExportCancel(&$event)
{
$this->OnGoBack($event);
}
/**
* Allows configuring export options
*
* @param kEvent $event
*/
function OnBeforeExportBegin(&$event)
{
}
function OnDeleteExportPreset(&$event)
{
$object =& $event->GetObject();
$items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) );
if($items_info)
{
list($id,$field_values) = each($items_info);
$preset_key = $field_values['ExportPresets'];
$user =& $this->Application->recallObject('u.current');
$export_settings = $user->getPersistantVar('export_settings');
if (!$export_settings) return ;
$export_settings = unserialize($export_settings);
if (!isset($export_settings[$event->Prefix])) return ;
$to_delete = '';
$export_presets = array(''=>'');
foreach ($export_settings[$event->Prefix] as $key => $val) {
if (implode('|', $val['ExportColumns']) == $preset_key) {
$to_delete = $key;
break;
}
}
if ($to_delete) {
unset($export_settings[$event->Prefix][$to_delete]);
$user->setPersistantVar('export_settings', serialize($export_settings));
}
}
}
/**
* Saves changes & changes language
*
* @param kEvent $event
*/
function OnPreSaveAndChangeLanguage(&$event)
{
$event->CallSubEvent('OnPreSave');
if ($event->status == erSUCCESS) {
$this->Application->SetVar('m_lang', $this->Application->GetVar('language'));
}
}
function OnUploadFile(&$event)
{
// Flash uploader does NOT send correct cookies, so we need to make our own check
$cookie_name = 'adm_'.$this->Application->ConfigValue('SessionCookieName');
$this->Application->HttpQuery->Cookie['cookies_on'] = 1;
$this->Application->HttpQuery->Cookie[$cookie_name] = $this->Application->GetVar('flashsid');
$admin_ses =& $this->Application->recallObject('Session.admin');
/* @var $admin_ses Session */
$user = $admin_ses->RecallVar('user_id');
$perm_helper =& $this->Application->recallObject('PermissionsHelper');
/* @var $perm_helper kPermissionsHelper */
$section = $event->getSection();
if (!$perm_helper->CheckUserPermission($user, $section.'.add') && !$perm_helper->CheckUserPermission($user, $section.'.edit')) {
$event->status = erPERM_FAIL;
header('HTTP/1.0 403 You don\'t have permissions to upload');
exit;
return;
}
if (!$cookie_name) $cookie_name = 'sid';
$value = $this->Application->GetVar('Filedata');
if (!$value) return ;
$tmp_path = defined('WRITEABLE') ? WRITEABLE.'/tmp/' : FULL_PATH.'/kernel/cache/';
$fname = $value['name'];
$id = $this->Application->GetVar('id');
if ($id) $fname = $id.'_'.$fname;
if (!is_writable($tmp_path)) {
header('HTTP/1.0 500 Write permissions not set on the server');
exit;
}
move_uploaded_file($value['tmp_name'], $tmp_path.$fname);
exit;
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function OnDeleteFile(&$event)
{
if (strpos($this->Application->GetVar('file'), '../') !== false) return ;
$object =& $event->getObject(array('skip_autoload'=>true));
$options = $object->GetFieldOptions($this->Application->GetVar('field'));
$var_name = $event->getPrefixSpecial().'_file_pending_actions'.$this->Application->GetVar('m_wid');
$schedule = $this->Application->RecallVar($var_name);
$schedule = $schedule ? unserialize($schedule) : array();
$schedule[] = array('action'=>'delete', 'file'=>$path = FULL_PATH.$options['upload_dir'].$this->Application->GetVar('file'));
$this->Application->StoreVar($var_name, serialize($schedule));
$this->Application->Session->SaveData();
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function OnViewFile(&$event)
{
if (strpos($this->Application->GetVar('file'), '../') !== false) return ;
if ($this->Application->GetVar('tmp')) {
$path = (defined('WRITEABLE') ? WRITEABLE.'/tmp/' : FULL_PATH.'/kernel/cache/').$this->Application->GetVar('id').'_'.$this->Application->GetVar('file');
}
else {
$object =& $event->getObject(array('skip_autoload'=>true));
$options = $object->GetFieldOptions($this->Application->GetVar('field'));
$path = FULL_PATH.$options['upload_dir'].$this->Application->GetVar('file');
}
$type = mime_content_type($path);
header('Content-Length: '.filesize($path));
header('Content-Type: '.$type);
safeDefine('DBG_SKIP_REPORTING',1);
readfile($path);
exit();
}
+
+ /**
+ * Validates MInput control fields
+ *
+ * @param kEvent $event
+ */
+ function OnValidateMInputFields(&$event)
+ {
+ $minput_helper =& $this->Application->recallObject('MInputHelper');
+ /* @var $minput_helper MInputHelper */
+
+ $minput_helper->OnValidateMInputFields($event);
+ }
/**
* Returns auto-complete values for ajax-dropdown
*
* @param kEvent $event
*/
function OnSuggestValues(&$event)
{
$this->Application->XMLHeader();
$field = $this->Application->GetVar('field');
$cur_value = $this->Application->GetVar('cur_value');
if (!$field || !$cur_value) {
exit;
}
$object =& $event->getObject();
$sql = 'SELECT DISTINCT '.$field.'
FROM '.$object->TableName.'
WHERE '.$field.' LIKE '.$this->Conn->qstr($cur_value.'%').'
ORDER BY '.$field.'
LIMIT 0,20';
$data = $this->Conn->GetCol($sql);
echo '<suggestions>';
foreach ($data as $item) {
echo '<item>'.$item.'</item>';
}
echo '</suggestions>';
$event->status = erSTOP;
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function OnSaveWidths(&$event)
{
safeDefine('DBG_SKIP_REPORTING', 1);
$lang =& $this->Application->recallObject('lang.current');
// header('Content-type: text/xml; charset='.$lang->GetDBField('Charset'));
$picker_helper =& $this->Application->RecallObject('ColumnPickerHelper');
/* @var $picker_helper kColumnPickerHelper */
$picker_helper->PreparePicker($event->getPrefixSpecial(), $this->Application->GetVar('grid_name'));
$picker_helper->SaveWidths($event->getPrefixSpecial(), $this->Application->GetVar('widths'));
exit;
}
/**
* Called from CSV import script after item fields
* are set and validated, but before actual item create/update.
* If event status is erSUCCESS, line will be imported,
* else it will not be imported but added to skipped lines
* and displayed in the end of import.
* Event status is preset from import script.
*
* @param kEvent $event
*/
function OnBeforeCSVLineImport(&$event)
{
// abstract, for hooking
}
}
?>
\ No newline at end of file
Property changes on: branches/RC/core/kernel/db/db_event_handler.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.99.2.15
\ No newline at end of property
+1.99.2.16
\ No newline at end of property
Index: branches/RC/core/kernel/db/dbitem.php
===================================================================
--- branches/RC/core/kernel/db/dbitem.php (revision 10004)
+++ branches/RC/core/kernel/db/dbitem.php (revision 10005)
@@ -1,1056 +1,1060 @@
<?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();
/**
* Holds item values after loading (not affected by submit)
*
* @var Array
* @access private
*/
var $OriginalFieldValues = 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'] = '!la_err_required!'; //'Field is required';
$this->ErrorMsgs['unique'] = '!la_err_unique!'; //'Field value must be unique';
$this->ErrorMsgs['value_out_of_range'] = '!la_err_value_out_of_range!'; //'Field is out of range, possible values from %s to %s';
$this->ErrorMsgs['length_out_of_range'] = '!la_err_length_out_of_range!'; //'Field is out of range';
$this->ErrorMsgs['bad_type'] = '!la_err_bad_type!'; //'Incorrect data format, please use %s';
$this->ErrorMsgs['invalid_format'] = '!la_err_invalid_format!'; //'Incorrect data format, please use %s';
$this->ErrorMsgs['bad_date_format'] = '!la_err_bad_date_format!'; //'Incorrect date format, please use (%s) ex. (%s)';
$this->ErrorMsgs['primary_lang_required'] = '!la_err_primary_lang_required!';
}
function SetDirtyField($field_name, $field_value)
{
$this->DirtyFieldValues[$field_name] = $field_value;
}
function GetDirtyField($field_name)
{
return $this->DirtyFieldValues[$field_name];
}
function GetOriginalField($field_name)
{
return $this->OriginalFieldValues[$field_name];
}
/**
* Sets original field value (useful for custom virtual fields)
*
* @param string $field_name
*/
function SetOriginalField($field_name, $field_value)
{
$this->OriginalFieldValues[$field_name] = $field_value;
}
/**
* Set's default values for all fields
*
* @param bool $populate_ml_fields create all ml fields from db in config or not
*
* @access public
*/
function SetDefaultValues($populate_ml_fields = false)
{
parent::SetDefaultValues($populate_ml_fields);
if ($populate_ml_fields) {
$this->PopulateMultiLangFields();
}
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;
}
// kFormatter is always used, to make sure, that numeric value is converted to normal representation
// according to regional format, even when formatter is not set (try seting format to 1.234,56 to understand why)
$formatter =& $this->Application->recallObject(isset($options['formatter']) ? $options['formatter'] : 'kFormatter');
$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 = null, $error_params = null)
{
$error_field = isset($this->Fields[$field]['error_field']) ? $this->Fields[$field]['error_field'] : $field;
if (isset($this->FieldErrors[$error_field]['pseudo'])) {
// don't set more then one error on field
return ;
}
$this->FieldErrors[$error_field]['pseudo'] = $pseudo;
if (isset($error_params)) {
// additional params, that helps to determine error sources
$this->FieldErrors[$error_field]['params'] = $error_params;
}
if (isset($error_label) && !isset($this->ErrorMsgs[$pseudo])) {
// label for error (only when not already set)
$this->ErrorMsgs[$pseudo] = (substr($error_label, 0, 1) == '+') ? substr($error_label, 1) : '!'.$error_label.'!';
}
}
/**
* 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
* @param Array $keys_hash alternative, then item id, keys hash to load item by
* @return void
* @see kDBItem::Load()
* @see kDBItem::Update()
* @see kDBItem::Delete()
*/
function GetKeyClause($method=null, $keys_hash = null)
{
if( !isset($keys_hash) ) $keys_hash = Array($this->IDField => $this->ID);
$ret = '';
foreach($keys_hash as $field => $value)
{
if (!preg_match('/\./', $field)) {
$ret .= '(`'.$this->TableName.'`.'.$field.' = '.$this->Conn->qstr($value).') AND ';
}
else {
$ret .= '('.$field.' = '.$this->Conn->qstr($value).') AND ';
}
}
return preg_replace('/(.*) AND $/', '\\1', $ret);
}
/**
* Loads item from the database by given id
*
* @access public
* @param mixed $id item id of keys->values hash to load item by
* @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 ( isset($id_field_name) ) $this->SetIDField( $id_field_name );
$keys_sql = '';
if( is_array($id) )
{
$keys_sql = $this->GetKeyClause('load', $id);
}
else
{
$this->setID($id);
$keys_sql = $this->GetKeyClause('load');
}
if ( isset($id_field_name) ) $this->setIDField( $this->Application->getUnitOption($this->Prefix, 'IDField') );
if( ($id === false) || !$keys_sql ) return $this->Clear();
if( !$this->raiseEvent('OnBeforeItemLoad', $id) ) return false;
$q = $this->GetSelectSQL().' WHERE '.$keys_sql;
$field_values = $this->Conn->GetRow($q);
if($field_values)
{
$this->FieldValues = array_merge_recursive2($this->FieldValues, $field_values);
$this->OriginalFieldValues = $this->FieldValues;
}
else {
return $this->Clear();
}
if( is_array($id) || isset($id_field_name) ) $this->setID( $this->FieldValues[$this->IDField] );
$this->UpdateFormattersSubFields(); // used for updating separate virtual date/time fields from DB timestamp (for example)
$this->raiseEvent('OnAfterItemLoad', $this->GetID() );
$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 marked field with 'skip_empty'
// $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->Conn->ChangeQuery($sql) === false ) return false;
$affected = $this->Conn->getAffectedRows();
if (!$system_update && $affected == 1){
$this->setModifiedFlag();
}
$this->saveCustomFields();
$this->raiseEvent('OnAfterItemUpdate');
$this->Loaded = true;
if ($this->mode != 't') {
$this->Application->resetCounters($this->TableName);
}
return true;
}
function ValidateField($field)
{
$options = $this->Fields[$field];
/*if (isset($options['formatter'])) {
$formatter =& $this->Application->recallObject($options['formatter']);
$formatter->UpdateMasterFields($field, $this->GetDBField($field), $options, $this);
}*/
$error_field = isset($options['error_field']) ? $options['error_field'] : $field;
$res = !isset($this->FieldErrors[$error_field]['pseudo']) || !$this->FieldErrors[$error_field]['pseudo'];
$res = $res && $this->ValidateType($field, $options);
$res = $res && $this->ValidateRange($field, $options);
$res = $res && $this->ValidateUnique($field, $options);
$res = $res && $this->ValidateRequired($field, $options);
$res = $res && $this->CustomValidation($field, $options);
return $res;
}
/**
* 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 = $this->ValidateField($field);
$global_res = $global_res && $res;
}
if (!$global_res && $this->Application->isDebugMode()) {
$error_msg = ' Validation failed in prefix <strong>'.$this->Prefix.'</strong>,
FieldErrors follow (look at items with <strong>"pseudo"</strong> key set)<br />
You may ignore this notice if submitted data really has a validation error';
trigger_error(trim($error_msg), E_USER_NOTICE);
$this->Application->Debugger->dumpVars($this->FieldErrors);
}
return $global_res;
}
/**
* Check field value by user-defined alghoritm
*
* @param string $field field name
* @param Array $params field options from config
* @return bool
*/
function CustomValidation($field, $params)
{
return true;
}
/**
* Check if item has errors
*
* @param Array $skip_fields fields to skip during error checking
* @return bool
*/
function HasErrors($skip_fields)
{
$global_res = false;
foreach ($this->Fields as $field => $field_params) {
// If Formatter has set some error messages during values parsing
if ( !( in_array($field, $skip_fields) ) &&
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];
if ( $val != '' &&
isset($params['type']) &&
preg_match("#int|integer|double|float|real|numeric|string#", $params['type'])
) {
if ($params['type'] == 'numeric') {
trigger_error('Invalid field type <strong>'.$params['type'].'</strong> (in ValidateType method), please use <strong>float</strong> instead', E_USER_NOTICE);
$params['type'] = 'float';
}
$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->SetError($field, 'bad_type', null, $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;
if (isset($params['required']) && $params['required']) {
$check_value = $this->FieldValues[$field];
if ($this->Application->ConfigValue('TrimRequiredFields')) {
$check_value = trim($check_value);
}
$res = ((string)$check_value != '');
}
$options = $this->GetFieldOptions($field);
if (!$res && getArrayValue($options, 'formatter') != 'kUploadFormatter') {
$this->SetError($field, '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;
$unique_fields = getArrayValue($params,'unique');
if($unique_fields !== false)
{
$where = Array();
array_push($unique_fields,$field);
foreach($unique_fields as $unique_field)
{
// if field is not empty or if it is required - we add where condition
if ($this->GetDBField($unique_field) != '' || (isset($this->Fields[$unique_field]['required']) && $this->Fields[$unique_field]['required'])) {
$where[] = '`'.$unique_field.'` = '.$this->Conn->qstr( $this->GetDBField($unique_field) );
}
}
// This can ONLY happen if all unique fields are empty and not required.
// In such case we return true, because if unique field is not required there may be numerous empty values
if (!$where) return true;
$sql = 'SELECT COUNT(*) FROM %s WHERE ('.implode(') AND (',$where).') AND ('.$this->IDField.' <> '.(int)$this->ID.')';
$res_temp = $this->Conn->GetOne( str_replace('%s', $this->TableName, $sql) );
$current_table_only = getArrayValue($params, 'current_table_only'); // check unique record only in current table
$res_live = $current_table_only ? 0 : $this->Conn->GetOne( str_replace('%s', $this->Application->GetLiveName($this->TableName), $sql) );
$res = ($res_temp == 0) && ($res_live == 0);
if (!$res) {
$this->SetError($field, '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];
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) {
if ( !isset($min_val) ) $min_val = '-&infin;';
if ( !isset($max_val) ) $max_val = '&infin;';
$this->SetError($field, 'value_out_of_range', null, 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) {
$error_params = Array (getArrayValue($params, 'min_len'), getArrayValue($params, 'max_len'));
$this->SetError($field, 'length_out_of_range', null, $error_params);
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 (!$err) return '';
// if special error msg defined in config
if( isset($this->Fields[$field]['error_msgs'][$err]) )
{
$msg = $this->Fields[$field]['error_msgs'][$err];
}
else //fall back to defaults
{
if( !isset($this->ErrorMsgs[$err]) ) {
trigger_error('No user message is defined for pseudo error <b>'.$err.'</b><br>', E_USER_WARNING);
return $err; //return the pseudo itself
}
$msg = $this->ErrorMsgs[$err];
}
$msg = $this->Application->ReplaceLanguageTags($msg, $force_escape);
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;
//Adding field' value to Values block of Insert statement, escaping it with 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'], 0);
}
else {
$values_sql .= 'NULL';
}
}
else {
if ($field_name == $this->IDField && $this->FieldValues[$field_name] == 0) {
$values_sql .= 'DEFAULT';
}
else {
$values_sql .= $this->Conn->qstr($this->FieldValues[$field_name], 0);
}
}
$fields_sql .= '`'.$field_name.'`, '; //Adding field name to fields block of Insert statement
$values_sql .= ', ';
}
//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) return false;
$insert_id = $this->Conn->getInsertID();
if ($insert_id == 0) {
// insert into temp table (id is not auto-increment field)
$insert_id = $this->FieldValues[$this->IDField];
}
$this->setID($insert_id);
if (!$system_create){
$this->setModifiedFlag();
}
$this->saveCustomFields();
if ($this->mode != 't') {
$this->Application->resetCounters($this->TableName);
}
$this->raiseEvent('OnAfterItemCreate');
$this->Loaded = true;
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');
$ret = $this->Conn->ChangeQuery($q);
$this->setModifiedFlag();
if ($this->Conn->getAffectedRows() > 0) {
// something was actually deleted
$this->raiseEvent('OnAfterItemDelete');
}
if ($this->mode != 't') {
$this->Application->resetCounters($this->TableName);
}
return $ret;
}
function PopulateMultiLangFields()
{
$ml_helper =& $this->Application->recallObject('kMultiLanguageHelper');
/* @var $ml_helper kMultiLanguageHelper */
$lang_count = $ml_helper->getLanguageCount();
foreach ($this->Fields as $field => $options)
{
if (isset($options['formatter']) && $options['formatter'] == 'kMultiLanguage' && isset($options['master_field'])) {
if (preg_match('/^l([0-9]+)_(.*)/', $field, $regs)) {
$l = $regs[1];
$name = $regs[2];
unset($options['required']); // all non-primary language field set to non-required
for ($i=1; $i<=$lang_count; $i++) {
if ($i == $l || !$ml_helper->LanguageFound($i)) continue;
$this->Fields['l'.$i.'_'.$name] = $options;
}
}
}
}
}
/**
* 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
+ * @param string $title_field FieldName to alter, by default - TitleField of the prefix
+ * @param string $format sprintf-style format of renaming pattern, by default Copy %1$s of %2$s which makes it Copy [Number] of Original Name
* @access private
*/
- function NameCopy($master=null, $foreign_key=null)
+ function NameCopy($master=null, $foreign_key=null, $title_field=null, $format='Copy %1$s of %2$s')
{
+ if (!isset($title_field)) {
$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];
+ if ( preg_match('/'.sprintf($format, '([0-9]*) *', '(.*)').'/', $new_name, $regs) ) {
+ $new_name = sprintf($format, ($regs[1]+1), $regs[2]);
}
elseif ($original_checked) {
- $new_name = 'Copy of '.$new_name;
+ $new_name = sprintf($format, '', $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);
$foreign_key_field = getArrayValue($master, 'ForeignKey');
$foreign_key_field = is_array($foreign_key_field) ? $foreign_key_field[ $master['ParentPrefix'] ] : $foreign_key_field;
if ($foreign_key_field && isset($foreign_key)) {
$query .= ' AND '.$foreign_key_field.' = '.$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, $additional_params = Array())
{
if( !isset($id) ) $id = $this->GetID();
$event = new kEvent( Array('name'=>$name,'prefix'=>$this->Prefix,'special'=>$this->Special) );
$event->setEventParam('id', $id);
if ($additional_params) {
foreach ($additional_params as $ap_name => $ap_value) {
$event->setEventParam($ap_name, $ap_value);
}
}
$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;
}
/**
* Checks if field is required
*
* @param string $field
* @return bool
*/
function isRequired($field)
{
return getArrayValue( $this->Fields[$field], 'required' );
}
/**
* Sets new required flag to field
*
* @param string $field
* @param bool $is_required
*/
function setRequired($field, $is_required = true)
{
$this->Fields[$field]['required'] = $is_required;
}
function Clear($new_id = null)
{
$this->setID($new_id);
$this->Loaded = false;
$this->FieldValues = Array();
$this->OriginalFieldValues = Array ();
$this->SetDefaultValues();
$this->FieldErrors = Array();
return $this->Loaded;
}
function Query($force = false)
{
if( $this->Application->isDebugMode() )
{
$this->Application->Debugger->appendTrace();
}
trigger_error('<b>Query</b> method is called in class <b>'.get_class($this).'</b> for prefix <b>'.$this->getPrefixSpecial().'</b>', E_USER_ERROR);
}
function saveCustomFields()
{
if (!$this->customFields) {
return true;
}
$cdata_key = rtrim($this->Prefix.'-cdata.'.$this->Special, '.');
$cdata =& $this->Application->recallObject($cdata_key, null, Array('skip_autoload' => true, 'populate_ml_fields' => true));
$resource_id = $this->GetDBField('ResourceId');
$cdata->Load($resource_id, 'ResourceId');
$cdata->SetDBField('ResourceId', $resource_id);
$ml_formatter =& $this->Application->recallObject('kMultiLanguage');
/* @var $ml_formatter kMultiLanguage */
foreach ($this->customFields as $custom_id => $custom_name) {
$force_primary = isset($cdata->Fields['cust_'.$custom_id]['force_primary']) && $cdata->Fields['cust_'.$custom_id]['force_primary'];
$cdata->SetDBField($ml_formatter->LangFieldName('cust_'.$custom_id, $force_primary), $this->GetDBField('cust_'.$custom_name));
}
if ($cdata->isLoaded()) {
$ret = $cdata->Update();
}
else {
$ret = $cdata->Create();
if ($cdata->mode == 't') $cdata->setTempID();
}
return $ret;
}
/**
* Returns specified field value from all selected rows.
* Don't affect current record index
*
* @param string $field
* @return Array
*/
function GetCol($field)
{
return Array (0 => $this->GetDBField($field));
}
}
?>
\ No newline at end of file
Property changes on: branches/RC/core/kernel/db/dbitem.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.44.2.6
\ No newline at end of property
+1.44.2.7
\ No newline at end of property
Index: branches/RC/core/units/users/users_event_handler.php
===================================================================
--- branches/RC/core/units/users/users_event_handler.php (revision 10004)
+++ branches/RC/core/units/users/users_event_handler.php (revision 10005)
@@ -1,1377 +1,1492 @@
<?php
class UsersEventHandler extends kDBEventHandler
{
/**
* Allows to override standart permission mapping
*
*/
function mapPermissions()
{
parent::mapPermissions();
$permissions = Array (
// admin
'OnSetPersistantVariable' => Array('self' => 'view'), // because setting to logged in user only
- 'OnUpdateRootPassword' => Array('self' => true), // because setting to logged in user only
+ 'OnUpdateRootPassword' => Array('self' => true),
+ 'OnUpdatePassword' => Array('self' => true),
// front
'OnRefreshForm' => Array('self' => true),
'OnForgotPassword' => Array('self' => true),
'OnResetPassword' => Array('self' => true),
'OnResetPasswordConfirmed' => Array('self' => true),
'OnSubscribeQuery' => Array('self' => true),
'OnSubscribeUser' => Array('self' => true),
'OnRecommend' => Array('self' => true),
'OnItemBuild' => Array('self' => true),
'OnMassResetSettings' => Array('self' => 'edit'),
+ 'OnMassCloneUsers' => Array('self' => 'add'),
);
$this->permMapping = array_merge($this->permMapping, $permissions);
}
/**
* Shows only admins when required
*
* @param kEvent $event
*/
function SetCustomQuery(&$event)
{
$object =& $event->getObject();
/* @var $object kDBList */
if ($event->Special == 'admins') {
$object->addFilter('primary_filter', 'ug.GroupId = 11');
}
if ($event->Special == 'regular') {
$object->addFilter('primary_filter', 'ug.GroupId <> 11');
}
if (!$this->Application->IsAdmin()) {
$object->addFilter('status_filter', '%1$s.Status = '.STATUS_ACTIVE);
}
+
+ if ($event->Special == 'group') {
+ $group_id = $this->Application->GetVar('g_id');
+ if ($group_id !== false) {
+ // show only users, that user doesn't belong to current group
+ $table_name = $this->Application->GetTempName(TABLE_PREFIX.'UserGroup', 'prefix:g');
+ $sql = 'SELECT PortalUserId
+ FROM '.$table_name.'
+ WHERE GroupId = '.$group_id;
+ $user_ids = $this->Conn->GetCol($sql);
+ array_push($user_ids); // Guest & Everyone groups are set dynamically
+ if ($user_ids) {
+ $object->addFilter('already_member_filter', '%1$s.PortalUserId NOT IN ('.implode(',', $user_ids).')');
+ }
+ }
+ }
}
/**
* Checks permissions of user
*
* @param kEvent $event
*/
function CheckPermission(&$event)
{
if ($event->Name == 'OnLogin' || $event->Name == 'OnLogout') {
// permission is checked in OnLogin event directly
return true;
}
if (!$this->Application->IsAdmin()) {
$user_id = $this->Application->RecallVar('user_id');
$items_info = $this->Application->GetVar($event->getPrefixSpecial(true));
if ($event->Name == 'OnCreate' && $user_id == -2) {
// "Guest" can create new users
return true;
}
if ($event->Name == 'OnUpdate' && $user_id > 0) {
$user_dummy =& $this->Application->recallObject($event->Prefix.'.-item', null, Array('skip_autoload' => true));
foreach ($items_info as $id => $field_values) {
if ($id != $user_id) {
// registered users can update their record only
return false;
}
$user_dummy->Load($id);
$status_field = array_shift($this->Application->getUnitOption($event->Prefix, 'StatusField'));
if ($user_dummy->GetDBField($status_field) != STATUS_ACTIVE) {
// not active user is not allowed to update his record (he could not activate himself manually)
return false;
}
if (isset($field_values[$status_field]) && $user_dummy->GetDBField($status_field) != $field_values[$status_field]) {
// user can't change status by himself
return false;
}
}
return true;
}
if ($event->Name == 'OnUpdate' && $user_id <= 0) {
// guests are not allowed to update their record, because they don't have it :)
return false;
}
}
return parent::CheckPermission($event);
}
function OnSessionExpire()
{
$this->Application->resetCounters('UserSession');
if ($this->Application->IsAdmin()) {
$this->Application->Redirect('index', Array('expired' => 1), '', 'index.php');
}
if ($this->Application->GetVar('admin') == 1) {
$session_admin =& $this->Application->recallObject('Session.admin');
/* @var $session_admin Session */
if (!$session_admin->LoggedIn()) {
// front-end session created from admin session & both expired
$this->Application->DeleteVar('admin');
$this->Application->Redirect('index', Array('expired' => 1), '', 'admin/index.php');
}
}
$get = $this->Application->HttpQuery->getRedirectParams();
$t = $this->Application->GetVar('t');
$get['js_redirect'] = $this->Application->ConfigValue('UseJSRedirect');
$this->Application->Redirect($t ? $t : 'index', $get);
}
/**
* Checks user data and logs it in if allowed
*
* @param kEvent $event
*/
function OnLogin(&$event)
{
// persistent session data after login is not refreshed, because redirect will follow in any case
$prefix_special = $this->Application->IsAdmin() ? 'u.current' : 'u'; // "u" used on front not to change theme
$object =& $this->Application->recallObject($prefix_special, null, Array('skip_autoload' => true));
$password = $this->Application->GetVar('password');
$invalid_pseudo = $this->Application->IsAdmin() ? 'la_invalid_password' : 'lu_invalid_password';
if(!$password)
{
$object->SetError('ValidateLogin', 'invalid_password', $invalid_pseudo);
$event->status = erFAIL;
return false;
}
$email_as_login = $this->Application->ConfigValue('Email_As_Login');
list($login_field, $submit_field) = $email_as_login && !$this->Application->IsAdmin() ? Array('Email', 'email') : Array('Login', 'login');
$login_value = $this->Application->GetVar($submit_field);
// process "Save Username" checkbox
if ($this->Application->IsAdmin()) {
$save_username = $this->Application->GetVar('cb_save_username') ? $login_value : '';
$this->Application->Session->SetCookie('save_username', $save_username, adodb_mktime() + 31104000); // 1 year expiration
$this->Application->SetVar('save_username', $save_username); // cookie will be set on next refresh, but refresh won't occur if login error present, so duplicate cookie in HTTPQuery
}
$super_admin = ($login_value == 'super-root') && $this->verifySuperAdmin();
if ($this->Application->IsAdmin() && ($login_value == 'root') || ($super_admin && $login_value == 'super-root')) {
// logging in "root" (admin only)
$login_value = 'root';
$root_password = $this->Application->ConfigValue('RootPass');
$password_formatter =& $this->Application->recallObject('kPasswordFormatter');
$test = $password_formatter->EncryptPassword($password, 'b38');
if ($root_password != $test) {
$object->SetError('ValidateLogin', 'invalid_password', $invalid_pseudo);
$event->status = erFAIL;
return false;
}
elseif ($this->checkLoginPermission($login_value)) {
$user_id = -1;
$object->Load($user_id);
$object->SetDBField('Login', $login_value);
$session =& $this->Application->recallObject('Session');
$session->SetField('PortalUserId', $user_id);
// $session->SetField('GroupList', implode(',', $groups) );
$this->Application->SetVar('u.current_id', $user_id);
$this->Application->StoreVar('user_id', $user_id);
if ($super_admin) {
$this->Application->StoreVar('super_admin', 1);
}
$this->processLoginRedirect($event, $password);
return true;
}
else {
$object->SetError('ValidateLogin', 'invalid_license', 'la_invalid_license');
$event->status = erFAIL;
return false;
}
}
/*$sql = 'SELECT PortalUserId FROM '.$object->TableName.' WHERE (%s = %s) AND (Password = MD5(%s))';
$user_id = $this->Conn->GetOne( sprintf($sql, $login_field, $this->Conn->qstr($login_value), $this->Conn->qstr($password) ) );*/
$sql = 'SELECT PortalUserId FROM '.$object->TableName.' WHERE (Email = %1$s OR Login = %1$s) AND (Password = MD5(%2$s))';
$user_id = $this->Conn->GetOne( sprintf($sql, $this->Conn->qstr($login_value), $this->Conn->qstr($password) ) );
if ($user_id) {
$object->Load($user_id);
if ($object->GetDBField('Status') == STATUS_ACTIVE) {
$groups = $object->getMembershipGroups(true);
if(!$groups) $groups = Array();
array_push($groups, $this->Application->ConfigValue('User_LoggedInGroup') );
$this->Application->StoreVar( 'UserGroups', implode(',', $groups) );
if ($this->checkLoginPermission($login_value)) {
$session =& $this->Application->recallObject('Session');
$session->SetField('PortalUserId', $user_id);
$session->SetField('GroupList', implode(',', $groups) );
$this->Application->SetVar('u.current_id', $user_id);
$this->Application->StoreVar('user_id', $user_id);
$this_login = (int)$object->getPersistantVar('ThisLogin');
$object->setPersistantVar('LastLogin', $this_login);
$object->setPersistantVar('ThisLogin', adodb_mktime());
}
else {
$object->Load(-2);
$object->SetError('ValidateLogin', 'no_permission', 'lu_no_permissions');
$event->status = erFAIL;
}
$this->processLoginRedirect($event, $password);
}
else {
$event->redirect = $this->Application->GetVar('pending_disabled_template');
}
}
else
{
$object->SetID(-2);
$object->SetError('ValidateLogin', 'invalid_password', $invalid_pseudo);
$event->status = erFAIL;
}
$event->SetRedirectParam('pass', 'all');
// $event->SetRedirectParam('pass_category', 1); // to test
}
/**
* Checks that user is allowed to use super admin mode
*
* @return bool
*/
function verifySuperAdmin()
{
$sa_mode = ipMatch(defined('SA_IP') ? SA_IP : '');
return $sa_mode || $this->Application->isDebugMode();
}
/**
* Enter description here...
*
* @param string $user_name
* @return bool
*/
function checkLoginPermission($user_name)
{
$ret = true;
if ($this->Application->IsAdmin()) {
$modules_helper =& $this->Application->recallObject('ModulesHelper');
if ($user_name != 'root') {
// root is virtual user, so allow him to login to admin in any case
$ret = $this->Application->CheckPermission('ADMIN', 1);
}
$ret = $ret && $modules_helper->checkLogin();
}
else {
$ret = $this->Application->CheckPermission('LOGIN', 1);
}
return $ret;
}
/**
* Process all required data and redirect logged-in user
*
* @param kEvent $event
*/
function processLoginRedirect(&$event, $password)
{
$prefix_special = $this->Application->IsAdmin() ? 'u.current' : 'u'; // "u" used on front not to change theme
$object =& $this->Application->recallObject($prefix_special, null, Array('skip_autoload' => true));
$next_template = $this->Application->GetVar('next_template');
if ($next_template == '_ses_redirect') {
$location = $this->Application->BaseURL().$this->Application->RecallVar($next_template);
if( $this->Application->isDebugMode() && constOn('DBG_REDIRECT') )
{
$this->Application->Debugger->appendTrace();
echo "<b>Debug output above!!!</b> Proceed to redirect: <a href=\"$location\">$location</a><br>";
}
else {
header('Location: '.$location);
}
$session =& $this->Application->recallObject('Session');
$session->SaveData();
exit;
}
if ($next_template) {
$event->redirect = $next_template;
}
if ($this->Application->ConfigValue('UseJSRedirect')) {
$event->SetRedirectParam('js_redirect', 1);
}
$sync_manager =& $this->Application->recallObjectP('UsersSyncronizeManager', null, Array(), 'InPortalSyncronize');
$sync_manager->performAction('LoginUser', $object->GetDBField('Login'), $password);
$this->Application->resetCounters('UserSession');
}
/**
* Called when user logs in using old in-portal
*
* @param kEvent $event
*/
function OnInpLogin(&$event)
{
$sync_manager =& $this->Application->recallObjectP('UsersSyncronizeManager', null, Array(), 'InPortalSyncronize');
$sync_manager->performAction('LoginUser', $event->getEventParam('user'), $event->getEventParam('pass') );
if ($event->redirect && is_string($event->redirect)) {
// some real template specified instead of true
$this->Application->Redirect($event->redirect, $event->redirect_params);
}
}
/**
* Called when user logs in using old in-portal
*
* @param kEvent $event
*/
function OnInpLogout(&$event)
{
$sync_manager =& $this->Application->recallObjectP('UsersSyncronizeManager', null, Array(), 'InPortalSyncronize');
$sync_manager->performAction('LogoutUser');
}
function OnLogout(&$event)
{
$sync_manager =& $this->Application->recallObjectP('UsersSyncronizeManager', null, Array(), 'InPortalSyncronize');
$sync_manager->performAction('LogoutUser');
$session =& $this->Application->recallObject('Session');
$session->SetField('PortalUserId', -2);
$this->Application->SetVar('u.current_id', -2);
$this->Application->StoreVar('user_id', -2);
$object =& $this->Application->recallObject('u.current', null, Array('skip_autoload' => true));
$object->Load(-2);
$this->Application->DestroySession();
$group_list = $this->Application->ConfigValue('User_GuestGroup').','.$this->Application->ConfigValue('User_LoggedInGroup');
$session->SetField('GroupList', $group_list);
$this->Application->StoreVar('UserGroups', $group_list);
if ($this->Application->ConfigValue('UseJSRedirect')) {
$event->SetRedirectParam('js_redirect', 1);
}
$this->Application->resetCounters('UserSession');
$event->SetRedirectParam('pass', 'all');
}
/**
* Prefill states dropdown with correct values
*
* @param kEvent $event
* @access public
*/
function OnPrepareStates(&$event)
{
$cs_helper =& $this->Application->recallObject('CountryStatesHelper');
$cs_helper->PopulateStates($event, 'State', 'Country');
$object =& $event->getObject();
if( $object->isRequired('Country') && $cs_helper->CountryHasStates( $object->GetDBField('Country') ) ) $object->setRequired('State', true);
$object->setLogin();
}
/**
* Redirects user after succesfull registration to confirmation template (on Front only)
*
* @param kEvent $event
*/
function OnAfterItemCreate(&$event)
{
+ if ($this->Application->GetVar('skip_set_primary')) return;
$is_subscriber = $this->Application->GetVar('IsSubscriber');
if(!$is_subscriber)
{
$object =& $event->getObject();
$ug_table = TABLE_PREFIX.'UserGroup';
if ($object->mode == 't') {
$ug_table = $this->Application->GetTempName($ug_table, 'prefix:'.$event->Prefix);
}
$sql = 'UPDATE '.$ug_table.'
SET PrimaryGroup = 0
WHERE PortalUserId = '.$object->GetDBField('PortalUserId');
$this->Conn->Query($sql);
// set primary group to user
if ($this->Application->IsAdmin() && $this->Application->GetVar('user_group')) {
// while in admin you can set any group for new users
$group_id = $this->Application->GetVar('user_group');
}
else {
$group_id = $this->Application->ConfigValue('User_NewGroup');
}
$sql = 'REPLACE INTO '.$ug_table.'(PortalUserId,GroupId,PrimaryGroup) VALUES (%s,%s,1)';
$this->Conn->Query( sprintf($sql, $object->GetID(), $group_id) );
}
}
/**
* Login user if possible, if not then redirect to corresponding template
*
* @param kEvent $event
*/
function autoLoginUser(&$event)
{
$object =& $event->getObject();
$this->Application->SetVar('u.current_id', $object->GetID() );
if($object->GetDBField('Status') == STATUS_ACTIVE && !$this->Application->ConfigValue('User_Password_Auto'))
{
$email_as_login = $this->Application->ConfigValue('Email_As_Login');
list($login_field, $submit_field) = $email_as_login ? Array('Email', 'email') : Array('Login', 'login');
$this->Application->SetVar($submit_field, $object->GetDBField($login_field) );
$this->Application->SetVar('password', $object->GetDBField('Password_plain') );
$event->CallSubEvent('OnLogin');
}
}
/**
* When creating user & user with such email exists then force to use OnUpdate insted of ?
*
* @param kEvent $event
*/
function OnSubstituteSubscriber(&$event)
{
$ret = false;
$object =& $event->getObject( Array('skip_autoload' => true) );
$items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) );
if($items_info)
{
list($id, $field_values) = each($items_info);
$user_email = isset($field_values['Email']) ? $field_values['Email'] : false;
if($user_email)
{
// check if is subscriber
$verify_user =& $this->Application->recallObject('u.verify', null, Array('skip_autoload' => true) );
$verify_user->Load($user_email, 'Email');
if( $verify_user->isLoaded() && $verify_user->isSubscriberOnly() )
{
$items_info = Array( $verify_user->GetDBField('PortalUserId') => $field_values );
$this->Application->SetVar($event->getPrefixSpecial(true), $items_info);
$ret = true;
}
}
}
if( isset($event->MasterEvent) )
{
$event->MasterEvent->setEventParam('is_subscriber_only', $ret);
}
else
{
$event->setEventParam('is_subscriber_only', $ret);
}
}
/**
* Enter description here...
*
* @param kEvent $event
* @return bool
*/
function isSubscriberOnly(&$event)
{
$event->CallSubEvent('OnSubstituteSubscriber');
$is_subscriber = false;
if( $event->getEventParam('is_subscriber_only') )
{
$is_subscriber = true;
$object =& $event->getObject( Array('skip_autoload' => true) );
$this->OnUpdate($event);
if($event->status == erSUCCESS)
{
$this->OnAfterItemCreate($event);
$object->SendEmailEvents();
if( !$this->Application->IsAdmin() && ($event->status == erSUCCESS) && $event->redirect) $this->autoLoginUser($event);
}
}
return $is_subscriber;
}
/**
* Creates new user
*
* @param kEvent $event
*/
function OnCreate(&$event)
{
if( !$this->Application->IsAdmin() ) $this->setUserStatus($event);
if( !$this->isSubscriberOnly($event) )
{
$cs_helper =& $this->Application->recallObject('CountryStatesHelper');
$cs_helper->CheckStateField($event, 'State', 'Country');
$object =& $event->getObject( Array('skip_autoload' => true) );
/* @var $object kDBItem */
if ($this->Application->ConfigValue('User_Password_Auto')) {
$pass = makepassword4(rand(5,8));
$object->SetField('Password', $pass);
$object->SetField('VerifyPassword', $pass);
$this->Application->SetVar('user_password',$pass);
}
parent::OnCreate($event);
$this->Application->SetVar('u.current_id', $object->getID() ); // for affil:OnRegisterAffiliate after hook
$this->setNextTemplate($event);
if( !$this->Application->IsAdmin() && ($event->status == erSUCCESS) && $event->redirect)
{
$object->SendEmailEvents();
$this->autoLoginUser($event);
}
}
}
/**
* Set's new user status based on config options
*
* @param kEvent $event
*/
function setUserStatus(&$event)
{
$object =& $event->getObject( Array('skip_autoload' => true) );
$new_users_allowed = $this->Application->ConfigValue('User_Allow_New');
// 1 - Instant, 2 - Not Allowed, 3 - Pending
switch ($new_users_allowed)
{
case 1: // Instant
$object->SetDBField('Status', 1);
$next_template = $this->Application->GetVar('registration_confirm_template');
if($next_template) $event->redirect = $next_template;
break;
case 3: // Pending
$next_template = $this->Application->GetVar('registration_confirm_pending_template');
if($next_template) $event->redirect = $next_template;
$object->SetDBField('Status', 2);
break;
case 2: // Not Allowed
$object->SetDBField('Status', 0);
break;
}
/*if ($object->GetDBField('PaidMember') == 1) {
$this->Application->HandleEvent($add_to_cart, 'ord:OnAddToCart');
$event->redirect = 'in-commerce/checkout/shop_cart';
} */
}
/**
* Set's new unique resource id to user
*
* @param kEvent $event
*/
function OnBeforeItemCreate(&$event)
{
$email_as_login = $this->Application->ConfigValue('Email_As_Login');
$object =& $event->getObject();
if ($email_as_login) {
$object->Fields['Email']['error_msgs']['unique'] = $this->Application->Phrase('lu_user_and_email_already_exist');
}
}
/**
* Set's new unique resource id to user
*
* @param kEvent $event
*/
function OnAfterItemValidate(&$event)
{
$object =& $event->getObject();
$resource_id = $object->GetDBField('ResourceId');
if (!$resource_id)
{
$object->SetDBField('ResourceId', $this->Application->NextResourceId() );
}
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function OnRecommend(&$event)
{
$friend_email = $this->Application->GetVar('friend_email');
$friend_name = $this->Application->GetVar('friend_email');
// used for error reporting only -> rewrite code + theme (by Alex)
$object =& $this->Application->recallObject('u', null, Array('skip_autoload' => true)); // TODO: change theme too
/* @var $object UsersItem */
if (preg_match("/^[_a-zA-Z0-9-\.]+@[a-zA-Z0-9-\.]+\.[a-z]{2,4}$/", $friend_email))
{
$send_params = array();
$send_params['to_email']=$friend_email;
$send_params['to_name']=$friend_name;
$user_id = $this->Application->RecallVar('user_id');
$email_event =& $this->Application->EmailEventUser('SITE.SUGGEST', $user_id, $send_params);
if ($email_event->status == erSUCCESS){
$event->redirect_params = array('opener' => 's', 'pass' => 'all');
$event->redirect = $this->Application->GetVar('template_success');
}
else {
// $event->redirect_params = array('opener' => 's', 'pass' => 'all');
// $event->redirect = $this->Application->GetVar('template_fail');
$object->SetError('Email', 'send_error', 'lu_email_send_error');
$event->status = erFAIL;
}
}
else {
$object->SetError('Email', 'invalid_email', 'lu_InvalidEmail');
$event->status = erFAIL;
}
}
/**
* Saves address changes and mades no redirect
*
* @param kEvent $event
*/
function OnUpdateAddress(&$event)
{
$object =& $event->getObject( Array('skip_autoload' => true) );
$items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) );
if($items_info)
{
list($id,$field_values) = each($items_info);
if($id > 0) $object->Load($id);
$object->SetFieldsFromHash($field_values);
$object->setID($id);
$object->Validate();
}
$event->redirect = false;
}
/**
* Validate subscriber's email & store it to session -> redirect to confirmation template
*
* @param kEvent $event
*/
function OnSubscribeQuery(&$event)
{
$user_email = $this->Application->GetVar('subscriber_email');
if (preg_match("/^[_a-zA-Z0-9-\.]+@[a-zA-Z0-9-\.]+\.[a-z]{2,4}$/", $user_email)) {
$object =& $this->Application->recallObject($this->Prefix.'.subscriber', null, Array('skip_autoload' => true));
/* @var $object UsersItem */
$this->Application->StoreVar('SubscriberEmail', $user_email);
$object->Load($user_email, 'Email');
if ($object->isLoaded()) {
$group_info = $this->GetGroupInfo($object->GetID());
$event->redirect = $this->Application->GetVar($group_info ? 'unsubscribe_template' : 'subscribe_template');
}
else {
$event->redirect = $this->Application->GetVar('subscribe_template');
$this->Application->StoreVar('SubscriberEmail', $user_email);
}
}
else {
// used for error reporting only -> rewrite code + theme (by Alex)
$object =& $this->Application->recallObject('u', null, Array('skip_autoload' => true)); // TODO: change theme too
/* @var $object UsersItem */
$object->SetError('SubscribeEmail', 'invalid_email', 'lu_InvalidEmail');
$event->status = erFAIL;
}
}
/**
* Subscribe/Unsubscribe user based on email stored in previous step
*
* @param kEvent $event
*/
function OnSubscribeUser(&$event)
{
$object = &$this->Application->recallObject($this->Prefix.'.subscriber', null, Array('skip_autoload' => true));
/* @var $object UsersItem */
$user_email = $this->Application->RecallVar('SubscriberEmail');
if (preg_match("/^[_a-zA-Z0-9-\.]+@[a-zA-Z0-9-\.]+\.[a-z]{2,4}$/", $user_email)) {
$this->RemoveRequiredFields($object);
$object->Load($user_email, 'Email');
if ($object->isLoaded()) {
$group_info = $this->GetGroupInfo($object->GetID());
if ($group_info){
if ($event->getEventParam('no_unsubscribe')) return;
if ($group_info['PrimaryGroup']){
// delete user
$object->Delete();
}
else {
$this->RemoveSubscriberGroup($object->GetID());
}
$event->redirect = $this->Application->GetVar('unsubscribe_ok_template');
}
else {
$this->AddSubscriberGroup($object->GetID(), 0);
$event->redirect = $this->Application->GetVar('subscribe_ok_template');
}
}
else {
$object->SetField('Email', $user_email);
$object->SetField('Login', $user_email);
$object->SetDBField('dob', 1);
$object->SetDBField('dob_date', 1);
$object->SetDBField('dob_time', 1);
$ip = getenv('HTTP_X_FORWARDED_FOR')?getenv('HTTP_X_FORWARDED_FOR'):getenv('REMOTE_ADDR');
$object->SetDBField('ip', $ip);
$this->Application->SetVar('IsSubscriber', 1);
if ($object->Create()) {
$this->AddSubscriberGroup($object->GetID(), 1);
$event->redirect = $this->Application->GetVar('subscribe_ok_template');
}
$this->Application->SetVar('IsSubscriber', 0);
}
}
}
function AddSubscriberGroup($user_id, $is_primary){
$group_id = $this->Application->ConfigValue('User_SubscriberGroup');
$sql = 'INSERT INTO '.TABLE_PREFIX.'UserGroup(PortalUserId,GroupId,PrimaryGroup) VALUES (%s,%s,'.$is_primary.')';
$this->Conn->Query( sprintf($sql, $user_id, $group_id) );
$this->Application->EmailEventAdmin('USER.SUBSCRIBE', $user_id);
$this->Application->EmailEventUser('USER.SUBSCRIBE', $user_id);
}
function RemoveSubscriberGroup($user_id){
$group_id = $this->Application->ConfigValue('User_SubscriberGroup');
$sql = 'DELETE FROM '.TABLE_PREFIX.'UserGroup WHERE PortalUserId='.$user_id.' AND GroupId='.$this->Application->ConfigValue('User_SubscriberGroup');
$this->Conn->Query($sql);
$this->Application->EmailEventAdmin('USER.UNSUBSCRIBE', $user_id);
$this->Application->EmailEventUser('USER.UNSUBSCRIBE', $user_id);
}
/**
* Allows to detect user subscription status (subscribed or not)
*
* @param int $user_id
* @return bool
*/
function GetGroupInfo($user_id)
{
$sql = 'SELECT *
FROM '.TABLE_PREFIX.'UserGroup
WHERE (PortalUserId = '.$user_id.') AND (GroupId = '.$this->Application->ConfigValue('User_SubscriberGroup').')';
return $this->Conn->GetRow($sql);
}
function OnForgotPassword(&$event)
{
$user_object =& $this->Application->recallObject('u.forgot', null, Array('skip_autoload' => true));
/* @var $user_object UsersItem */
// used for error reporting only -> rewrite code + theme (by Alex)
$user_current_object =& $this->Application->recallObject('u', null, Array('skip_autoload' => true)); // TODO: change theme too
/* @var $user_current_object UsersItem */
$username = $this->Application->GetVar('username');
$email = $this->Application->GetVar('email');
$found = false;
$allow_reset = true;
if (strlen($username)) {
$user_object->Load($username, 'Login');
if ($user_object->isLoaded()) {
$found = ($user_object->GetDBField("Login")==$username && $user_object->GetDBField("Status")==1) && strlen($user_object->GetDBField("Password"));
}
}
else if(strlen($email)) {
$user_object->Load($email, 'Email');
if ($user_object->isLoaded()) {
$found = ($user_object->GetDBField("Email")==$email && $user_object->GetDBField("Status")==1) && strlen($user_object->GetDBField("Password"));
}
}
if ($user_object->isLoaded()) {
$PwResetConfirm = $user_object->GetDBField('PwResetConfirm');
$PwRequestTime = $user_object->GetDBField('PwRequestTime');
$PassResetTime = $user_object->GetDBField('PassResetTime');
//$MinPwResetDelay = $user_object->GetDBField('MinPwResetDelay');
$MinPwResetDelay = $this->Application->ConfigValue('Users_AllowReset');
$allow_reset = (strlen($PwResetConfirm) ?
adodb_mktime() > $PwRequestTime + $MinPwResetDelay :
adodb_mktime() > $PassResetTime + $MinPwResetDelay);
}
if ($found && $allow_reset) {
$this->Application->StoreVar('tmp_user_id', $user_object->GetDBField("PortalUserId"));
$this->Application->StoreVar('tmp_email', $user_object->GetDBField("Email"));
$confirm_template = $this->Application->GetVar('reset_confirm_template');
if (!$confirm_template) {
$this->Application->SetVar('reset_confirm_template', 'platform/login/forgotpass_reset');
}
$this->Application->EmailEventUser('USER.PSWDC', $user_object->GetDBField('PortalUserId'));
$event->redirect = $this->Application->GetVar('template_success');
}
else {
if (!strlen($username) && !strlen($email)) {
$user_current_object->SetError('Login', 'forgotpw_nodata', 'lu_ferror_forgotpw_nodata');
$user_current_object->SetError('Email', 'forgotpw_nodata', 'lu_ferror_forgotpw_nodata');
}
else {
if ($allow_reset) {
if (strlen($username)) {
$user_current_object->SetError('Login', 'unknown_username', 'lu_ferror_unknown_username');
}
if (strlen($email)) {
$user_current_object->SetError('Email', 'unknown_email', 'lu_ferror_unknown_email');
}
}
else {
if (strlen($username)) {
$user_current_object->SetError('Login', 'reset_denied', 'lu_ferror_reset_denied');
}
if (strlen($email)) {
$user_current_object->SetError('Email', 'reset_denied', 'lu_ferror_reset_denied');
}
}
}
if($user_current_object->FieldErrors){
$event->redirect = false;
}
}
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function OnResetPassword(&$event)
{
$user_object =& $this->Application->recallObject('u.forgot');
if($user_object->Load($this->Application->RecallVar('tmp_user_id'))){
$this->Application->EmailEventUser('USER.PSWDC', $user_object->GetDBField("PortalUserId"));
$event->redirect = $this->Application->GetVar('template_success');
$m_cat_id = $this->Application->findModule('Name', 'In-Commerce', 'RootCat');
$this->Application->SetVar('m_cat_id', $m_cat_id);
$event->SetRedirectParam('pass', 'm');
}
}
function OnResetPasswordConfirmed(&$event)
{
// used for error reporting only -> rewrite code + theme (by Alex)
$user_current_object =& $this->Application->recallObject('u', null, Array('skip_autoload' => true));// TODO: change theme too
/* @var $user_current_object UsersItem */
$passed_key = trim($this->Application->GetVar('user_key'));
if (!$passed_key) {
$event->redirect_params = Array('opener' => 's', 'pass' => 'all');
$event->redirect = false;
$user_current_object->SetError('PwResetConfirm', 'code_is_not_valid', 'lu_code_is_not_valid');
}
$user_object =& $this->Application->recallObject('u.forgot', null, Array('skip_autoload' => true));
/* @var $user_object UsersItem */
$user_object->Load($passed_key, 'PwResetConfirm');
if ($user_object->isLoaded()) {
$exp_time = $user_object->GetDBField('PwRequestTime') + 3600;
$user_object->SetDBField('PwResetConfirm', '');
$user_object->SetDBField('PwRequestTime', 0);
if ($exp_time > adodb_mktime()) {
$newpw = makepassword4();
$this->Application->StoreVar('password', $newpw);
$user_object->SetDBField('Password', $newpw);
$user_object->SetDBField('PassResetTime', adodb_mktime());
$user_object->SetDBField('PwResetConfirm', '');
$user_object->SetDBField('PwRequestTime', 0);
$user_object->Update();
$this->Application->SetVar('ForgottenPassword', $newpw);
$email_event_user =& $this->Application->EmailEventUser('USER.PSWD', $user_object->GetDBField('PortalUserId'));
$email_event_admin =& $this->Application->EmailEventAdmin('USER.PSWD');
$this->Application->DeleteVar('ForgottenPassword');
if ($email_event_user->status == erSUCCESS) {
$event->redirect_params = array('opener' => 's', 'pass' => 'all');
$event->redirect = $this->Application->GetVar('template_success');
}
$user_object->SetDBField('Password', md5($newpw));
$user_object->Update();
} else {
$user_current_object->SetError('PwResetConfirm', 'code_expired', 'lu_code_expired');
$event->redirect = false;
}
} else {
$user_current_object->SetError('PwResetConfirm', 'code_is_not_valid', 'lu_code_is_not_valid');
$event->redirect = false;
}
}
function OnUpdate(&$event)
{
$cs_helper =& $this->Application->recallObject('CountryStatesHelper');
$cs_helper->CheckStateField($event, 'State', 'Country');
parent::OnUpdate($event);
$this->setNextTemplate($event);
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function setNextTemplate(&$event)
{
if( !$this->Application->IsAdmin() )
{
$event->redirect_params['opener'] = 's';
$object =& $event->getObject();
if($object->GetDBField('Status') == STATUS_ACTIVE)
{
$next_template = $this->Application->GetVar('next_template');
if($next_template) $event->redirect = $next_template;
}
}
}
/**
* Delete users from groups if their membership is expired
*
* @param kEvent $event
*/
function OnCheckExpiredMembership(&$event)
{
// send pre-expiration reminders: begin
$pre_expiration = adodb_mktime() + $this->Application->ConfigValue('User_MembershipExpirationReminder') * 3600 * 24;
$sql = 'SELECT PortalUserId, GroupId
FROM '.TABLE_PREFIX.'UserGroup
WHERE (MembershipExpires IS NOT NULL) AND (ExpirationReminderSent = 0) AND (MembershipExpires < '.$pre_expiration.')';
$skip_clause = $event->getEventParam('skip_clause');
if ($skip_clause) {
$sql .= ' AND !('.implode(') AND !(', $skip_clause).')';
}
$records = $this->Conn->Query($sql);
if ($records) {
$conditions = Array();
foreach ($records as $record) {
$email_event_user =& $this->Application->EmailEventUser('USER.MEMBERSHIP.EXPIRATION.NOTICE', $record['PortalUserId']);
$email_event_admin =& $this->Application->EmailEventAdmin('USER.MEMBERSHIP.EXPIRATION.NOTICE');
$conditions[] = '(PortalUserId = '.$record['PortalUserId'].' AND GroupId = '.$record['GroupId'].')';
}
$sql = 'UPDATE '.TABLE_PREFIX.'UserGroup
SET ExpirationReminderSent = 1
WHERE '.implode(' OR ', $conditions);
$this->Conn->Query($sql);
}
// send pre-expiration reminders: end
// remove users from groups with expired membership: begin
$sql = 'SELECT PortalUserId
FROM '.TABLE_PREFIX.'UserGroup
WHERE (MembershipExpires IS NOT NULL) AND (MembershipExpires < '.adodb_mktime().')';
$user_ids = $this->Conn->GetCol($sql);
if ($user_ids) {
foreach ($user_ids as $id) {
$email_event_user =& $this->Application->EmailEventUser('USER.MEMBERSHIP.EXPIRED', $id);
$email_event_admin =& $this->Application->EmailEventAdmin('USER.MEMBERSHIP.EXPIRED');
}
}
$sql = 'DELETE FROM '.TABLE_PREFIX.'UserGroup
WHERE (MembershipExpires IS NOT NULL) AND (MembershipExpires < '.adodb_mktime().')';
$this->Conn->Query($sql);
// remove users from groups with expired membership: end
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function OnRefreshForm(&$event)
{
$event->redirect = false;
$item_info = $this->Application->GetVar($event->Prefix_Special);
list($id, $fields) = each($item_info);
$object =& $event->getObject( Array('skip_autoload' => true) );
$object->setID($id);
$object->IgnoreValidation = true;
$object->SetFieldsFromHash($fields);
}
/**
* Sets persistant variable
*
* @param kEvent $event
*/
function OnSetPersistantVariable(&$event)
{
$object =& $event->getObject();
$field = $this->Application->GetVar('field');
$value = $this->Application->GetVar('value');
$object->setPersistantVar($field, $value);
$force_tab = $this->Application->GetVar('SetTab');
if ($force_tab) {
$this->Application->StoreVar('force_tab', $force_tab);
}
}
/**
* Overwritten to return user from order by special .ord
*
* @param kEvent $event
*/
function getPassedID(&$event)
{
switch ($event->Special) {
case 'ord':
$order =& $this->Application->recallObject('ord');
/* @var $order OrdersItem */
$id = $order->GetDBField('PortalUserId');
break;
case 'profile':
$id = $this->Application->GetVar('user_id');
if (!$id) {
// if none user_id given use current user id
$id = $this->Application->RecallVar('user_id');
}
break;
default:
$id = parent::getPassedID($event);
break;
}
return $id;
}
/**
* Allows to change root password
*
* @param kEvent $event
*/
function OnUpdateRootPassword(&$event)
{
+ return $this->OnUpdatePassword($event);
+ }
+
+ /**
+ * Allows to change root password
+ *
+ * @param kEvent $event
+ */
+ function OnUpdatePassword(&$event)
+ {
+ $items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) );
+ if (!$items_info) return ;
+ list ($id, $field_values) = each($items_info);
$user_id = $this->Application->RecallVar('user_id');
- if ($user_id != -1) {
- // not "root" can't change root's password via this event
+ if ($id == $user_id && ($user_id > 0 || $user_id == -1)) {
+ $user_dummy =& $this->Application->recallObject($event->Prefix.'.-item', null, Array('skip_autoload' => true));
+ /* @var $user_dummy kDBItem */
+
+ $user_dummy->Load($id);
+ $status_field = array_shift($this->Application->getUnitOption($event->Prefix, 'StatusField'));
+
+ if ($user_dummy->GetDBField($status_field) != STATUS_ACTIVE) {
+ // not active user is not allowed to update his record (he could not activate himself manually)
return false;
}
+ }
+
+ if ($user_id == -1) {
+ $object =& $event->getObject( Array('skip_autoload' => true) );
+ /* @var $object UsersItem */
// put salt to user's config
- $field_options = $this->Application->getUnitOption($event->Prefix.'.RootPassword', 'Fields');
+ $field_options = $object->GetFieldOptions('RootPassword');
$field_options['salt'] = 'b38';
- $this->Application->setUnitOption($event->Prefix.'.RootPassword', 'Fields', $field_options);
-
- $object =& $event->getObject( Array('skip_autoload' => true) );
- /* @var $object UsersItem */
-
- $items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) );
- if ($items_info) {
- list ($id, $field_values) = each($items_info);
+ $object->SetFieldOptions('RootPassword', $field_options);
+ $verify_options = $object->GetFieldOptions('VerifyRootPassword');
+ $verify_options['salt'] = 'b38';
+ $object->SetFieldOptions('VerifyRootPassword', $verify_options);
+
+ // this is internal hack to allow root/root passwords for dev
+ if ($this->Application->isDebugMode() && $field_values['RootPassword'] == 'root') {
+ $this->Application->ConfigHash['Min_Password'] = 4;
+ }
+
$this->RemoveRequiredFields($object);
$object->SetDBField('RootPassword', $this->Application->ConfigValue('RootPass'));
$object->SetFieldsFromHash($field_values);
+ $object->setID(-1);
$status = $object->Validate();
if ($status) {
// validation on, password match too
$fields_hash = Array (
'VariableValue' => $object->GetDBField('RootPassword')
);
$conf_table = $this->Application->getUnitOption('conf', 'TableName');
$this->Conn->doUpdate($fields_hash, $conf_table, 'VariableName = "RootPass"');
$event->SetRedirectParam('opener', 'u');
}
else {
$event->status = erFAIL;
$event->redirect = false;
+ return;
}
}
+ else {
+ $object =& $event->getObject();
+ $object->SetFieldsFromHash($field_values);
+ if (!$object->Update()) {
+ $event->status = erFAIL;
+ $event->redirect = false;
+ }
+ }
+ $event->SetRedirectParam('opener', 'u');
+ $event->redirect == true;
}
/**
* Apply some special processing to
* object beeing recalled before using
* it in other events that call prepareObject
*
* @param Object $object
* @param kEvent $event
* @access protected
*/
function prepareObject(&$object, &$event)
{
parent::prepareObject($object, $event);
if (!$this->Application->IsAdmin()) {
if ($this->Application->RecallVar('register_captcha_code')) return ;
$captcha_helper =& $this->Application->recallObject('CaptchaHelper');
/* @var $captcha_helper kCaptchaHelper */
$this->Application->StoreVar('register_captcha_code', $captcha_helper->GenerateCaptchaCode());
}
}
/**
* Apply custom processing to item
*
* @param kEvent $event
*/
function customProcessing(&$event, $type)
{
if ($event->Name == 'OnCreate' && $type == 'before') {
$object =& $event->getObject();
/* @var $object kDBItem */
// if auto password has not been set already - store real one - to be used in email events
if (!$this->Application->GetVar('user_password')) {
$this->Application->SetVar('user_password', $object->GetDirtyField('Password'));
$object->SetDBField('Password_plain', $object->GetDirtyField('Password'));
}
// Validate captcha image if it's requried
if ($this->Application->ConfigValue('RegistrationCaptcha') && $object->GetDBField('Captcha') != $this->Application->RecallVar('register_captcha_code')) {
$object->SetError('Captcha', 'captcha_error', 'lu_captcha_error');
$captcha_helper =& $this->Application->recallObject('CaptchaHelper');
/* @var $captcha_helper kCaptchaHelper */
$this->Application->StoreVar('register_captcha_code', $captcha_helper->GenerateCaptchaCode());
}
}
}
function OnMassResetSettings(&$event)
{
if ($this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1)) {
return;
}
$event->status=erSUCCESS;
$ids = $this->StoreSelectedIDs($event);
$default_user_id = $this->Application->ConfigValue('DefaultSettingsUserId');
if (in_array($default_user_id, $ids)) {
array_splice($ids, array_search($default_user_id, $ids), 1);
}
if ($ids) {
$q = 'DELETE FROM '.TABLE_PREFIX.'PersistantSessionData WHERE PortalUserId IN ('.join(',', $ids).') AND
(VariableName LIKE "%_columns_%"
OR
VariableName LIKE "%_filter%"
OR
VariableName LIKE "%_PerPage%")';
$this->Conn->Query($q);
}
$this->clearSelectedIDs($event);
}
/**
* Checks, that currently loaded item is allowed for viewing (non permission-based)
*
* @param kEvent $event
* @return bool
*/
function checkItemStatus(&$event)
{
$object =& $event->getObject();
if (!$object->isLoaded()) {
return true;
}
$virtual_users = Array (-1, -2); // root, Guest
return ($object->GetDBField('Status') == STATUS_ACTIVE) || in_array($object->GetID(), $virtual_users);
}
/**
* Sends approved/declined email event on user status change
*
* @param kEvent $event
*/
function OnAfterItemUpdate(&$event)
{
$object =& $event->getObject();
/* @var $object UsersItem */
if (!$this->Application->IsAdmin() || $object->IsTempTable()) {
return ;
}
$this->sendStatusChangeEvent($object->GetID(), $object->GetOriginalField('Status'), $object->GetDBField('Status'));
}
/**
* Stores user's original Status before overwriting with data from temp table
*
* @param kEvent $event
*/
function OnBeforeDeleteFromLive(&$event)
{
$user_status = $this->Application->GetVar('user_status');
if (!$user_status) {
$user_status = Array ();
}
$user_id = $event->getEventParam('id');
if ($user_id > 0) {
$user_status[$user_id] = $this->getUserStatus($user_id);
$this->Application->SetVar('user_status', $user_status);
}
}
/**
* Sends approved/declined email event on user status change (in temp tables during editing)
*
* @param kEvent $event
*/
function OnAfterCopyToLive(&$event)
{
$temp_id = $event->getEventParam('temp_id');
if ($temp_id == 0) {
// this is new user create, don't send email events
return ;
}
$new_status = $this->getUserStatus($temp_id);
$user_status = $this->Application->GetVar('user_status');
$this->sendStatusChangeEvent($temp_id, $user_status[$temp_id], $new_status);
}
/**
* Returns user status (active, pending, disabled) based on ID and temp mode setting
*
* @param int $user_id
* @return int
*/
function getUserStatus($user_id)
{
$id_field = $this->Application->getUnitOption($this->Prefix, 'IDField');
$table_name = $this->Application->getUnitOption($this->Prefix, 'TableName');
$sql = 'SELECT Status
FROM '.$table_name.'
WHERE '.$id_field.' = '.$user_id;
return $this->Conn->GetOne($sql);
}
/**
* Sends approved/declined email event on user status change
*
* @param int $user_id
* @param int $prev_status
* @param int $new_status
*/
function sendStatusChangeEvent($user_id, $prev_status, $new_status)
{
$status_events = Array (
STATUS_ACTIVE => 'USER.APPROVE',
STATUS_DISABLED => 'USER.DENY',
);
$email_event = isset($status_events[$new_status]) ? $status_events[$new_status] : false;
if (($prev_status != $new_status) && $email_event) {
$this->Application->EmailEventUser($email_event, $user_id);
$this->Application->EmailEventAdmin($email_event);
}
}
/**
* OnAfterConfigRead for users
*
* @param kEvent $event
*/
function OnAfterConfigRead(&$event)
{
parent::OnAfterConfigRead($event);
$first_country = $this->Application->ConfigValue('User_Default_Registration_Country');
if ($first_country) {
// update user country dropdown sql
$fields = $this->Application->getUnitOption($event->Prefix, 'Fields');
$fields['Country']['options_sql'] = preg_replace('/ORDER BY (.*)/', 'ORDER BY IF (DestId = '.$first_country.', 1, 0) DESC, \\1', $fields['Country']['options_sql']);
$this->Application->setUnitOption($event->Prefix, 'Fields', $fields);
}
}
+
+ /**
+ * OnMassCloneUsers
+ *
+ * @param kEvent $event
+ */
+ function OnMassCloneUsers(&$event)
+ {
+ if ($this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1)) {
+ return;
+ }
+
+ $event->status=erSUCCESS;
+ $ids = $this->StoreSelectedIDs($event);
+
+ $this->Application->SetVar('skip_set_primary', 1); // otherwise it will default primary group, search for skip_set_primary above
+ $temp_handler =& $this->Application->recallObject($event->Prefix.'_TempHandler', 'kTempTablesHandler');
+ /* @var $temp_handler kTempTablesHandler */
+ $cloned_users = $temp_handler->CloneItems($event->Prefix, '', $ids);
+ $this->clearSelectedIDs($event);
+ }
+
+ /**
+ * When cloning users, reset password (set random)
+ *
+ * @param kEvent $event
+ */
+ function OnBeforeClone(&$event)
+ {
+ $object =& $event->getObject();
+ /* @var $object kDBItem */
+ $object->setRequired('Password', 0);
+ $object->setRequired('VerifyPassword', 0);
+ $object->SetDBField('Password', rand(100000000, 999999999));
+ $object->SetDBField('CreatedOn', adodb_mktime());
+ $object->SetDBField('ResourceId', false); // this will reset it
+
+ // change email cause it should be unique
+ $object->NameCopy(array(), $object->GetID(), 'Email', 'copy%1$s.%2$s');
+
+ $object->UpdateFormattersSubFields();
+ }
+
+ /**
+ * Copy user groups after copying user
+ *
+ * @param kEvent $event
+ */
+ function OnAfterClone(&$event)
+ {
+ $id = $event->getEventParam('id');
+ $original_id = $event->getEventParam('original_id');
+
+ $sql = 'INSERT '.TABLE_PREFIX."UserGroup SELECT $id, GroupId, MembershipExpires, PrimaryGroup, 0 FROM ".TABLE_PREFIX."UserGroup WHERE PortalUserId = $original_id";
+ $this->Conn->Query($sql);
+ }
+
}
?>
\ No newline at end of file
Property changes on: branches/RC/core/units/users/users_event_handler.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.87.2.9
\ No newline at end of property
+1.87.2.10
\ No newline at end of property
Index: branches/RC/core/units/user_groups/user_groups_eh.php
===================================================================
--- branches/RC/core/units/user_groups/user_groups_eh.php (revision 10004)
+++ branches/RC/core/units/user_groups/user_groups_eh.php (revision 10005)
@@ -1,91 +1,132 @@
<?php
class UserGroupsEventHandler extends kDBEventHandler {
/**
* Adds user as member for selected groups
*
* @param kEvent $event
*/
function OnProcessSelected(&$event)
{
+ if ($event->Prefix == 'u-ug') {
$new_groups = $this->Application->GetVar('g');
if (!$new_groups) {
return ;
}
$new_groups = array_keys($new_groups);
// don't insert duplicate group membership record
$user_id = $this->Application->GetVar('u_id');
$table_name = $this->Application->GetTempName(TABLE_PREFIX.'UserGroup', 'prefix:u');
$sql = 'SELECT GroupId
FROM '.$table_name.'
WHERE PortalUserId = '.$user_id;
$old_groups = $this->Conn->GetCol($sql);
$new_groups = array_diff($new_groups, $old_groups);
if ($new_groups) {
foreach ($new_groups as $new_group) {
$fields_hash = Array (
'GroupId' => $new_group,
'PortalUserId' => $user_id,
'PrimaryGroup' => 0,
);
$this->Conn->doInsert($fields_hash, $table_name);
}
}
+ }
+ if ($event->Prefix == 'g-ug') {
+ $new_users = $this->Application->GetVar('u');
+ if (!$new_users) {
+ return ;
+ }
+
+ $new_users = array_keys($new_users);
+
+ // don't insert duplicate group membership record
+ $group_id = $this->Application->GetVar('g_id');
+ $table_name = $this->Application->GetTempName(TABLE_PREFIX.'UserGroup', 'prefix:g');
+ $sql = 'SELECT PortalUserId
+ FROM '.$table_name.'
+ WHERE GroupId = '.$group_id;
+ $old_users = $this->Conn->GetCol($sql);
+
+ $new_users = array_diff($new_users, $old_users);
+ if ($new_users) {
+ foreach ($new_users as $new_user) {
+ $fields_hash = Array (
+ 'GroupId' => $group_id,
+ 'PortalUserId' => $new_user,
+ 'PrimaryGroup' => 0,
+ );
+ $this->Conn->doInsert($fields_hash, $table_name);
+ }
+ }
+ }
+ $this->Application->StoreVar($this->Application->GetTopmostPrefix($event->Prefix).'_modified', '1');
$event->SetRedirectParam('opener', 'u');
}
/**
* Sets primary group for user (in editing only)
*
* @param kEvent $event
*/
function OnSetPrimary(&$event)
{
$ids = $this->StoreSelectedIDs($event);
if ($ids) {
$id = array_shift($ids);
$object =& $event->getObject( Array('skip_autoload' => true) );
$user_id = $this->Application->GetVar('u_id');
$sql = 'UPDATE '.$object->TableName.'
SET PrimaryGroup = 0
WHERE PortalUserId = '.$user_id;
$this->Conn->Query($sql);
$sql = 'UPDATE '.$object->TableName.'
SET PrimaryGroup = 1
WHERE '.$object->IDField.' = '.$id.' AND PortalUserId = '.$user_id;
$this->Conn->Query($sql);
}
$this->clearSelectedIDs($event);
}
/**
* Don't allow primary group record deleting
*
* @param kEvent $event
*/
function customProcessing(&$event, $type)
{
if ($event->Name == 'OnMassDelete' && $type == 'before') {
$ids = $event->getEventParam('ids');
if ($ids) {
$object =& $event->getObject( Array('skip_autoload' => true) );
+
+ if ($event->Prefix == 'u-ug') {
$user_id = $this->Application->GetVar('u_id');
$sql = 'SELECT '.$object->IDField.'
FROM '.$object->TableName.'
WHERE '.$object->IDField.' IN ('.implode(',', $ids).') AND PortalUserId = '.$user_id.' AND PrimaryGroup = 0';
$ids = $this->Conn->GetCol($sql);
+ }
+ elseif ($event->Prefix == 'g-ug') {
+ $group_id = $this->Application->GetVar('g_id');
+ $sql = 'SELECT '.$object->IDField.'
+ FROM '.$object->TableName.'
+ WHERE '.$object->IDField.' IN ('.implode(',', $ids).') AND GroupId = '.$group_id.' AND PrimaryGroup = 0';
+ $ids = $this->Conn->GetCol($sql);
+ }
$event->setEventParam('ids', $ids);
}
}
}
}
?>
\ No newline at end of file
Property changes on: branches/RC/core/units/user_groups/user_groups_eh.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.2
\ No newline at end of property
+1.2.2.1
\ No newline at end of property
Index: branches/RC/core/units/user_groups/user_groups_config.php
===================================================================
--- branches/RC/core/units/user_groups/user_groups_config.php (revision 10004)
+++ branches/RC/core/units/user_groups/user_groups_config.php (revision 10005)
@@ -1,77 +1,115 @@
<?php
$config = Array(
'Prefix' => 'ug',
'Clones' => Array(
'g-ug' => Array(
'ParentPrefix' => 'g',
'ForeignKey' => 'GroupId',
'ParentTableKey' => 'GroupId',
+
+ 'IDField' => 'PortalUserId',
+
+ 'ListSQLs' => Array(
+ '' => ' SELECT %1$s.* %2$s FROM %1$s
+ LEFT JOIN '.TABLE_PREFIX.'PortalGroup g ON %1$s.GroupId = g.GroupId
+ LEFT JOIN '.TABLE_PREFIX.'PortalUser u ON %1$s.PortalUserId = u.PortalUserId'
+ ),
+ 'ItemSQLs' => Array(
+ '' => ' SELECT %1$s.* %2$s FROM %1$s
+ LEFT JOIN '.TABLE_PREFIX.'PortalGroup g ON %1$s.GroupId = g.GroupId
+ LEFT JOIN '.TABLE_PREFIX.'PortalUser u ON %1$s.PortalUserId = u.PortalUserId'
+ ),
+ 'CalculatedFields' => Array (
+ '' => Array(
+ 'UserName' => 'CONCAT(u.LastName, \' \', u.FirstName)',
+ 'UserLogin' => 'u.Login',
+ ),
+ ),
+ 'VirtualFields' => Array (
+ 'UserName' => Array('type' => 'string'),
+ 'UserLogin' => Array('type' => 'string'),
+ ),
+ 'Grids' => Array(
+ 'GroupUsers' => Array(
+ 'Icons' => Array ('default' => 'icon16_group.gif'),
+ 'Fields' => Array(
+ 'PortalUserId' => Array ('title' => 'la_col_Id', 'data_block' => 'grid_checkbox_td', 'filter_block' => 'grid_range_filter'),
+ 'UserName' => Array ('title'=>'la_col_UserFirstLastName'),
+ 'UserLogin' => Array ('title'=>'la_col_Login'),
+ 'PrimaryGroup' => Array( 'title'=>'la_col_PrimaryGroup', 'filter_block' => 'grid_options_filter'),
+ 'MembershipExpires' => Array ('title' => 'la_col_MembershipExpires', 'data_block' => 'grid_membership_td', 'filter_block' => 'grid_date_range_filter'),
+ ),
+ ),
+ ),
),
'u-ug' => Array(
'ParentPrefix' => 'u',
'ForeignKey' => 'PortalUserId',
'ParentTableKey' => 'PortalUserId',
),
),
'ItemClass' => Array('class'=>'UserGroups_DBItem','file'=>'user_groups_dbitem.php','build_event'=>'OnItemBuild'),
'ListClass' => Array('class'=>'kDBList','file'=>'','build_event'=>'OnListBuild'),
'EventHandlerClass' => Array('class'=>'UserGroupsEventHandler','file'=>'user_groups_eh.php','build_event'=>'OnBuild'),
'TagProcessorClass' => Array('class'=>'kDBTagProcessor','file'=>'','build_event'=>'OnBuild'),
'AutoLoad' => true,
'QueryString' => Array (
1 => 'id',
2 => 'page',
3 => 'event',
),
'IDField' => 'GroupId',
'TableName' => TABLE_PREFIX.'UserGroup',
'ListSQLs' => Array( ''=>' SELECT %1$s.* %2$s FROM %1$s
LEFT JOIN '.TABLE_PREFIX.'PortalGroup g ON %1$s.GroupId = g.GroupId'),
'ItemSQLs' => Array( ''=>' SELECT %1$s.* %2$s FROM %1$s
LEFT JOIN '.TABLE_PREFIX.'PortalGroup g ON %1$s.GroupId = g.GroupId'),
'AutoDelete' => true,
- 'AutoClone' => true,
+ 'AutoClone' => false,
'CalculatedFields' => Array (
'' => Array(
'GroupName' => 'g.Name',
+ 'GroupDescription' => 'g.Description',
),
),
'Fields' => Array(
'PortalUserId' => Array('type' => 'int', 'not_null' => 1, 'default' => 0),
'GroupId' => Array('type' => 'int', 'not_null' => 1, 'default' => 0),
'MembershipExpires' => Array('type' => 'int', 'formatter' => 'kDateFormatter', 'default' => null),
'PrimaryGroup' => Array('type' => 'int', 'formatter' => 'kOptionsFormatter', 'options' => Array (1 => 'la_Yes', 0 => 'la_No'), 'use_phrases' => 1, 'not_null' => 1, 'default' => 1),
'ExpirationReminderSent' => Array('type' => 'int', 'not_null' => 1, 'default' => 0),
),
'VirtualFields' => Array (
'GroupName' => Array('type' => 'string'),
+ 'GroupDescription' => Array('type' => 'string'),
),
'Grids' => Array(
'Default' => Array(
'Icons' => Array ('default' => 'icon16_group.gif'),
'Fields' => Array(
'GroupId' => Array ('title' => 'la_col_Id', 'data_block' => 'grid_checkbox_td', 'filter_block' => 'grid_range_filter'),
'GroupName' => Array ('title'=>'la_col_GroupName'),
+ 'GroupDescription' => Array ('title'=>'la_col_Description'),
'PrimaryGroup' => Array( 'title'=>'la_col_PrimaryGroup', 'filter_block' => 'grid_options_filter'),
'MembershipExpires' => Array ('title' => 'la_col_MembershipExpires', 'data_block' => 'grid_membership_td', 'filter_block' => 'grid_date_range_filter'),
),
),
),
);
?>
\ No newline at end of file
Property changes on: branches/RC/core/units/user_groups/user_groups_config.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.6.2.1
\ No newline at end of property
+1.6.2.2
\ No newline at end of property
Index: branches/RC/core/units/groups/groups_config.php
===================================================================
--- branches/RC/core/units/groups/groups_config.php (revision 10004)
+++ branches/RC/core/units/groups/groups_config.php (revision 10005)
@@ -1,128 +1,128 @@
<?php
$config = Array(
'Prefix' => 'g',
'ItemClass' => Array('class' => 'GroupsItem', 'file' => 'groups_item.php', 'build_event' => 'OnItemBuild'),
'ListClass' => Array('class' => 'kDBList', 'file' => '', 'build_event' => 'OnListBuild'),
'EventHandlerClass' => Array('class' => 'GroupsEventHandler', 'file' => 'groups_event_handler.php','build_event'=>'OnBuild'),
'TagProcessorClass' => Array('class' => 'kDBTagProcessor', 'file' => '','build_event'=>'OnBuild'),
'AutoLoad' => true,
'QueryString' => Array(
1 => 'id',
2 => 'page',
3 => 'event',
4 => 'mode',
),
'IDField' => 'GroupId',
'StatusField' => Array('Enabled'),
'TitleField' => 'Name',
'TitlePresets' => Array(
'default' => Array( 'new_status_labels' => Array('g' => '!la_title_Adding_Group!'),
'edit_status_labels' => Array('g' => '!la_title_Editing_Group!'),
'new_titlefield' => Array('g' => ''),
),
'groups_list' => Array('prefixes' => Array('g.total_List'), 'format' => "!la_title_Groups! (#g.total_recordcount#)"),
'groups_edit' => Array('prefixes' => Array('g'), 'format' => "#g_status# '#g_titlefield#' - !la_title_General!"),
'groups_edit_users' => Array('prefixes' => Array('g', 'g-ug_List'), 'format' => "#g_status# '#g_titlefield#' - !la_title_Users! (#g-ug_recordcount#)" ),
'groups_edit_permissions' => Array('prefixes' => Array('g'), 'format' => "#g_status# '#g_titlefield#' - !la_title_Permissions!" ),
'groups_edit_additional_permissions' => Array('prefixes' => Array('g'), 'format' => "#g_status# '#g_titlefield#' - !la_title_AdditionalPermissions!" ),
'select_group' => Array('prefixes' => Array('g.user_List'), 'format' => "!la_title_Groups! (#g.user_recordcount#) - !la_title_SelectGroup!"),
),
'PermSection' => Array('main' => 'in-portal:user_groups'),
'TableName' => TABLE_PREFIX.'PortalGroup',
'ListSQLs' => Array(
'' => 'SELECT %1$s.* %2$s FROM %1$s',
'total' => 'SELECT %1$s.* %2$s
FROM %1$s
LEFT JOIN '.TABLE_PREFIX.'UserGroup ug ON ug.GroupId = %1$s.GroupId',
),
'ItemSQLs' => Array('' => ' SELECT %1$s.* %2$s
FROM %1$s
LEFT JOIN '.TABLE_PREFIX.'UserGroup ug ON ug.GroupId = %1$s.GroupId'),
'ListSortings' => Array(
'' => Array(
'Sorting' => Array('Name' => 'asc'),
)
),
- 'SubItems' => Array('g-perm', /*'g-ug'*/),
+ 'SubItems' => Array('g-perm', 'g-ug'),
'CalculatedFields' => Array(
'total' => Array(
'UserCount' => 'COUNT(ug.PortalUserId)',
),
),
'Fields' => Array (
'GroupId' => Array('type' => 'int', 'not_null' => 1, 'default' => 0),
'Name' => Array('type' => 'string', 'not_null' => 1, 'required' => 1, 'default' => ''),
'Description' => Array('type' => 'string', 'default' => null),
'CreatedOn' => Array('type' => 'int', 'formatter' => 'kDateFormatter', 'default' => '#NOW#'),
'System' => Array('type' => 'int', 'not_null' => 1, 'default' => 0),
'Personal' => Array('type' => 'int','not_null' => 1, 'default' => 0),
'Enabled' => Array('type' => 'int', 'formatter' => 'kOptionsFormatter', 'options' => Array(1 => 'la_Enabled', 0 => 'la_Disabled'), 'use_phrases' => 1, 'not_null' => 1, 'default' => 1),
'ResourceId' => Array('type' => 'int','not_null' => 1, 'default' => 0),
),
'VirtualFields' => Array(
'UserCount' => Array('type' => 'int', 'default' => 0),
),
'Grids' => Array(
'Default' => Array(
'Icons' => Array(1 => 'icon16_group.gif', 0 => 'icon16_group_disabled.gif'),
'Fields' => Array(
'GroupId' => Array('title' => 'la_col_Id', 'data_block' => 'grid_checkbox_td', 'filter_block' => 'grid_range_filter'),
'Name' => Array('title' => 'la_col_GroupName'),
'UserCount' => Array('title' => 'la_col_UserCount', 'filter_block' => 'grid_range_filter'),
),
),
'UserGroups' => Array (
'Icons' => Array (1 => 'icon16_group.gif', 0 => 'icon16_group_disabled.gif'),
'Fields' => Array (
'GroupId' => Array('title' => 'la_col_Id', 'data_block' => 'grid_checkbox_td', 'filter_block' => 'grid_range_filter'),
'Name' => Array('title' => 'la_col_GroupName'),
),
),
'Radio' => Array (
'Icons' => Array(1 => 'icon16_group.gif', 0 => 'icon16_group_disabled.gif'),
'Fields' => Array(
'GroupId' => Array('title' => 'la_col_Id', 'data_block' => 'grid_radio_td', 'filter_block' => 'grid_range_filter'),
'Name' => Array('title' => 'la_col_GroupName'),
'Description' => Array('title' => 'la_col_Description'),
),
),
'GroupSelector' => Array (
'Icons' => Array(1 => 'icon16_group.gif', 0 => 'icon16_group_disabled.gif'),
'Fields' => Array(
'GroupId' => Array('title' => 'la_col_Id', 'data_block' => 'grid_checkbox_td', 'filter_block' => 'grid_range_filter'),
'Name' => Array('title' => 'la_col_GroupName'),
'Description' => Array('title' => 'la_col_Description'),
),
),
),
);
?>
\ No newline at end of file
Property changes on: branches/RC/core/units/groups/groups_config.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.21.2.1
\ No newline at end of property
+1.21.2.2
\ No newline at end of property
Index: branches/RC/core/units/general/helpers/search_helper.php
===================================================================
--- branches/RC/core/units/general/helpers/search_helper.php (revision 10004)
+++ branches/RC/core/units/general/helpers/search_helper.php (revision 10005)
@@ -1,568 +1,575 @@
<?php
class kSearchHelper extends kHelper {
/**
* Splits search phrase into keyword using quotes,plus and minus sings and spaces as split criteria
*
* @param string $keyword
* @return string
*/
function splitKeyword($keyword)
{
$quotes_re = '/([+\-]?)"(.*?)"/';
$no_quotes_re = '/([+\-]?)([^ ]+)/';
$quoted_kw = preg_match_all($quotes_re, $keyword, $res);
foreach ($res[2] as $index => $kw) $final[$kw] = $res[1][$index];
$keyword = preg_replace($quotes_re, '', $keyword);
$not_quoted_kw = preg_match_all($no_quotes_re, $keyword, $res);
foreach ($res[2] as $index => $kw) $final[$kw] = $res[1][$index];
return $final;
}
function getPositiveKeywords($keyword)
{
$keywords = $this->splitKeyword($keyword);
$ret = Array();
foreach ($keywords as $keyword => $sign) {
if ($sign == '+' || $sign == '') {
$ret[] = $keyword;
}
}
return $ret;
}
function buildWhereClause($keyword, $fields)
{
$keywords = $this->splitKeyword($keyword);
$normal_conditions = Array();
$plus_conditions = Array();
$minus_conditions = Array();
foreach ($keywords as $keyword => $sign) {
switch ($sign) {
case '+':
$plus_conditions[] = implode(' LIKE "%'.$keyword.'%" OR ', $fields).' LIKE "%'.$keyword.'%"';
break;
case '-':
foreach ($fields as $field) {
$condition[] = $field.' NOT LIKE "%'.$keyword.'%" OR '.$field.' IS NULL';
}
$minus_conditions[] = '('.implode(') AND (', $condition).')';
break;
case '':
$keyword = str_replace('"', '\"', $keyword);
$normal_conditions[] = implode(' LIKE "%'.$keyword.'%" OR ', $fields).' LIKE "%'.$keyword.'%"';
break;
}
}
// building where clause
if ($normal_conditions) {
$where_clause = '('.implode(') OR (', $normal_conditions).')';
}
else {
$where_clause = '1';
}
if ($plus_conditions) {
$where_clause = '('.$where_clause.') AND ('.implode(') AND (', $plus_conditions).')';
}
if ($minus_conditions) {
$where_clause = '('.$where_clause.') AND ('.implode(') AND (', $minus_conditions).')';
}
return $where_clause;
}
/**
* Returns additional information about search field
*
* @param kDBList $object
* @param string $field_name
* @return Array
*/
function getFieldInformation(&$object, $field_name)
{
$sql_filter_type = isset($object->VirtualFields[$field_name]) ? 'having' : 'where';
$field_type = isset($object->Fields[$field_name]['type']) ? $object->Fields[$field_name]['type'] : 'string';
if (preg_match('/(.*)\.(.*)/', $field_name, $regs)) {
$table_name = '`'.$regs[1].'`.'; // field from external table
$field_name = $regs[2];
}
elseif ($sql_filter_type == 'where') {
$table_name = '`'.$object->TableName.'`.'; // field from local table
}
$table_name = ($sql_filter_type == 'where') ? $table_name : '';
// replace wid inside table name to WID_MARK constant value
$is_temp_table = preg_match('/(.*)'.TABLE_PREFIX.'ses_'.$this->Application->GetSID().'(_[\d]+){0,1}_edit_(.*)/', $table_name, $regs);
if ($is_temp_table) {
$table_name = $regs[1].TABLE_PREFIX.'ses_'.EDIT_MARK.'_edit_'.$regs[3]; // edit_mark will be replaced with sid[_main_wid] in AddFilters
}
return Array ('field_name' => $field_name, 'field_type' => $field_type, 'table_name' => $table_name, 'sql_filter_type' => $sql_filter_type);
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function performSearch(&$event)
{
$object =& $event->getObject();
// process search keyword
$search_keyword = $this->Application->GetVar( $event->getPrefixSpecial(true).'_search_keyword');
$this->Application->StoreVar( $event->getPrefixSpecial().'_search_keyword', $search_keyword);
$search_keyword = str_replace('*', '%', $search_keyword);
$custom_filter = $this->processCustomFilters($event);
if(!$search_keyword && $custom_filter === false) {
$this->resetSearch($event);
return true;
}
if ($search_keyword) {
$this->processAutomaticFilters($event, $search_keyword, $custom_filter);
}
}
function processAutomaticFilters(&$event, $search_keyword, $custom_filter)
{
$grid_name = $this->Application->GetVar('grid_name');
$grids = $this->Application->getUnitOption($event->Prefix, 'Grids');
$search_fields = array_keys($grids[$grid_name]['Fields']);
$search_filter = Array();
$object =& $event->getObject();
foreach ($search_fields as $search_field) {
$custom_search = isset($custom_filter[$search_field]);
$filter_data = $this->getSearchClause($object, $search_field, $search_keyword, $custom_search);
if ($filter_data) {
$search_filter[$search_field] = $filter_data;
}
else {
unset($search_filter[$search_field]);
}
}
$this->Application->StoreVar($event->getPrefixSpecial().'_search_filter', serialize($search_filter) );
}
/**
* Returns search clause for any particular field
*
* @param kDBList $object
* @param string $search_field
* @param string $search_keyword what we are searching (false, when building custom filter clause)
* @param string $custom_search already found using custom filter
* @return Array
*/
function getSearchClause(&$object, $field_name, $search_keyword, $custom_search)
{
$search_keywords = $this->splitKeyword($search_keyword);
extract( $this->getFieldInformation($object, $field_name) ); // see getFieldInformation for more details
$filter_value = '';
// get field clause by formatter name and/or parameters
$formatter = getArrayValue($object->Fields[$field_name], 'formatter');
switch ($formatter) {
case 'kOptionsFormatter':
$search_keys = Array();
if ($custom_search === false) {
// if keywords passed through simple search filter (on each grid)
$use_phrases = getArrayValue($object->Fields[$field_name], 'use_phrases');
$field_options = $object->GetFieldOptions($field_name);
foreach ($field_options['options'] as $key => $val) {
foreach ($search_keywords as $keyword => $sign) {
$pattern = '#'.$keyword.'#i';
if (!preg_match($pattern, $use_phrases ? $this->Application->Phrase($val) : $val)) {
if ($sign == '+') {
$filter_value = $table_name.'`'.$field_name.'` = NULL';
break;
}
else {
continue;
}
}
if ($sign == '+' || $sign == '') {
$search_keys[$key] = $this->Conn->qstr($key);
}
elseif($sign == '-') {
// if same value if found as exclusive too, then remove from search result
unset($search_keys[$key]);
}
}
}
}
if ($search_keys) {
$filter_value = $table_name.'`'.$field_name.'` IN ('.implode(',', $search_keys).')';
}
$field_processed = true;
break;
case 'kDateFormatter':
// if date is searched using direct filter, then do nothing here, otherwise search using LIKE clause
$field_processed = ($custom_search !== false) ? true : false;
break;
default:
$field_processed = false;
break;
}
// if not already processed by formatter, then get clause by field type
if (!$field_processed && $search_keywords) {
switch($field_type)
{
case 'int':
case 'integer':
case 'numeric':
$search_keys = Array();
foreach ($search_keywords as $keyword => $sign) {
if (!is_numeric($keyword) || ($sign == '-')) continue;
$search_keys[] = $this->Conn->qstr($keyword);
}
if ($search_keys) {
$filter_value = $table_name.'`'.$field_name.'` IN ('.implode(',', $search_keys).')';
}
break;
case 'double':
case 'float':
case 'real':
$search_keys = Array();
foreach ($search_keywords as $keyword => $sign) {
$keyword = str_replace(',', '.', $keyword);
if (!is_numeric($keyword) || ($sign == '-')) continue;
$search_keys[] = 'ABS('.$table_name.'`'.$field_name.'` - '.$this->Conn->qstr($keyword).') <= 0.0001';
}
if ($search_keys) {
$filter_value = '('.implode(') OR (', $search_keys).')';
}
break;
case 'string':
$filter_value = $this->buildWhereClause($search_keyword, Array($table_name.'`'.$field_name.'`'));
break;
}
}
if ($filter_value) {
return Array('type' => $sql_filter_type, 'value' => $filter_value);
}
return false;
}
/**
* Processes custom filters from submit
*
* @param KEvent $event
* @return bool
*/
function processCustomFilters(&$event)
{
$grid_name = $this->Application->GetVar('grid_name');
// update "custom filter" with values from submit: begin
$view_name = $this->Application->RecallVar($event->getPrefixSpecial().'_current_view');
$custom_filters = $this->Application->RecallPersistentVar($event->getPrefixSpecial().'_custom_filter.'.$view_name, ALLOW_DEFAULT_SETTINGS);
if ($custom_filters) {
$custom_filters = unserialize($custom_filters);
$custom_filter = isset($custom_filters[$grid_name]) ? $custom_filters[$grid_name] : Array ();
}
else {
$custom_filter = Array ();
}
// submit format custom_filters[prefix_special][field]
$submit_filters = $this->Application->GetVar('custom_filters');
if ($submit_filters) {
$submit_filters = getArrayValue($submit_filters, $event->getPrefixSpecial(), $grid_name);
if ($submit_filters) {
foreach ($submit_filters as $field_name => $field_options) {
list ($filter_type, $field_value) = each($field_options);
$is_empty = strlen(is_array($field_value) ? implode('', $field_value) : $field_value) == 0;
if ($is_empty) {
if (isset($custom_filter[$field_name])) {
// use isset, because non-existing key will cause "php notice"!
unset($custom_filter[$field_name][$filter_type]); // remove filter
if (!$custom_filter[$field_name]) {
// if no filters left for field, then delete record at all
unset($custom_filter[$field_name]);
}
}
}
else {
$custom_filter[$field_name][$filter_type]['submit_value'] = $field_value;
}
}
}
}
if ($custom_filter) {
$custom_filters[$grid_name] = $custom_filter;
}
else {
unset($custom_filters[$grid_name]);
}
// update "custom filter" with values from submit: end
if (!$custom_filter) {
// in case when no filters specified, there are nothing to process
$this->Application->StorePersistentVar($event->getPrefixSpecial().'_custom_filter.'.$view_name, serialize($custom_filters) );
return false;
}
$object =& $event->getObject(); // don't recall it each time in getCustomFilterSearchClause
$grid_info = $this->Application->getUnitOption($event->Prefix.'.'.$grid_name, 'Grids');
foreach ($custom_filter as $field_name => $field_options) {
list ($filter_type, $field_options) = each($field_options);
$field_options['grid_options'] = $grid_info['Fields'][$field_name];
$field_options = $this->getCustomFilterSearchClause($object, $field_name, $filter_type, $field_options);
if ($field_options['value']) {
unset($field_options['grid_options']);
$custom_filter[$field_name][$filter_type] = $field_options;
}
}
$custom_filters[$grid_name] = $custom_filter;
$this->Application->StorePersistentVar($event->getPrefixSpecial().'_custom_filter.'.$view_name, serialize($custom_filters) );
return $custom_filter;
}
/**
* Return numeric range filter value + checking that it's number
*
* @param Array $value array containing range filter value
* @return unknown
*/
function getRangeValue($value)
{
return strlen($value) && is_numeric($value) ? $this->Conn->qstr($value) : false;
}
function getCustomFilterSearchClause(&$object, $field_name, $filter_type, $field_options)
{
// this is usually used for mutlilingual fields and date fields
if (isset($field_options['grid_options']['sort_field'])) {
$field_name = $field_options['grid_options']['sort_field'];
}
extract( $this->getFieldInformation($object, $field_name) ); // see getFieldInformation for more details
$filter_value = '';
switch ($filter_type) {
case 'range':
$from = $this->getRangeValue($field_options['submit_value']['from']);
$to = $this->getRangeValue($field_options['submit_value']['to']);
if ($from !== false && $to !== false) {
// add range filter
$filter_value = $table_name.'`'.$field_name.'` >= '.$from.' AND '.$table_name.'`'.$field_name.'` <= '.$to;
}
elseif ($from !== false) {
// add equals filter on $from
$filter_value = $table_name.'`'.$field_name.'` = '.$from;
}
elseif ($to !== false) {
// add equals filter on $to
$filter_value = $table_name.'`'.$field_name.'` = '.$to;
}
break;
case 'float_range':
// MySQL can't compare values in "float" type columns using "=" operator
$from = $this->getRangeValue($field_options['submit_value']['from']);
$to = $this->getRangeValue($field_options['submit_value']['to']);
if ($from !== false && $to !== false) {
// add range filter
$filter_value = $table_name.'`'.$field_name.'` >= '.$from.' AND '.$table_name.'`'.$field_name.'` <= '.$to;
}
elseif ($from !== false) {
// add equals filter on $from
$filter_value = 'ABS('.$table_name.'`'.$field_name.'` - '.$from.') <= 0.0001';
}
elseif ($to !== false) {
// add equals filter on $to
$filter_value = 'ABS('.$table_name.'`'.$field_name.'` - '.$to.') <= 0.0001';
}
break;
case 'date_range':
$from = $this->processRangeField($object, $field_name, $field_options['submit_value'], 'from');
$to = $this->processRangeField($object, $field_name, $field_options['submit_value'], 'to');
$day_seconds = 23 * 60 * 60 + 59 * 60 + 59;
if ($from !== false && $to === false) {
$from = strtotime(date('Y-m-d', $from).' 00:00:00', $from); // reset to morning
$to = $from + $day_seconds;
}
elseif ($from === false && $to !== false) {
$to = strtotime(date('Y-m-d', $to).' 23:59:59', $to); // reset to evening
$from = $to - $day_seconds;
}
if ($from !== false && $to !== false) {
$filter_value = $table_name.'`'.$field_name.'` >= '.$from.' AND '.$table_name.'`'.$field_name.'` <= '.$to;
}
break;
case 'equals':
case 'options':
$field_value = strlen($field_options['submit_value']) ? $this->Conn->qstr($field_options['submit_value']) : false;
if ($field_value) {
$filter_value = $table_name.'`'.$field_name.'` = '.$field_value;
}
break;
+ case 'picker':
+ $field_value = strlen($field_options['submit_value']) ? $field_options['submit_value'] : false;
+ if ($field_value) {
+ $filter_value = $table_name.'`'.$field_name.'` LIKE "%|'.$field_value.'|%"';
+ }
+ break;
+
case 'like':
$filter_value = $this->buildWhereClause($field_options['submit_value'], Array($table_name.'`'.$field_name.'`'));
break;
default:
break;
}
$field_options['sql_filter_type'] = $sql_filter_type;
$field_options['value'] = $filter_value;
return $field_options;
}
/**
* Enter description here...
*
* @param kdbItem $object
* @param string $search_field
* @param string $value
* @param string $type
*/
function processRangeField(&$object, $search_field, $value, $type)
{
if (!strlen($value[$type])) {
return false;
}
$lang_current =& $this->Application->recallObject('lang.current');
$options = $object->GetFieldOptions($search_field);
$dt_separator = isset($options['date_time_separator']) ? $options['date_time_separator'] : ' ';
$tmp_value = explode($dt_separator, $value[$type], 2);
if (count($tmp_value) == 1) {
// time is missing, then guess it and add to date
$time = ($type == 'from') ? adodb_mktime(0, 0, 0) : adodb_mktime(23, 59, 59);
$time = adodb_date($lang_current->GetDBField('InputTimeFormat'), $time);
$value[$type] .= $dt_separator.$time;
}
$formatter =& $this->Application->recallObject($object->Fields[$search_field]['formatter']);
$value_ts = $formatter->Parse($value[$type], $search_field, $object);
$pseudo = getArrayValue($object->FieldErrors, $search_field, 'pseudo');
if ($pseudo) {
unset($object->FieldErrors[$search_field]); // remove error!
// invalid format -> ignore this date in search
return false;
}
return $value_ts;
}
/**
* Resets current search
*
* @param kEvent $event
*/
function resetSearch(&$event)
{
$this->Application->RemoveVar($event->getPrefixSpecial().'_search_filter');
$this->Application->RemoveVar($event->getPrefixSpecial().'_search_keyword');
$view_name = $this->Application->RecallVar($event->getPrefixSpecial().'_current_view');
$this->Application->RemovePersistentVar($event->getPrefixSpecial().'_custom_filter.'.$view_name);
}
/**
* Creates filters based on "types" & "except" parameters from PrintList
*
* @param kEvent $event
* @param Array $type_clauses
* @param string $types
* @param string $except_types
*/
function SetComplexFilter(&$event, &$type_clauses, $types, $except_types)
{
$includes_or_filter =& $this->Application->makeClass('kMultipleFilter', FLT_TYPE_OR);
$excepts_and_filter =& $this->Application->makeClass('kMultipleFilter', FLT_TYPE_AND);
$includes_or_filter_h =& $this->Application->makeClass('kMultipleFilter', FLT_TYPE_OR);
$excepts_and_filter_h =& $this->Application->makeClass('kMultipleFilter', FLT_TYPE_AND);
if ($types) {
$types = explode(',', $types);
foreach ($types as $type) {
$type = trim($type);
if (isset($type_clauses[$type])) {
if ($type_clauses[$type]['having_filter']) {
$includes_or_filter_h->addFilter('filter_'.$type, $type_clauses[$type]['include']);
} else {
$includes_or_filter->addFilter('filter_'.$type, $type_clauses[$type]['include']);
}
}
}
}
if ($except_types) {
$except_types = explode(',', $except_types);
foreach ($except_types as $type) {
$type = trim($type);
if (isset($type_clauses[$type])) {
if ($type_clauses[$type]['having_filter']) {
$excepts_and_filter_h->addFilter('filter_'.$type, $type_clauses[$type]['except']);
} else {
$excepts_and_filter->addFilter('filter_'.$type, $type_clauses[$type]['except']);
}
}
}
}
$object =& $event->getObject();
$object->addFilter('includes_filter', $includes_or_filter);
$object->addFilter('excepts_filter', $excepts_and_filter);
$object->addFilter('includes_filter_h', $includes_or_filter_h, HAVING_FILTER);
$object->addFilter('excepts_filter_h', $excepts_and_filter_h, HAVING_FILTER);
}
}
?>
\ No newline at end of file
Property changes on: branches/RC/core/units/general/helpers/search_helper.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.10.2.2
\ No newline at end of property
+1.10.2.3
\ No newline at end of property
Index: branches/RC/core/admin_templates/users/user_edit_password.tpl
===================================================================
--- branches/RC/core/admin_templates/users/user_edit_password.tpl (revision 10004)
+++ branches/RC/core/admin_templates/users/user_edit_password.tpl (revision 10005)
@@ -1,39 +1,40 @@
<inp2:adm_SetPopupSize width="564" height="377"/>
<inp2:m_include t="incs/header"/>
<inp2:m_RenderElement name="combined_header" section="proj-base:users" pagination="0" prefix="u" title_preset="admins_edit"/>
<!-- ToolBar --->
<table class="toolbar" height="30" cellspacing="0" cellpadding="0" width="100%" border="0">
<tbody>
<tr>
<td>
<script type="text/javascript">
a_toolbar = new ToolBar();
a_toolbar.AddButton( new ToolBarButton('select', '<inp2:m_phrase label="la_ToolTip_Save" escape="1"/>', function() {
- submit_event('u','<inp2:u_SaveEvent/>');
+ submit_event('u','OnUpdatePassword');
}
) );
a_toolbar.AddButton( new ToolBarButton('cancel', '<inp2:m_phrase label="la_ToolTip_Cancel" escape="1"/>', function() {
cancel_edit('u','OnCancelEdit','<inp2:u_SaveEvent/>','<inp2:m_Phrase label="la_FormCancelConfirmation" escape="1"/>');
}
) );
a_toolbar.Render();
</script>
</td>
</tr>
</tbody>
</table>
<inp2:u_SaveWarning name="grid_save_warning"/>
+<inp2:u_ErrorWarning name="form_error_warning"/>
<table width="100%" border="0" cellspacing="0" cellpadding="4" class="table-collapsed">
<inp2:m_RenderElement name="inp_id_label" prefix="u" field="PortalUserId" title="!la_fld_Id!"/>
<inp2:m_RenderElement name="inp_label" prefix="u" field="Login" title="la_fld_Username"/>
<inp2:m_RenderElement name="inp_edit_password" prefix="u" field="Password" title="la_fld_Password"/>
<inp2:m_RenderElement name="inp_edit_password" prefix="u" field="VerifyPassword" title="la_fld_VerifyPassword"/>
<inp2:m_RenderElement name="inp_label" prefix="u" field="FirstName" title="la_fld_FirstName"/>
<inp2:m_RenderElement name="inp_label" prefix="u" field="LastName" title="la_fld_LastName"/>
<inp2:m_RenderElement name="inp_label" prefix="u" field="Email" title="la_fld_Email"/>
</table>
<inp2:m_include t="incs/footer"/>
Property changes on: branches/RC/core/admin_templates/users/user_edit_password.tpl
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.5
\ No newline at end of property
+1.5.2.1
\ No newline at end of property
Index: branches/RC/core/admin_templates/users/admins_list.tpl
===================================================================
--- branches/RC/core/admin_templates/users/admins_list.tpl (revision 10004)
+++ branches/RC/core/admin_templates/users/admins_list.tpl (revision 10005)
@@ -1,59 +1,68 @@
<inp2:m_include t="incs/header"/>
<inp2:m_RenderElement name="combined_header" section="proj-base:admins" pagination="1" prefix="u.admins" title_preset="" grid="Admins" />
<!-- ToolBar --->
<table class="toolbar" height="30" cellspacing="0" cellpadding="0" width="100%" border="0">
<tbody>
<tr>
<td>
<script type="text/javascript">
//do not rename - this function is used in default grid for double click!
function edit()
{
set_hidden_field('remove_specials[u.admins]', 1);
std_edit_item('u.admins', 'proj-base/users/admins_edit');
}
var a_toolbar = new ToolBar();
a_toolbar.AddButton( new ToolBarButton('proj-base:new_user', '<inp2:m_phrase label="la_ToolTip_Add" escape="1"/>',
function() {
set_hidden_field('remove_specials[u.admins]', 1);
std_precreate_item('u.admins', 'proj-base/users/admins_edit')
} ) );
a_toolbar.AddButton( new ToolBarButton('edit', '<inp2:m_phrase label="la_ToolTip_Edit" escape="1"/>::<inp2:m_phrase label="la_ShortToolTip_Edit" escape="1"/>', edit) );
a_toolbar.AddButton( new ToolBarButton('delete', '<inp2:m_phrase label="la_ToolTip_Delete" escape="1"/>',
function() {
set_hidden_field('remove_specials[u.admins]', 1);
std_delete_items('u.admins')
} ) );
a_toolbar.AddButton( new ToolBarSeparator('sep1') );
+ a_toolbar.AddButton( new ToolBarButton('clone', '<inp2:m_phrase label="la_ToolTip_CloneUser" escape="1"/>::<inp2:m_phrase label="la_ShortToolTip_CloneUser" escape="1"/>',
+ function() {
+ set_hidden_field('remove_specials[u.admins]', 1);
+ submit_event('u.admins', 'OnMassCloneUsers');
+ } ) );
+
+
+ a_toolbar.AddButton( new ToolBarSeparator('sep2') );
+
a_toolbar.AddButton( new ToolBarButton('refresh', '<inp2:m_phrase label="la_ToolTip_ResetSettings" escape="1"/>::<inp2:m_phrase label="la_ShortToolTip_ResetSettings" escape="1"/>',
function() {
set_hidden_field('remove_specials[u.admins]', 1);
submit_event('u.admins', 'OnMassResetSettings');
} ) );
- a_toolbar.AddButton( new ToolBarSeparator('sep2') );
+ a_toolbar.AddButton( new ToolBarSeparator('sep3') );
a_toolbar.AddButton( new ToolBarButton('view', '<inp2:m_phrase label="la_ToolTip_View" escape="1"/>', function() {
show_viewmenu(a_toolbar,'view');
}
) );
a_toolbar.Render();
</script>
</td>
<inp2:m_RenderElement name="search_main_toolbar" prefix="u.admins" grid="Admins"/>
</tr>
</tbody>
</table>
<inp2:m_RenderElement name="grid" PrefixSpecial="u.admins" IdField="PortalUserId" grid="Admins" menu_filters="yes" grid_filters="1"/>
<script type="text/javascript">
- Grids['u.admins'].SetDependantToolbarButtons( new Array('edit','delete') );
+ Grids['u.admins'].SetDependantToolbarButtons( new Array('edit','delete','clone') );
</script>
<inp2:m_include t="incs/footer"/>
\ No newline at end of file
Property changes on: branches/RC/core/admin_templates/users/admins_list.tpl
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.3.2.2
\ No newline at end of property
+1.3.2.3
\ No newline at end of property
Index: branches/RC/core/admin_templates/users/root_edit_password.tpl
===================================================================
--- branches/RC/core/admin_templates/users/root_edit_password.tpl (revision 10004)
+++ branches/RC/core/admin_templates/users/root_edit_password.tpl (revision 10005)
@@ -1,35 +1,36 @@
<inp2:adm_SetPopupSize width="564" height="377"/>
<inp2:m_include t="incs/header"/>
<inp2:m_set u_id="-1"/>
<inp2:m_RenderElement name="combined_header" section="proj-base:admins" pagination="0" prefix="u" title_preset="root_edit"/>
<!-- ToolBar --->
<table class="toolbar" height="30" cellspacing="0" cellpadding="0" width="100%" border="0">
<tbody>
<tr>
<td>
<script type="text/javascript">
a_toolbar = new ToolBar();
a_toolbar.AddButton( new ToolBarButton('select', '<inp2:m_phrase label="la_ToolTip_Save" escape="1"/>', function() {
submit_event('u','OnUpdateRootPassword');
}
) );
a_toolbar.AddButton( new ToolBarButton('cancel', '<inp2:m_phrase label="la_ToolTip_Cancel" escape="1"/>', function() {
window.close();
}
) );
a_toolbar.Render();
</script>
</td>
</tr>
</tbody>
</table>
<inp2:u_SaveWarning name="grid_save_warning"/>
+<inp2:u_ErrorWarning name="form_error_warning"/>
<table width="100%" border="0" cellspacing="0" cellpadding="4" class="table-collapsed">
<inp2:m_RenderElement name="inp_edit_password" prefix="u" field="RootPassword" title="la_fld_Password"/>
<inp2:m_RenderElement name="inp_edit_password" prefix="u" field="VerifyRootPassword" title="la_fld_VerifyPassword"/>
</table>
<inp2:m_include t="incs/footer"/>
Property changes on: branches/RC/core/admin_templates/users/root_edit_password.tpl
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.5
\ No newline at end of property
+1.5.2.1
\ No newline at end of property
Index: branches/RC/core/admin_templates/js/script.js
===================================================================
--- branches/RC/core/admin_templates/js/script.js (revision 10004)
+++ branches/RC/core/admin_templates/js/script.js (revision 10005)
@@ -1,1450 +1,1454 @@
if ( !( isset($init_made) && $init_made ) ) {
var Application = new kApplication();
var Grids = new Array();
var Toolbars = new Array();
var $Menus = new Array();
var $ViewMenus = new Array();
var $nls_menus = new Array();
var $MenuNames = new Array();
var $form_name = 'kernel_form';
if(!$fw_menus) var $fw_menus = new Array();
var $env = '';
var submitted = false;
var unload_legal = false;
var $edit_mode = false;
var $init_made = true; // in case of double inclusion of script.js :)
// hook processing
var hBEFORE = 1; // this is const, but including this twice causes errors
var hAFTER = 2; // this is const, but including this twice causes errors
var $hooks = new Array();
replaceFireBug();
}
function use_popups($prefix_special, $event) {
return $use_popups;
}
function getArrayValue()
{
var $value = arguments[0];
var $current_key = 0;
$i = 1;
while ($i < arguments.length) {
$current_key = arguments[$i];
if (isset($value[$current_key])) {
$value = $value[$current_key];
}
else {
return false;
}
$i++;
}
return $value;
}
function setArrayValue()
{
// first argument - array, other arguments - keys (arrays too), last argument - value
var $array = arguments[0];
var $current_key = 0;
$i = 1;
while ($i < arguments.length - 1) {
$current_key = arguments[$i];
if (!isset($array[$current_key])) {
$array[$current_key] = new Array();
}
$array = $array[$current_key];
$i++;
}
$array[$array.length] = arguments[arguments.length - 1];
}
function resort_grid($prefix_special, $field, $ajax)
{
set_form($prefix_special, $ajax);
set_hidden_field($prefix_special + '_Sort1', $field);
submit_event($prefix_special, 'OnSetSorting', null, null, $ajax);
}
function direct_sort_grid($prefix_special, $field, $direction, $field_pos, $ajax)
{
if(!isset($field_pos)) $field_pos = 1;
set_form($prefix_special, $ajax);
set_hidden_field($prefix_special+'_Sort'+$field_pos,$field);
set_hidden_field($prefix_special+'_Sort'+$field_pos+'_Dir',$direction);
set_hidden_field($prefix_special+'_SortPos',$field_pos);
submit_event($prefix_special,'OnSetSortingDirect', null, null, $ajax);
}
function reset_sorting($prefix_special)
{
submit_event($prefix_special,'OnResetSorting');
}
function set_per_page($prefix_special, $per_page, $ajax)
{
set_form($prefix_special, $ajax);
set_hidden_field($prefix_special + '_PerPage', $per_page);
submit_event($prefix_special, 'OnSetPerPage', null, null, $ajax);
}
function submit_event(prefix_special, event, t, form_action, $ajax)
{
if (!Application.processHooks(prefix_special + ':' + event)) {
return false;
}
if ($ajax) {
return $Catalog.submit_event(prefix_special, event, t);
}
if (event) {
set_hidden_field('events[' + prefix_special + ']', event);
}
if (t) set_hidden_field('t', t);
if (form_action) {
var old_env = '';
if (!form_action.match(/\?/)) {
document.getElementById($form_name).action.match(/.*(\?.*)/);
old_env = RegExp.$1;
}
document.getElementById($form_name).action = form_action + old_env;
}
submit_kernel_form();
}
function submit_action($url, $action)
{
$form = document.getElementById($form_name);
$form.action = $url;
set_hidden_field('Action', $action);
submit_kernel_form();
}
function show_form_data()
{
var $kf = document.getElementById($form_name);
$ret = '';
for(var i in $kf.elements)
{
$elem = $kf.elements[i];
$ret += $elem.id + ' = ' + $elem.value + "\n";
}
alert($ret);
}
function submit_kernel_form()
{
if (submitted) {
return;
}
submitted = true;
unload_legal = true;
var $form = document.getElementById($form_name);
if (typeof $form.onsubmit == "function") {
$form.onsubmit();
}
$form.submit();
$form.target = '';
set_hidden_field('t', t);
window.setTimeout(function() {submitted = false}, 500);
}
function set_event(prefix_special, event)
{
var event_field=document.getElementById('events[' + prefix_special + ']');
if(isset(event_field))
{
event_field.value = event;
}
}
function isset(variable)
{
if(variable==null) return false;
return (typeof(variable)=='undefined')?false:true;
}
function in_array(needle, haystack)
{
return array_search(needle, haystack) != -1;
}
function array_search(needle, haystack)
{
for (var i=0; i<haystack.length; i++)
{
if (haystack[i] == needle) return i;
}
return -1;
}
function print_pre(variable, msg)
{
if (!isset(msg)) msg = '';
var s = msg;
for (prop in variable) {
s += prop+" => "+variable[prop] + "\n";
}
alert(s);
}
function go_to_page($prefix_special, $page, $ajax)
{
set_form($prefix_special, $ajax);
set_hidden_field($prefix_special + '_Page', $page);
submit_event($prefix_special, null, null, null, $ajax);
}
function go_to_list(prefix_special, tab)
{
set_hidden_field(prefix_special+'_GoTab', tab);
submit_event(prefix_special,'OnUpdateAndGoToTab',null);
}
function go_to_tab(prefix_special, tab)
{
set_hidden_field(prefix_special+'_GoTab', tab);
submit_event(prefix_special,'OnPreSaveAndGoToTab',null);
}
function go_to_id(prefix_special, id)
{
set_hidden_field(prefix_special+'_GoId', id);
submit_event(prefix_special,'OnPreSaveAndGo')
}
// in-portal compatibility functions: begin
function getScriptURL($script_name, tpl)
{
tpl = tpl ? '-'+tpl : '';
var $asid = get_hidden_field('sid');
return base_url+$script_name+'?env='+( isset($env)&&$env?$env:$asid )+tpl+'&en=0';
}
function OpenEditor(extra_env,TargetForm,TargetField)
{
// var $url = getScriptURL('admin/editor/editor_new.php');
var $url = getScriptURL('admin/index.php', 'popups/editor');
// alert($url);
$url = $url+'&TargetForm='+TargetForm+'&TargetField='+TargetField+'&destform=popup';
if(extra_env.length>0) $url += extra_env;
openwin($url,'html_edit',800,575);
}
function OpenUserSelector(extra_env,TargetForm,TargetField)
{
var $url = getScriptURL('admin/users/user_select.php');
$url += '&destform='+TargetForm+'&Selector=radio&destfield='+TargetField+'&IdField=Login';
if(extra_env.length>0) $url += extra_env;
openwin($url,'user_select',800,575);
return false;
}
function OpenCatSelector(extra_env)
{
var $url = getScriptURL('admin/cat_select.php');
if(extra_env.length>0) $url += extra_env;
openwin($url,'catselect',750,400);
}
function OpenItemSelector(extra_env,$TargetForm)
{
var $url = getScriptURL('admin/relation_select.php') + '&destform='+$TargetForm;
if(extra_env.length>0) $url += extra_env;
openwin($url,'groupselect',750,400);
}
function OpenUserEdit($user_id, $extra_env)
{
var $url = getScriptURL('admin/users/adduser.php') + '&direct_id=' + $user_id;
if( isset($extra_env) ) $url += $extra_env;
window.location.href = $url;
}
function OpenLinkEdit($link_id, $extra_env)
{
var $url = getScriptURL('in-link/admin/addlink.php') + '&item=' + $link_id;
if( isset($extra_env) ) $url += $extra_env;
window.location.href = $url;
}
function OpenHelp($help_link)
{
// $help_link.match('http://(.*).lv/in-commerce/admin(.*)');
// alert(RegExp.$2);
openwin($help_link,'HelpPopup',750,400);
}
function openEmailSend($url, $type, $prefix_special)
{
var $kf = document.getElementById($form_name);
var $prev_action = $kf.action;
var $prev_opener = get_hidden_field('m_opener');
$kf.action = $url;
set_hidden_field('m_opener', 'p');
$kf.target = 'sendmail';
set_hidden_field('idtype', 'group');
set_hidden_field('idlist', Grids[$prefix_special].GetSelected().join(',') );
openwin('','sendmail',750,400);
submit_kernel_form();
$kf.action = $prev_action;
set_hidden_field('m_opener', $prev_opener);
}
// in-portal compatibility functions: end
function InitTranslator(prefix, field, t, multi_line)
{
var $kf = document.getElementById($form_name);
var $window_name = 'select_'+t.replace(/(\/|-)/g, '_');
var $regex = new RegExp('(.*)\?env=(' + document.getElementById('sid').value + ')?-(.*?):(m[^:]+)');
$regex = $regex.exec($kf.action);
// set_hidden_field('return_m', $regex[4]);
var $prev_opener = get_hidden_field('m_opener');
if (!isset(multi_line)) multi_line = 0;
openwin('', $window_name, 750, 400);
// set_hidden_field('return_template', $kf.elements['t'].value); // where should return after popup is done
set_hidden_field('m_opener', 'p');
set_hidden_field('translator_wnd_name', $window_name);
set_hidden_field('translator_field', field);
set_hidden_field('translator_t', t);
set_hidden_field('translator_prefixes', prefix);
set_hidden_field('translator_multi_line', multi_line);
$kf.target = $window_name;
return $prev_opener;
}
function PreSaveAndOpenTranslator(prefix, field, t, multi_line)
{
var $prev_opener = InitTranslator(prefix, field, t, multi_line);
var split_prefix = prefix.split(',');
submit_event(split_prefix[0], 'OnPreSaveAndOpenTranslator');
set_hidden_field('m_opener', $prev_opener);
}
function PreSaveAndOpenTranslatorCV(prefix, field, t, resource_id, multi_line)
{
var $prev_opener = InitTranslator(prefix, field, t, multi_line);
set_hidden_field('translator_resource_id', resource_id);
var split_prefix = prefix.split(',');
submit_event(split_prefix[0],'OnPreSaveAndOpenTranslator');
set_hidden_field('m_opener', $prev_opener);
}
function openTranslator(prefix,field,url,wnd)
{
var $kf = document.getElementById($form_name);
set_hidden_field('trans_prefix', prefix);
set_hidden_field('trans_field', field);
set_hidden_field('events[trans]', 'OnLoad');
var $regex = new RegExp('(.*)\?env=(' + document.getElementById('sid').value + ')?-(.*?):(.*)');
var $t = $regex.exec(url)[3];
$kf.target = wnd;
submit_event(prefix,'',$t,url);
}
function openwin($url,$name,$width,$height)
{
// prevent window from opening larger, then screen resolution on user's computer (to Kostja)
// alert('openwin: name = ['+$name+']');
var left = Math.round((screen.width - $width)/2);
var top = Math.round((screen.height - $height)/2);
cur_x = is.ie ? window.screenLeft : window.screenX;
cur_y = is.ie ? window.screenTop : window.screenY;
// alert('current X,Y: '+cur_x+','+cur_y+' target x,y: '+left+','+top);
var $window_params = 'left='+left+',top='+top+',width='+$width+',height='+$height+',status=yes,resizable=yes,menubar=no,scrollbars=yes,toolbar=no';
return window.open($url,$name,$window_params);
}
function OnResizePopup(e) {
if (!document.all) {
var $winW = window.innerWidth;
var $winH = window.innerHeight;
}
else {
var $winW = window.document.body.offsetWidth;
var $winH = window.document.body.offsetHeight;
}
window.status = '[width: ' + $winW + '; height: ' + $winH + ']';
}
function opener_action(new_action)
{
var $prev_opener = get_hidden_field('m_opener');
set_hidden_field('m_opener', new_action);
return $prev_opener;
}
function open_popup($prefix_special, $event, $t, $window_size) {
if (!$window_size) {
// if no size given, then query it from ajax
var $default_size = '750x400';
var $pm = getFrame('head').$popup_manager;
if ($pm) {
// popup manager was found in head frame
$pm.ResponceFunction = function ($responce) {
if (!$responce.match(/([\d]+)x([\d]+)/)) {
// invalid responce was received, may be php fatal error during AJAX request
$responce = $default_size;
}
open_popup($prefix_special, $event, $t, $responce);
}
$pm.GetSize($t);
return ;
}
$window_size = $default_size;
}
var $kf = document.getElementById($form_name);
var $window_name = $t.replace(/(\/|-)/g, '_'); // replace "/" and "-" with "_"
$window_size = $window_size.split('x');
openwin('', $window_name, $window_size[0], $window_size[1]);
$kf.target = $window_name;
var $prev_opener = opener_action('p');
event_bak = get_hidden_field('events[' + $prefix_special + ']')
if (!event_bak) event_bak = '';
submit_event($prefix_special, $event, $t);
opener_action($prev_opener); // restore opener in parent window
set_hidden_field('events[' + $prefix_special + ']', event_bak); // restore event
// AJAX popup size respoce is received after std_edit_item/std_precreate_item function exit
set_hidden_field($prefix_special + '_mode', null);
}
function openSelector($prefix, $url, $dst_field, $window_size, $event)
{
// if url has additional params - store it and make hidden fields from it (later, below)
var $additional = [];
if ($url.match('(.*?)&(.*)')) {
$url = RegExp.$1;
var tmp = RegExp.$2;
var pairs = tmp.split('&');
for (var i in pairs) {
var data = pairs[i].split('=');
$additional[data[0]] = data[1];
}
}
// get template name from url
var $regex = new RegExp('(.*)\?env=(' + document.getElementById('sid').value + ')?-(.*?):(m[^:]+)');
$regex = $regex.exec($url);
var $t = $regex[3];
// substitute form action with selector's url
var $kf = document.getElementById($form_name);
var $prev_action = $kf.action;
$kf.action = $url;
// check parameter values
if (!isset($event)) $event = '';
Application.processHooks($prefix + ':OnBeforeOpenSelector');
// set variables need for selector to work
set_hidden_field('main_prefix', $prefix);
set_hidden_field('dst_field', $dst_field);
for (var i in $additional)
{
set_hidden_field(i, $additional[i]);
}
open_popup($prefix, $event, $t);
// restore form action back
$kf.action = $prev_action;
}
function translate_phrase($label, $template) {
set_hidden_field('phrases_label', $label);
open_popup('phrases', 'OnNew', $template);
}
function std_precreate_item(prefix_special, edit_template)
{
set_hidden_field(prefix_special+'_mode', 't');
if (use_popups(prefix_special, 'OnPreCreate')) {
open_popup(prefix_special, 'OnPreCreate', edit_template);
}
else {
opener_action('d');
submit_event(prefix_special,'OnPreCreate', edit_template);
}
// set_hidden_field(prefix_special+'_mode', '');
}
function std_new_item(prefix_special, edit_template)
{
if (use_popups(prefix_special, 'OnNew')) {
open_popup(prefix_special, 'OnNew', edit_template);
}
else {
opener_action('d');
submit_event(prefix_special,'OnNew', edit_template);
}
}
function std_edit_item(prefix_special, edit_template)
{
set_hidden_field(prefix_special+'_mode', 't');
if (use_popups(prefix_special, 'OnEdit')) {
open_popup(prefix_special, 'OnEdit', edit_template);
}
else {
opener_action('d');
submit_event(prefix_special,'OnEdit',edit_template);
}
// set_hidden_field(prefix_special+'_mode', '');
}
function std_edit_temp_item(prefix_special, edit_template)
{
if (use_popups(prefix_special, '')) {
open_popup(prefix_special, '', edit_template);
}
else {
opener_action('d');
submit_event(prefix_special,'',edit_template);
}
}
function std_delete_items(prefix_special, t, $ajax)
{
- if (inpConfirm('Are you sure you want to delete selected items?')) {
+ var phrase = phrases['la_Delete_Confirm'] ? phrases['la_Delete_Confirm'] : 'Are you sure you want to delete selected items?';
+ if (inpConfirm(phrase)) {
submit_event(prefix_special, 'OnMassDelete', t, null, $ajax);
}
}
function std_csv_export(prefix_special, grid, template)
{
set_hidden_field('PrefixSpecial', prefix_special);
set_hidden_field('grid', grid);
if (use_popups(prefix_special, '')) {
open_popup(prefix_special, '', template);
}
else {
submit_event(prefix_special, '', template);
}
}
function std_csv_import(prefix_special, grid, template)
{
set_hidden_field('PrefixSpecial', prefix_special);
set_hidden_field('grid', grid);
if (use_popups(prefix_special, '')) {
open_popup(prefix_special, '', template);
}
else {
submit_event(prefix_special, '', template);
}
}
// set current form base on ajax
function set_form($prefix_special, $ajax)
{
if ($ajax) {
$form_name = $Catalog.queryTabRegistry('prefix', $prefix_special, 'tab_id') + '_form';
}
}
// sets hidden field value
// if the field does not exist - creates it
function set_hidden_field($field_id, $value, $has_id)
{
var $kf = document.getElementById($form_name);
var $field = $kf.elements[$field_id];
if ($value === null) {
if ($field) {
$kf.removeChild($field);
}
return true;
}
if ($field) {
$field.value = $value;
return true;
}
$field = document.createElement('INPUT');
$field.type = 'hidden';
$field.name = $field_id;
if (!isset($has_id) || $has_id) {
$field.id = $field_id;
}
$field.value = $value;
$kf.appendChild($field);
return false;
}
// sets hidden field value
// if the field does not exist - creates it
function setInnerHTML($field_id, $value)
{
var $element = document.getElementById($field_id);
if (!$element) return false;
$element.innerHTML = $value;
}
function get_hidden_field($field)
{
var $kf = document.getElementById($form_name);
return $kf.elements[$field] ? $kf.elements[$field].value : false;
}
function search($prefix_special, $grid_name, $ajax)
{
set_form($prefix_special, $ajax);
set_hidden_field('grid_name', $grid_name);
submit_event($prefix_special, 'OnSearch', null, null, $ajax);
}
function search_reset($prefix_special, $grid_name, $ajax)
{
set_form($prefix_special, $ajax);
set_hidden_field('grid_name', $grid_name);
submit_event($prefix_special, 'OnSearchReset', null, null, $ajax);
}
function search_keydown($event, $prefix_special, $grid, $ajax)
{
$event = $event ? $event : event;
if (window.event) {// IE
var $key_code = $event.keyCode;
}
else if($event.which) { // Netscape/Firefox/Opera
var $key_code = $event.which;
}
switch ($key_code) {
case 13:
search($prefix_special, $grid, parseInt($ajax));
break;
case 27:
search_reset($prefix_special, $grid, parseInt($ajax));
break;
}
}
function getRealLeft(el)
{
if (typeof(el) == 'string') {
el = document.getElementById(el);
}
xPos = el.offsetLeft;
tempEl = el.offsetParent;
while (tempEl != null)
{
xPos += tempEl.offsetLeft;
tempEl = tempEl.offsetParent;
}
// if (obj.x) return obj.x;
return xPos;
}
function getRealTop(el)
{
if (typeof(el) == 'string') {
el = document.getElementById(el);
}
yPos = el.offsetTop;
tempEl = el.offsetParent;
while (tempEl != null)
{
yPos += tempEl.offsetTop;
tempEl = tempEl.offsetParent;
}
// if (obj.y) return obj.y;
return yPos;
}
function show_viewmenu_old($toolbar, $button_id)
{
var $img = $toolbar.GetButtonImage($button_id);
var $pos_x = getRealLeft($img) - ((document.all) ? 6 : -2);
var $pos_y = getRealTop($img) + 32;
var $prefix_special = '';
window.triedToWriteMenus = false;
if($ViewMenus.length == 1)
{
$prefix_special = $ViewMenus[$ViewMenus.length-1];
$fw_menus[$prefix_special+'_view_menu']();
$Menus[$prefix_special+'_view_menu'].writeMenus('MenuContainers['+$prefix_special+']');
window.FW_showMenu($Menus[$prefix_special+'_view_menu'], $pos_x, $pos_y);
}
else
{
// prepare menus
for(var $i in $ViewMenus)
{
$prefix_special = $ViewMenus[$i];
$fw_menus[$prefix_special+'_view_menu']();
}
$Menus['mixed'] = new Menu('ViewMenu_mixed');
// merge menus into new one
for(var $i in $ViewMenus)
{
$prefix_special = $ViewMenus[$i];
$Menus['mixed'].addMenuItem( $Menus[$prefix_special+'_view_menu'] );
}
$Menus['mixed'].writeMenus('MenuContainers[mixed]');
window.FW_showMenu($Menus['mixed'], $pos_x, $pos_y);
}
}
var nlsMenuRendered = false;
function show_viewmenu($toolbar, $button_id)
{
if($ViewMenus.length == 1) {
$prefix_special = $ViewMenus[$ViewMenus.length-1];
menu_to_show = $prefix_special+'_view_menu';
}
else
{
mixed_menu = menuMgr.createMenu(rs('mixed_menu'));
mixed_menu.applyBorder(false, false, false, false);
mixed_menu.dropShadow("none");
mixed_menu.showIcon = true;
// merge menus into new one
for(var $i in $ViewMenus)
{
$prefix_special = $ViewMenus[$i];
mixed_menu.addItem( rs($prefix_special+'.view.menu.mixed'),
$MenuNames[$prefix_special+'_view_menu'],
'javascript:void()', null, true, null,
rs($prefix_special+'.view.menu'),$MenuNames[$prefix_special+'_view_menu'] );
}
menu_to_show = 'mixed_menu';
}
renderMenus();
nls_showMenu(rs(menu_to_show), $toolbar.GetButtonImage($button_id))
}
function renderMenus()
{
menuMgr.renderMenus('nlsMenuPlace');
nlsMenuRendered = true;
}
function set_window_title($title)
{
var $window = window;
if($window.parent) $window = $window.parent;
$window.document.title = (main_title.length ? main_title + ' - ' : '') + $title;
}
function set_filter($prefix_special, $filter_id, $filter_value, $ajax)
{
set_form($prefix_special, $ajax);
set_hidden_field('filter_id', $filter_id);
set_hidden_field('filter_value', $filter_value);
submit_event($prefix_special, 'OnSetFilter', null, null, $ajax);
}
function filters_remove_all($prefix_special, $ajax)
{
set_form($prefix_special, $ajax);
submit_event($prefix_special,'OnRemoveFilters', null, null, $ajax);
}
function filters_apply_all($prefix_special, $ajax)
{
set_form($prefix_special, $ajax);
submit_event($prefix_special,'OnApplyFilters', null, null, $ajax);
}
function RemoveTranslationLink($string, $escaped)
{
if (!isset($escaped)) $escaped = true;
if ($escaped) {
return $string.replace(/&lt;a href=&quot;(.*?)&quot;&gt;(.*?)&lt;\/a&gt;/g, '$2');
}
return $string.replace(/<a href="(.*?)">(.*?)<\/a>/g, '$2');
}
function redirect($url)
{
window.location.href = $url;
}
function update_checkbox_options($cb_mask, $hidden_id)
{
var $kf = document.getElementById($form_name);
var $tmp = '';
for (var i = 0; i < $kf.elements.length; i++)
{
if ( $kf.elements[i].id.match($cb_mask) )
{
if ($kf.elements[i].checked) $tmp += '|'+$kf.elements[i].value;
}
}
if($tmp.length > 0) $tmp += '|';
document.getElementById($hidden_id).value = $tmp.replace(/,$/, '');
}
function update_multiple_options($hidden_id) {
var $select = document.getElementById($hidden_id + '_select');
var $result = '';
for (var $i = 0; $i < $select.options.length; $i++) {
if ($select.options[$i].selected) {
$result += $select.options[$i].value + '|';
}
}
document.getElementById($hidden_id).value = $result ? '|' + $result : '';
}
// related to lists operations (moving)
- function move_selected($from_list, $to_list)
+ function move_selected($from_list, $to_list, $error_msg)
{
if (typeof($from_list) != 'object') $from_list = document.getElementById($from_list);
if (typeof($to_list) != 'object') $to_list = document.getElementById($to_list);
if (has_selected_options($from_list))
{
var $from_array = select_to_array($from_list);
var $to_array = select_to_array($to_list);
var $new_from = Array();
var $cur = null;
for (var $i = 0; $i < $from_array.length; $i++)
{
$cur = $from_array[$i];
if ($cur[2]) // If selected - add to To array
{
$to_array[$to_array.length] = $cur;
}
else //Else - keep in new From
{
$new_from[$new_from.length] = $cur;
}
}
$from_list = array_to_select($new_from, $from_list);
$to_list = array_to_select($to_array, $to_list);
}
else
{
- alert('Please select items to perform moving!');
+ alert(isset($error_msg) ? $error_msg : 'Please select items to perform moving!');
}
}
function select_to_array($aSelect)
{
var $an_array = new Array();
var $cur = null;
for (var $i = 0; $i < $aSelect.length; $i++)
{
$cur = $aSelect.options[$i];
$an_array[$an_array.length] = new Array($cur.text, $cur.value, $cur.selected);
}
return $an_array;
}
function array_to_select($anArray, $aSelect)
{
var $initial_length = $aSelect.length;
for (var $i = $initial_length - 1; $i >= 0; $i--)
{
$aSelect.options[$i] = null;
}
for (var $i = 0; $i < $anArray.length; $i++)
{
$cur = $anArray[$i];
$aSelect.options[$aSelect.length] = new Option($cur[0], $cur[1]);
}
}
function select_compare($a, $b)
{
if ($a[0] < $b[0])
return -1;
if ($a[0] > $b[0])
return 1;
return 0;
}
function select_to_string($aSelect)
{
var $result = '';
var $cur = null;
if (typeof($aSelect) != 'object') $aSelect = document.getElementById($aSelect);
for (var $i = 0; $i < $aSelect.length; $i++)
{
$result += $aSelect.options[$i].value + '|';
}
return $result.length ? '|' + $result : '';
}
function selected_to_string($aSelect)
{
var $result = '';
var $cur = null;
if (typeof($aSelect) != 'object') $aSelect = document.getElementById($aSelect);
for (var $i = 0; $i < $aSelect.length; $i++)
{
$cur = $aSelect.options[$i];
if ($cur.selected && $cur.value != '')
{
$result += $cur.value + '|';
}
}
return $result.length ? '|' + $result : '';
}
function string_to_selected($str, $aSelect)
{
var $cur = null;
for (var $i = 0; $i < $aSelect.length; $i++)
{
$cur = $aSelect.options[$i];
$aSelect.options[$i].selected = $str.match('\\|' + $cur.value + '\\|') ? true : false;
}
}
function set_selected($selected_options, $aSelect)
{
if (!$selected_options.length) return false;
for (var $i = 0; $i < $aSelect.length; $i++)
{
for (var $k = 0; $k < $selected_options.length; $k++)
{
if ($aSelect.options[$i].value == $selected_options[$k])
{
$aSelect.options[$i].selected = true;
}
}
}
}
function get_selected_count($theList)
{
var $count = 0;
var $cur = null;
for (var $i = 0; $i < $theList.length; $i++)
{
$cur = $theList.options[$i];
if ($cur.selected) $count++;
}
return $count;
}
function get_selected_index($aSelect, $typeIndex)
{
var $index = 0;
for (var $i = 0; $i < $aSelect.length; $i++)
{
if ($aSelect.options[$i].selected)
{
$index = $i;
if ($typeIndex == 'firstSelected') break;
}
}
return $index;
}
function has_selected_options($theList)
{
var $ret = false;
var $cur = null;
for (var $i = 0; $i < $theList.length; $i++)
{
$cur = $theList.options[$i];
- if ($cur.selected) $ret = true;
+ if ($cur.selected) {
+ $ret = true;
+ break;
+ }
}
return $ret;
}
function select_sort($aSelect)
{
if (typeof($aSelect) != 'object') $aSelect = document.getElementById($aSelect);
var $to_array = select_to_array($aSelect);
$to_array.sort(select_compare);
array_to_select($to_array, $aSelect);
}
function move_options_up($aSelect, $interval)
{
if (typeof($aSelect) != 'object') $aSelect = document.getElementById($aSelect);
if (has_selected_options($aSelect))
{
var $selected_options = Array();
var $first_selected = get_selected_index($aSelect, 'firstSelected');
for (var $i = 0; $i < $aSelect.length; $i++)
{
if ($aSelect.options[$i].selected && ($first_selected > 0) )
{
swap_options($aSelect, $i, $i - $interval);
$selected_options[$selected_options.length] = $aSelect.options[$i - $interval].value;
}
else if ($first_selected == 0)
{
//alert('Begin of list');
break;
}
}
set_selected($selected_options, $aSelect);
}
else
{
//alert('Check items from moving');
}
}
function move_options_down($aSelect, $interval)
{
if (typeof($aSelect) != 'object') $aSelect = document.getElementById($aSelect);
if (has_selected_options($aSelect))
{
var $last_selected = get_selected_index($aSelect, 'lastSelected');
var $selected_options = Array();
for (var $i = $aSelect.length - 1; $i >= 0; $i--)
{
if ($aSelect.options[$i].selected && ($aSelect.length - ($last_selected + 1) > 0))
{
swap_options($aSelect, $i, $i + $interval);
$selected_options[$selected_options.length] = $aSelect.options[$i + $interval].value;
}
else if ($last_selected + 1 == $aSelect.length)
{
//alert('End of list');
break;
}
}
set_selected($selected_options, $aSelect);
}
else
{
//alert('Check items from moving');
}
}
function swap_options($aSelect, $src_num, $dst_num)
{
var $src_html = $aSelect.options[$src_num].innerHTML;
var $dst_html = $aSelect.options[$dst_num].innerHTML;
var $src_value = $aSelect.options[$src_num].value;
var $dst_value = $aSelect.options[$dst_num].value;
var $src_option = document.createElement('OPTION');
var $dst_option = document.createElement('OPTION');
$aSelect.remove($src_num);
$aSelect.options.add($dst_option, $src_num);
$dst_option.innerText = $dst_html;
$dst_option.value = $dst_value;
$dst_option.innerHTML = $dst_html;
$aSelect.remove($dst_num);
$aSelect.options.add($src_option, $dst_num);
$src_option.innerText = $src_html;
$src_option.value = $src_value;
$src_option.innerHTML = $src_html;
}
function getXMLHTTPObject(content_type)
{
if (!isset(content_type)) content_type = 'text/plain';
var http_request = false;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
http_request.overrideMimeType(content_type);
// See note below about this line
}
} else if (window.ActiveXObject) { // IE
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
return http_request;
}
function str_repeat($symbol, $count)
{
var $i = 0;
var $ret = '';
while($i < $count) {
$ret += $symbol;
$i++;
}
return $ret;
}
function getDocumentFromXML(xml)
{
if (window.ActiveXObject) {
var doc = new ActiveXObject("Microsoft.XMLDOM");
doc.async=false;
doc.loadXML(xml);
}
else {
var parser = new DOMParser();
var doc = parser.parseFromString(xml,"text/xml");
}
return doc;
}
function set_persistant_var($var_name, $var_value, $t, $form_action)
{
set_hidden_field('field', $var_name);
set_hidden_field('value', $var_value);
submit_event('u', 'OnSetPersistantVariable', $t, $form_action);
}
/*functionremoveEvent(el, evname, func) {
if (Calendar.is_ie) {
el.detachEvent("on" + evname, func);
} else {
el.removeEventListener(evname, func, true);
}
};*/
function setCookie($Name, $Value)
{
// set cookie
if(getCookie($Name) != $Value)
{
document.cookie = $Name+'='+escape($Value)+'; path=' + $base_path + '/';
}
}
function getCookie($Name)
{
// get cookie
var $cookieString = document.cookie;
var $index = $cookieString.indexOf($Name+'=');
if($index == -1) return null;
$index = $cookieString.indexOf('=',$index)+1;
var $endstr = $cookieString.indexOf(';',$index);
if($endstr == -1) $endstr = $cookieString.length;
return unescape($cookieString.substring($index, $endstr));
}
function deleteCookie($Name)
{
// deletes cookie
if (getCookie($Name))
{
document.cookie = $Name+'=; expires=Thu, 01-Jan-70 00:00:01 GMT; path=/';
}
}
function addElement($dst_element, $tag_name) {
var $new_element = document.createElement($tag_name.toUpperCase());
$dst_element.appendChild($new_element);
return $new_element;
}
Math.sum = function($array) {
var $i = 0;
var $total = 0;
while ($i < $array.length) {
$total += $array[$i];
$i++;
}
return $total;
}
Math.average = function($array) {
return Math.sum($array) / $array.length;
}
// remove spaces and underscores from a string, used for nls_menu
function rs(str)
{
return str.replace(/[ _\']+/g, '.');
}
function getFrame($name)
{
var $main_window = window;
// 1. cycle through popups to get main window
try {
// will be error, when other site is opened in parent window
while ($main_window.opener) {
$main_window = $main_window.opener;
}
}
catch (err) {
// catch Access/Permission Denied error
// alert('getFrame.Error: [' + err.description + ']');
return window;
}
var $frameset = $main_window.parent.frames;
for ($i = 0; $i < $frameset.length; $i++) {
if ($frameset[$i].name == $name) {
return $frameset[$i];
}
}
return $main_window.parent;
}
function ClearBrowserSelection()
{
if (window.getSelection) {
// removeAllRanges will be supported by Opera from v 9+, do nothing by now
var selection = window.getSelection();
if (selection.removeAllRanges) { // Mozilla & Opera 9+
// alert('clearing FF')
window.getSelection().removeAllRanges();
}
} else if (document.selection && !is.opera) { // IE
// alert('clearing IE')
document.selection.empty();
}
}
function reset_form(prefix, event, msg)
{
if (confirm(RemoveTranslationLink(msg, true))) {
submit_event(prefix, event)
}
}
function cancel_edit(prefix, cancel_ev, save_ev, msg)
{
if ((!Form || (Form && Form.HasChanged)) && confirm(RemoveTranslationLink(msg, true))) {
submit_event(prefix, save_ev)
}
else {
submit_event(prefix, cancel_ev)
}
}
function execJS(node)
{
var bSaf = (navigator.userAgent.indexOf('Safari') != -1);
var bOpera = (navigator.userAgent.indexOf('Opera') != -1);
var bMoz = (navigator.appName == 'Netscape');
if (!node) return;
/* IE wants it uppercase */
var st = node.getElementsByTagName('SCRIPT');
var strExec;
for(var i=0;i<st.length; i++)
{
if (bSaf) {
strExec = st[i].innerHTML;
st[i].innerHTML = "";
} else if (bOpera) {
strExec = st[i].text;
st[i].text = "";
} else if (bMoz) {
strExec = st[i].textContent;
st[i].textContent = "";
} else {
strExec = st[i].text;
st[i].text = "";
}
try {
var x = document.createElement("script");
x.type = "text/javascript";
/* In IE we must use .text! */
if ((bSaf) || (bOpera) || (bMoz))
x.innerHTML = strExec;
else x.text = strExec;
document.getElementsByTagName("head")[0].appendChild(x);
} catch(e) {
alert(e);
}
}
};
function NumberFormatter() {}
NumberFormatter.ThousandsSep = '\'';
NumberFormatter.DecimalSep = '.';
NumberFormatter.Parse = function(num)
{
if (num == '') return 0;
return parseFloat( num.toString().replace(this.ThousandsSep, '').replace(this.DecimalSep, '.') );
}
NumberFormatter.Format = function(num)
{
num += '';
x = num.split('.');
x1 = x[0];
x2 = x.length > 1 ? this.DecimalSep + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + this.ThousandsSep + '$2');
}
return x1 + x2;
}
function getDimensions(obj) {
var style
if (obj.currentStyle) {
style = obj.currentStyle;
}
else {
style = getComputedStyle(obj,'');
}
padding = [parseInt(style.paddingTop), parseInt(style.paddingRight), parseInt(style.paddingBottom), parseInt(style.paddingLeft)]
border = [parseInt(style.borderTopWidth), parseInt(style.borderRightWidth), parseInt(style.borderBottomWidth), parseInt(style.borderLeftWidth)]
for (var i in padding) if ( isNaN( padding[i] ) ) padding[i] = 0
for (var i in border) if ( isNaN( border[i] ) ) border[i] = 0
var result = new Object();
result.innerHeight = obj.clientHeight - padding[0] - padding[2];
result.innerWidth = obj.clientWidth - padding[1] - padding[3];
result.padding = padding;
result.borders = border;
return result;
}
function findPos(obj) {
var curleft = curtop = 0;
if (obj.offsetParent) {
curleft = obj.offsetLeft
curtop = obj.offsetTop
while (obj = obj.offsetParent) {
curleft += obj.offsetLeft
curtop += obj.offsetTop
}
}
return [curleft,curtop];
}
function addEvent(el, evname, func, traditional) {
if (traditional) {
eval('el.on'+evname+'='+func);
return;
}
if (is.ie) {
el.attachEvent("on" + evname, func);
} else {
el.addEventListener(evname, func, true);
}
};
function addLoadEvent(func, wnd) {
if (!wnd) wnd = window
var oldonload = wnd.onload;
if (typeof wnd.onload != 'function') {
wnd.onload = func;
} else {
wnd.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
function replaceFireBug() {
if (!window.console || !console.firebug) {
var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml",
"group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];
window.console = {};
for (var i = 0; i < names.length; ++i) {
window.console[names[i]] = function() {
alert('FireBug console object methods are not available outside Firefox!');
}
}
}
}
function runOnChange(elId) {
var evt;
var el = typeof(elId) == 'string' ? document.getElementById(elId) : elId
if (document.createEvent) {
evt = document.createEvent("HTMLEvents");
evt.initEvent("change", true, false);
(evt) ? el.dispatchEvent(evt) : (el.onchange && el.onchange());
return;
}
if (el.fireEvent) {
el.fireEvent('onchange');
}
}
function WatchClosing(win, url)
{
window.setTimeout(function() {
if (win.closed) {
var req = Request.getRequest();
var $ajax_mark = (url.indexOf('?') ? '&' : '?') + 'ajax=yes';
req.open('GET', url + $ajax_mark, false); //!!!SYNCRONIOUS!!! REQUEST (3rd param = false!!!)
req.send(null);
}
},
2000
)
}
\ No newline at end of file
Property changes on: branches/RC/core/admin_templates/js/script.js
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.11.2.8
\ No newline at end of property
+1.11.2.9
\ No newline at end of property
Index: branches/RC/core/admin_templates/incs/header.tpl
===================================================================
--- branches/RC/core/admin_templates/incs/header.tpl (revision 10004)
+++ branches/RC/core/admin_templates/incs/header.tpl (revision 10005)
@@ -1,60 +1,61 @@
<inp2:m_DefaultParam body_properties=""/>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title><inp2:m_GetConfig var="Site_Name"/> - <inp2:m_Phrase label="la_AdministrativeConsole"/></title>
<meta http-equiv="content-type" content="text/html; charset=<inp2:lang_GetCharset/>">
<meta name="keywords" content="...">
<meta name="description" content="...">
<meta name="robots" content="all">
<meta name="copyright" content="Copyright &#174; 2006 Test, Inc">
<meta name="author" content="Intechnic Inc.">
<inp2:m_base_ref/>
<link rel="icon" href="img/favicon.ico" type="image/x-icon" />
<link rel="shortcut icon" href="img/favicon.ico" type="image/x-icon" />
<link rel="stylesheet" rev="stylesheet" href="incs/style.css" type="text/css" />
<script type="text/javascript" src="js/is.js"></script>
<script type="text/javascript" src="js/ajax.js"></script>
<script language="javascript" src="js/application.js"></script>
<script type="text/javascript" src="js/script.js"></script>
<script type="text/javascript" src="js/in-portal.js"></script>
<script type="text/javascript" src="js/toolbar.js"></script>
<script type="text/javascript" src="js/grid.js"></script>
<script type="text/javascript" src="js/forms.js"></script>
+<script type="text/javascript" src="js/form_controls.js"></script>
<script type="text/javascript" src="js/calendar.js"></script>
<script language="javascript">
var t = '<inp2:m_get param="t"/>';
var popups = '1';
var multiple_windows = '1';
var main_title = '<inp2:m_GetConfig var="Site_Name" escape="1"/>';
var tpl_changed = 0;
var base_url = '<inp2:m_BaseURL/>';
var $base_path = '<inp2:m_GetConst name="BASE_PATH"/>';
var img_path = '<inp2:m_TemplatesBase module="#MODULE#"/>/img/';
NumberFormatter.ThousandsSep = '<inp2:lang.current_Field name="ThousandSep" js_escape="1"/>';
NumberFormatter.DecimalSep = '<inp2:lang.current_Field name="DecimalPoint" js_escape="1"/>';
<inp2:m_if check="m_GetEquals" name="m_wid" value="" inverse="inverse">
window.name += '_<inp2:m_get name="m_wid"/>';
</inp2:m_if>
var $use_popups = <inp2:m_if check="adm_UsePopups">true<inp2:m_else/>false</inp2:m_if>;
var $use_toolbarlabels = <inp2:m_if check="adm_UseToolbarLabels">true<inp2:m_else/>false</inp2:m_if>;
</script>
</head>
<inp2:m_include t="incs/blocks"/>
<inp2:m_include t="incs/in-portal"/>
<inp2:m_if check="m_ParamEquals" name="nobody" value="yes" inverse="inverse">
<body <inp2:m_param name="body_properties"/>>
</inp2:m_if>
<inp2:m_if check="m_ParamEquals" name="noform" value="yes" inverse="inverse">
<inp2:m_RenderElement name="kernel_form"/>
</inp2:m_if>
\ No newline at end of file
Property changes on: branches/RC/core/admin_templates/incs/header.tpl
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.5.2.1
\ No newline at end of property
+1.5.2.2
\ No newline at end of property
Index: branches/RC/core/install/upgrades.sql
===================================================================
--- branches/RC/core/install/upgrades.sql (revision 10004)
+++ branches/RC/core/install/upgrades.sql (revision 10005)
@@ -1,165 +1,169 @@
# ===== v 4.0.1 =====
ALTER TABLE EmailLog ADD EventParams TEXT NOT NULL;
INSERT INTO ConfigurationAdmin VALUES ('MailFunctionHeaderSeparator', 'la_Text_smtp_server', 'la_config_MailFunctionHeaderSeparator', 'radio', NULL, '1=la_Linux,2=la_Windows', 30.08, 0, 0);
INSERT INTO ConfigurationValues VALUES (0, 'MailFunctionHeaderSeparator', 1, 'In-Portal', 'in-portal:configure_general');
ALTER TABLE PersistantSessionData DROP PRIMARY KEY ;
ALTER TABLE PersistantSessionData ADD INDEX ( `PortalUserId` ) ;
# ===== v 4.1.0 =====
ALTER TABLE EmailMessage ADD ReplacementTags TEXT AFTER Template;
ALTER TABLE Phrase
CHANGE Translation Translation TEXT NOT NULL,
CHANGE Module Module VARCHAR(30) NOT NULL DEFAULT 'In-Portal';
ALTER TABLE Category
CHANGE Description Description TEXT,
CHANGE l1_Description l1_Description TEXT,
CHANGE l2_Description l2_Description TEXT,
CHANGE l3_Description l3_Description TEXT,
CHANGE l4_Description l4_Description TEXT,
CHANGE l5_Description l5_Description TEXT,
CHANGE CachedNavbar CachedNavbar text,
CHANGE l1_CachedNavbar l1_CachedNavbar text,
CHANGE l2_CachedNavbar l2_CachedNavbar text,
CHANGE l3_CachedNavbar l3_CachedNavbar text,
CHANGE l4_CachedNavbar l4_CachedNavbar text,
CHANGE l5_CachedNavbar l5_CachedNavbar text,
CHANGE ParentPath ParentPath TEXT NULL DEFAULT NULL,
CHANGE NamedParentPath NamedParentPath TEXT NULL DEFAULT NULL;
ALTER TABLE ConfigurationAdmin CHANGE ValueList ValueList TEXT;
ALTER TABLE EmailQueue
CHANGE `Subject` `Subject` TEXT,
CHANGE toaddr toaddr TEXT,
CHANGE fromaddr fromaddr TEXT;
ALTER TABLE Category DROP Pop;
ALTER TABLE PortalUser
CHANGE CreatedOn CreatedOn INT DEFAULT NULL,
CHANGE dob dob INT(11) NULL DEFAULT NULL,
CHANGE PassResetTime PassResetTime INT(11) UNSIGNED NULL DEFAULT NULL,
CHANGE PwRequestTime PwRequestTime INT(11) UNSIGNED NULL DEFAULT NULL,
CHANGE `Password` `Password` VARCHAR(255) NULL DEFAULT 'd41d8cd98f00b204e9800998ecf8427e';
ALTER TABLE Modules
CHANGE BuildDate BuildDate INT UNSIGNED NULL DEFAULT NULL,
CHANGE Version Version VARCHAR(10) NOT NULL DEFAULT '0.0.0',
CHANGE `Var` `Var` VARCHAR(100) NOT NULL DEFAULT '';
ALTER TABLE Language
CHANGE Enabled Enabled INT(11) NOT NULL DEFAULT '1',
CHANGE InputDateFormat InputDateFormat VARCHAR(50) NOT NULL DEFAULT 'm/d/Y',
CHANGE InputTimeFormat InputTimeFormat VARCHAR(50) NOT NULL DEFAULT 'g:i:s A',
CHANGE DecimalPoint DecimalPoint VARCHAR(10) NOT NULL DEFAULT '',
CHANGE ThousandSep ThousandSep VARCHAR(10) NOT NULL DEFAULT '';
ALTER TABLE Events CHANGE FromUserId FromUserId INT(11) NOT NULL DEFAULT '-1';
ALTER TABLE StdDestinations CHANGE DestAbbr2 DestAbbr2 CHAR(2) NULL DEFAULT NULL;
ALTER TABLE PermCache DROP DACL;
ALTER TABLE PortalGroup CHANGE CreatedOn CreatedOn INT UNSIGNED NULL DEFAULT NULL;
ALTER TABLE UserSession
CHANGE SessionKey SessionKey INT UNSIGNED NULL DEFAULT NULL ,
CHANGE CurrentTempKey CurrentTempKey INT UNSIGNED NULL DEFAULT NULL ,
CHANGE PrevTempKey PrevTempKey INT UNSIGNED NULL DEFAULT NULL ,
CHANGE LastAccessed LastAccessed INT UNSIGNED NOT NULL DEFAULT '0',
CHANGE PortalUserId PortalUserId INT(11) NOT NULL DEFAULT '-2',
CHANGE Language Language INT(11) NOT NULL DEFAULT '1',
CHANGE Theme Theme INT(11) NOT NULL DEFAULT '1';
CREATE TABLE Counters (
CounterId int(10) unsigned NOT NULL auto_increment,
Name varchar(100) NOT NULL default '',
CountQuery text,
CountValue text,
LastCounted int(10) unsigned default NULL,
LifeTime int(10) unsigned NOT NULL default '3600',
IsClone tinyint(3) unsigned NOT NULL default '0',
TablesAffected text,
PRIMARY KEY (CounterId),
UNIQUE KEY Name (Name)
);
CREATE TABLE Skins (
`SkinId` int(11) NOT NULL auto_increment,
`Name` varchar(255) default NULL,
`CSS` text,
`Logo` varchar(255) default NULL,
`Options` text,
`LastCompiled` int(11) NOT NULL default '0',
`IsPrimary` int(1) NOT NULL default '0',
PRIMARY KEY (`SkinId`)
);
INSERT INTO Skins VALUES (DEFAULT, 'Default', '/* General elements */\r\n\r\nhtml {\r\n height: 100%;\r\n}\r\n\r\nbody {\r\n font-family: verdana,arial,helvetica,sans-serif;\r\n font-size: 9pt;\r\n color: #000000;\r\n overflow-x: auto; overflow-y: auto;\r\n margin: 0px 0px 0px 0px;\r\n text-decoration: none;\r\n}\r\n\r\na {\r\n color: #006699;\r\n text-decoration: none;\r\n}\r\n\r\na:hover {\r\n color: #009ff0;\r\n text-decoration: none;\r\n}\r\n\r\nform {\r\n display: inline;\r\n}\r\n\r\nimg { border: 0px; }\r\n\r\nbody.height-100 {\r\n height: 100%;\r\n}\r\n\r\nbody.regular-body {\r\n margin: 0px 10px 5px 10px;\r\n color: #000000;\r\n background-color: @@SectionBgColor@@;\r\n}\r\n\r\nbody.edit-popup {\r\n margin: 0px 0px 0px 0px;\r\n}\r\n\r\ntable.collapsed {\r\n border-collapse: collapse;\r\n}\r\n\r\n.bordered, table.bordered, .bordered-no-bottom {\r\n border: 1px solid #000000;\r\n border-collapse: collapse;\r\n}\r\n\r\n.bordered-no-bottom {\r\n border-bottom: none;\r\n}\r\n\r\n.login-table td {\r\n padding: 1px;\r\n}\r\n\r\n.disabled {\r\n background-color: #ebebeb;\r\n}\r\n\r\n/* Head frame */\r\n.head-table tr td {\r\n background-color: @@HeadBgColor@@;\r\n color: @@HeadColor@@\r\n}\r\n\r\ntd.kx-block-header, .head-table tr td.kx-block-header{\r\n color: @@HeadBarColor@@;\r\n background-color: @@HeadBarBgColor@@;\r\n padding-left: 7px;\r\n padding-right: 7px;\r\n}\r\n\r\na.kx-header-link {\r\n text-decoration: underline;\r\n color: #FFFFFF;\r\n}\r\n\r\na.kx-header-link:hover {\r\n color: #FFCB05;\r\n text-decoration: none;\r\n}\r\n\r\n.kx-secondary-foreground {\r\n color: @@HeadBarColor@@;\r\n background-color: @@HeadBarBgColor@@;\r\n}\r\n\r\n.kx-login-button {\r\n background-color: #2D79D6;\r\n color: #FFFFFF;\r\n}\r\n\r\n/* General form button (yellow) */\r\n.button {\r\n font-size: 12px;\r\n font-weight: normal;\r\n color: #000000;\r\n background: url(@@base_url@@/proj-base/admin_templates/img/button_back.gif) #f9eeae repeat-x;\r\n text-decoration: none;\r\n}\r\n\r\n/* Disabled (grayed-out) form button */\r\n.button-disabled {\r\n font-size: 12px;\r\n font-weight: normal;\r\n color: #676767;\r\n background: url(@@base_url@@/proj-base/admin_templates/img/button_back_disabled.gif) #f9eeae repeat-x;\r\n text-decoration: none;\r\n}\r\n\r\n/* Tabs bar */\r\n\r\n.tab, .tab-active {\r\n background-color: #F0F1EB;\r\n padding: 3px 7px 2px 7px;\r\n border-top: 1px solid black;\r\n border-left: 1px solid black;\r\n border-right: 1px solid black;\r\n}\r\n\r\n.tab-active {\r\n background-color: #2D79D6;\r\n border-bottom: 1px solid #2D79D6;\r\n}\r\n\r\n.tab a {\r\n color: #00659C;\r\n font-weight: bold;\r\n}\r\n\r\n.tab-active a {\r\n color: #fff;\r\n font-weight: bold;\r\n}\r\n\r\n\r\n/* Toolbar */\r\n\r\n.toolbar {\r\n font-size: 8pt;\r\n border: 1px solid #000000;\r\n border-width: 0px 1px 1px 1px;\r\n background-color: @@ToolbarBgColor@@;\r\n border-collapse: collapse;\r\n}\r\n\r\n.toolbar td {\r\n height: 100%;\r\n}\r\n\r\n.toolbar-button, .toolbar-button-disabled, .toolbar-button-over {\r\n float: left;\r\n text-align: center;\r\n font-size: 8pt;\r\n padding: 5px 5px 5px 5px;\r\n vertical-align: middle;\r\n color: #006F99;\r\n}\r\n\r\n.toolbar-button-over {\r\n color: #000;\r\n}\r\n\r\n.toolbar-button-disabled {\r\n color: #444;\r\n}\r\n\r\n/* Scrollable Grids */\r\n\r\n\r\n/* Main Grid class */\r\n.grid-scrollable {\r\n padding: 0px;\r\n border: 1px solid black !important;\r\n border-top: none !important;\r\n}\r\n\r\n/* Div generated by js, which contains all the scrollable grid elements, affects the style of scrollable area without data (if there are too few rows) */\r\n.grid-container {\r\n background-color: #fff;\r\n}\r\n\r\n.grid-container table {\r\n border-collapse: collapse;\r\n}\r\n\r\n/* Inner div generated in each data-cell */\r\n.grid-cell-div {\r\n overflow: hidden;\r\n height: auto;\r\n}\r\n\r\n/* Main row definition */\r\n.grid-data-row td, .grid-data-row-selected td, .grid-data-row-even-selected td, .grid-data-row-mouseover td, .table-color1, .table-color2 {\r\n font-weight: normal;\r\n color: @@OddColor@@;\r\n background-color: @@OddBgColor@@;\r\n padding: 3px 5px 3px 5px;\r\n height: 30px;\r\n overflow: hidden;\r\n /* border-right: 1px solid black; */\r\n}\r\n.grid-data-row-even td, .table-color2 {\r\n background-color: @@EvenBgColor@@;\r\n color: @@EvenColor@@;\r\n}\r\n.grid-data-row td a, .grid-data-row-selected td a, .grid-data-row-mouseover td a {\r\n text-decoration: underline;\r\n}\r\n\r\n/* mouse-over rows */\r\n.grid-data-row-mouseover td {\r\n background: #FFFDF4;\r\n}\r\n\r\n/* Selected row, applies to both checkbox and data areas */\r\n.grid-data-row-selected td {\r\n background: #FEF2D6;\r\n}\r\n\r\n.grid-data-row-even-selected td {\r\n background: #FFF7E0;\r\n}\r\n\r\n/* General header cell definition */\r\n.grid-header-row td {\r\n font-weight: bold;\r\n background-color: @@ColumnTitlesBgColor@@;\r\n text-decoration: none;\r\n padding: 3px 5px 3px 5px;\r\n color: @@ColumnTitlesColor@@;\r\n border-right: none;\r\n text-align: left;\r\n vertical-align: middle !important;\r\n white-space: nowrap;\r\n /* border-right: 1px solid black; */\r\n}\r\n\r\n/* Filters row */\r\ntr.grid-header-row-0 td {\r\n background-color: @@FiltersBgColor@@;\r\n border-bottom: 1px solid black;\r\n}\r\n\r\n/* Grid Filters */\r\ntable.range-filter {\r\n width: 100%;\r\n}\r\n\r\n.range-filter td {\r\n padding: 0px 0px 2px 2px !important;\r\n border: none !important;\r\n font-size: 8pt !important;\r\n font-weight: normal !important;\r\n text-align: left;\r\n color: #000000 !important;\r\n}\r\n\r\ninput.filter, select.filter {\r\n margin-bottom: 0px;\r\n width: 85%;\r\n}\r\n\r\ninput.filter-active {\r\n background-color: #FFFF00;\r\n}\r\n\r\nselect.filter-active {\r\n background-color: #FFFF00;\r\n}\r\n\r\n/* Column titles row */\r\ntr.grid-header-row-1 td {\r\n height: 25px;\r\n font-weight: bold;\r\n background-color: @@ColumnTitlesBgColor@@;\r\n color: @@ColumnTitlesColor@@;\r\n}\r\n\r\ntr.grid-header-row-1 td a {\r\n color: @@ColumnTitlesColor@@;\r\n}\r\n\r\ntr.grid-header-row-1 td a:hover {\r\n color: #FFCC00;\r\n}\r\n\r\n\r\n.grid-footer-row td {\r\n background-color: #D7D7D7;\r\n font-weight: bold;\r\n border-right: none;\r\n padding: 3px 5px 3px 5px;\r\n}\r\n\r\ntd.grid-header-last-cell, td.grid-data-last-cell, td.grid-footer-last-cell {\r\n border-right: none !important;\r\n}\r\n\r\ntd.grid-data-col-0, td.grid-data-col-0 div {\r\n text-align: center;\r\n vertical-align: middle !important;\r\n}\r\n\r\ntr.grid-header-row-0 td.grid-header-col-0 {\r\n text-align: center;\r\n vertical-align: middle !important;\r\n}\r\n\r\ntr.grid-header-row-0 td.grid-header-col-0 div {\r\n display: table-cell;\r\n vertical-align: middle;\r\n}\r\n\r\n.grid-status-bar {\r\n border: 1px solid black;\r\n border-top: none;\r\n padding: 0px;\r\n width: 100%;\r\n border-collapse: collapse;\r\n height: 30px;\r\n}\r\n\r\n.grid-status-bar td {\r\n background-color: @@TitleBarBgColor@@;\r\n color: @@TitleBarColor@@;\r\n font-size: 11pt;\r\n font-weight: normal;\r\n padding: 2px 8px 2px 8px;\r\n}\r\n\r\n/* /Scrollable Grids */\r\n\r\n\r\n/* Forms */\r\ntable.edit-form {\r\n border: none;\r\n border-top-width: 0px;\r\n border-collapse: collapse;\r\n width: 100%;\r\n}\r\n\r\n.edit-form-odd, .edit-form-even {\r\n padding: 0px;\r\n}\r\n\r\n.subsectiontitle {\r\n font-size: 10pt;\r\n font-weight: bold;\r\n background-color: #4A92CE;\r\n color: #fff;\r\n height: 25px;\r\n border-top: 1px solid black;\r\n}\r\n\r\n.label-cell {\r\n background: #DEE7F6 url(@@base_url@@/proj-base/admin_templates/img/bgr_input_name_line.gif) no-repeat right bottom;\r\n font: 12px arial, sans-serif;\r\n padding: 4px 20px;\r\n width: 150px;\r\n}\r\n\r\n.control-mid {\r\n width: 13px;\r\n border-left: 1px solid #7A95C2;\r\n background: #fff url(@@base_url@@/proj-base/admin_templates/img/bgr_mid.gif) repeat-x left bottom;\r\n}\r\n\r\n.control-cell {\r\n font: 11px arial, sans-serif;\r\n padding: 4px 10px 5px 5px;\r\n background: #fff url(@@base_url@@/proj-base/admin_templates/img/bgr_input_line.gif) no-repeat left bottom;\r\n width: auto;\r\n vertical-align: middle;\r\n}\r\n\r\n.label-cell-filler {\r\n background: #DEE7F6 none;\r\n}\r\n.control-mid-filler {\r\n background: #fff none;\r\n border-left: 1px solid #7A95C2;\r\n}\r\n.control-cell-filler {\r\n background: #fff none;\r\n}\r\n\r\n\r\n.error-cell {\r\n background-color: #fff;\r\n color: red;\r\n}\r\n\r\n.form-warning {\r\n color: red;\r\n}\r\n\r\n.req-note {\r\n font-style: italic;\r\n color: #333;\r\n}\r\n\r\n#scroll_container table.tableborder {\r\n border-collapse: separate\r\n}\r\n\r\n\r\n/* Uploader */\r\n\r\n.uploader-main {\r\n position: absolute;\r\n display: none;\r\n z-index: 10;\r\n border: 1px solid #777;\r\n padding: 10px;\r\n width: 350px;\r\n height: 120px;\r\n overflow: hidden;\r\n background-color: #fff;\r\n}\r\n\r\n.uploader-percent {\r\n width: 100%;\r\n padding-top: 3px;\r\n text-align: center;\r\n position: relative;\r\n z-index: 20;\r\n float: left;\r\n font-weight: bold;\r\n}\r\n\r\n.uploader-left {\r\n width: 100%;\r\n border: 1px solid black;\r\n height: 20px;\r\n background: #fff url(@@base_url@@/core/admin_templates/img/progress_left.gif);\r\n}\r\n\r\n.uploader-done {\r\n width: 0%;\r\n background-color: green;\r\n height: 20px;\r\n background: #4A92CE url(@@base_url@@/core/admin_templates/img/progress_done.gif);\r\n}\r\n\r\n\r\n/* To be sorted */\r\n\r\n\r\n/* Section title, right to the big icon */\r\n.admintitle {\r\n font-size: 16pt;\r\n font-weight: bold;\r\n color: @@SectionColor@@;\r\n text-decoration: none;\r\n}\r\n\r\n/* Left sid of bluebar */\r\n.header_left_bg {\r\n background-color: @@TitleBarBgColor@@;\r\n background-image: none;\r\n padding-left: 5px;\r\n}\r\n\r\n/* Right side of bluebar */\r\n.tablenav, tablenav a {\r\n font-size: 11pt;\r\n font-weight: bold;\r\n color: @@TitleBarColor@@;\r\n\r\n text-decoration: none;\r\n background-color: @@TitleBarBgColor@@;\r\n background-image: none;\r\n}\r\n\r\n/* Section title in the bluebar * -- why ''link''? :S */\r\n.tablenav_link {\r\n font-size: 11pt;\r\n font-weight: bold;\r\n color: @@TitleBarColor@@;\r\n text-decoration: none;\r\n}\r\n\r\n/* Active page in top and bottom bluebars pagination */\r\n.current_page {\r\n font-size: 10pt;\r\n font-weight: bold;\r\n background-color: #fff;\r\n color: #2D79D6;\r\n padding: 3px 2px 3px 3px;\r\n}\r\n\r\n/* Other pages and arrows in pagination on blue */\r\n.nav_url {\r\n font-size: 10pt;\r\n font-weight: bold;\r\n color: #fff;\r\n padding: 3px 2px 3px 3px;\r\n}\r\n\r\n/* Tree */\r\n.tree-body {\r\n background-color: @@TreeBgColor@@;\r\n height: 100%\r\n}\r\n\r\n.tree_head.td, .tree_head, .tree_head:hover {\r\n font-weight: bold;\r\n font-size: 10px;\r\n color: #FFFFFF;\r\n font-family: Verdana, Arial;\r\n text-decoration: none;\r\n}\r\n\r\n.tree {\r\n padding: 0px;\r\n border: none;\r\n border-collapse: collapse;\r\n}\r\n\r\n.tree tr td {\r\n padding: 0px;\r\n margin: 0px;\r\n font-family: helvetica, arial, verdana,;\r\n font-size: 11px;\r\n white-space: nowrap;\r\n}\r\n\r\n.tree tr td a {\r\n font-size: 11px;\r\n color: @@TreeColor@@;\r\n font-family: Helvetica, Arial, Verdana;\r\n text-decoration: none;\r\n padding: 2px 0px 2px 2px;\r\n}\r\n\r\n.tree tr.highlighted td a {\r\n background-color: @@TreeHighBgColor@@;\r\n color: @@TreeHighColor@@;\r\n}\r\n\r\n.tree tr.highlighted td a:hover {\r\n color: #fff;\r\n}\r\n\r\n.tree tr td a:hover {\r\n color: #000000;\r\n}', 'just_logo.gif', 'a:20:{s:11:"HeadBgColor";a:2:{s:11:"Description";s:27:"Head frame background color";s:5:"Value";s:7:"#1961B8";}s:9:"HeadColor";a:2:{s:11:"Description";s:21:"Head frame text color";s:5:"Value";s:7:"#CCFF00";}s:14:"SectionBgColor";a:2:{s:11:"Description";s:28:"Section bar background color";s:5:"Value";s:7:"#FFFFFF";}s:12:"SectionColor";a:2:{s:11:"Description";s:22:"Section bar text color";s:5:"Value";s:7:"#2D79D6";}s:12:"HeadBarColor";a:1:{s:5:"Value";s:7:"#FFFFFF";}s:14:"HeadBarBgColor";a:1:{s:5:"Value";s:7:"#1961B8";}s:13:"TitleBarColor";a:1:{s:5:"Value";s:7:"#FFFFFF";}s:15:"TitleBarBgColor";a:1:{s:5:"Value";s:7:"#2D79D6";}s:14:"ToolbarBgColor";a:1:{s:5:"Value";s:7:"#F0F1EB";}s:14:"FiltersBgColor";a:1:{s:5:"Value";s:7:"#D7D7D7";}s:17:"ColumnTitlesColor";a:1:{s:5:"Value";s:7:"#FFFFFF";}s:19:"ColumnTitlesBgColor";a:1:{s:5:"Value";s:7:"#999999";}s:8:"OddColor";a:1:{s:5:"Value";s:7:"#000000";}s:10:"OddBgColor";a:1:{s:5:"Value";s:7:"#F6F6F6";}s:9:"EvenColor";a:1:{s:5:"Value";s:7:"#000000";}s:11:"EvenBgColor";a:1:{s:5:"Value";s:7:"#EBEBEB";}s:9:"TreeColor";a:1:{s:5:"Value";s:7:"#006F99";}s:11:"TreeBgColor";a:1:{s:5:"Value";s:7:"#FFFFFF";}s:13:"TreeHighColor";a:1:{s:5:"Value";s:7:"#FFFFFF";}s:15:"TreeHighBgColor";a:1:{s:5:"Value";s:7:"#4A92CE";}}', 1178706881, 1);
INSERT INTO Permissions VALUES (0, 'in-portal:skins.view', 11, 1, 1, 0), (0, 'in-portal:skins.add', 11, 1, 1, 0), (0, 'in-portal:skins.edit', 11, 1, 1, 0), (0, 'in-portal:skins.delete', 11, 1, 1, 0);
# ===== v 4.1.1 =====
DROP TABLE EmailQueue;
CREATE TABLE EmailQueue (
EmailQueueId int(10) unsigned NOT NULL auto_increment,
ToEmail varchar(255) NOT NULL default '',
`Subject` varchar(255) NOT NULL default '',
MessageHeaders text,
MessageBody longtext,
Queued int(10) unsigned NOT NULL default '0',
SendRetries int(10) unsigned NOT NULL default '0',
LastSendRetry int(10) unsigned NOT NULL default '0',
PRIMARY KEY (EmailQueueId),
KEY LastSendRetry (LastSendRetry),
KEY SendRetries (SendRetries)
);
ALTER TABLE Events ADD ReplacementTags TEXT AFTER Event;
# ===== v 4.2.0 =====
ALTER TABLE CustomField ADD MultiLingual TINYINT UNSIGNED NOT NULL DEFAULT '1' AFTER FieldLabel;
ALTER TABLE Category
ADD TreeLeft BIGINT NOT NULL AFTER ParentPath,
ADD TreeRight BIGINT NOT NULL AFTER TreeLeft;
ALTER TABLE Category ADD INDEX (TreeLeft);
ALTER TABLE Category ADD INDEX (TreeRight);
INSERT INTO ConfigurationValues VALUES (DEFAULT, 'CategoriesRebuildSerial', '0', 'In-Portal', '');
UPDATE ConfigurationAdmin SET `element_type` = 'textarea' WHERE `VariableName` IN ('Category_MetaKey', 'Category_MetaDesc');
ALTER TABLE PortalUser
CHANGE FirstName FirstName VARCHAR(255) NOT NULL DEFAULT '',
CHANGE LastName LastName VARCHAR(255) NOT NULL DEFAULT '';
# ===== v 4.2.1 =====
INSERT INTO ConfigurationAdmin VALUES ('UseSmallHeader', 'la_Text_Website', 'la_config_UseSmallHeader', 'checkbox', '', '', 10.21, 0, 0);
INSERT INTO ConfigurationValues VALUES (DEFAULT, 'UseSmallHeader', '0', 'In-Portal', 'in-portal:configure_general');
INSERT INTO ConfigurationAdmin VALUES ('User_Default_Registration_Country', 'la_Text_General', 'la_config_DefaultRegistrationCountry', 'select', NULL , '=+,<SQL>SELECT DestName AS OptionName, DestId AS OptionValue FROM <PREFIX>StdDestinations WHERE DestParentId IS NULL Order BY OptionName</SQL>', 10.111, 0, 0);
INSERT INTO ConfigurationValues VALUES (DEFAULT, 'User_Default_Registration_Country', '', 'In-Portal:Users', 'in-portal:configure_users');
ALTER TABLE Category ADD SymLinkCategoryId INT UNSIGNED NULL DEFAULT NULL AFTER `Type`, ADD INDEX (SymLinkCategoryId);
ALTER TABLE ConfigurationValues CHANGE VariableValue VariableValue TEXT NULL DEFAULT NULL;
ALTER TABLE Language
ADD AdminInterfaceLang TINYINT UNSIGNED NOT NULL AFTER PrimaryLang,
ADD Priority INT NOT NULL AFTER AdminInterfaceLang;
UPDATE Language SET AdminInterfaceLang = 1 WHERE PrimaryLang = 1;
DELETE FROM PersistantSessionData WHERE VariableName = 'lang_columns_.';
ALTER TABLE SessionData CHANGE VariableValue VariableValue longtext NOT NULL;
REPLACE INTO ConfigurationAdmin VALUES ('CSVExportDelimiter', 'la_Text_CSV_Export', 'la_config_CSVExportDelimiter', 'select', NULL, '0=la_Tab,1=la_Comma,2=la_Semicolon,3=la_Space,4=la_Colon', 40.1, 0, 1);
REPLACE INTO ConfigurationAdmin VALUES ('CSVExportEnclosure', 'la_Text_CSV_Export', 'la_config_CSVExportEnclosure', 'radio', NULL, '0=la_Doublequotes,1=la_Quotes', 40.2, 0, 1);
REPLACE INTO ConfigurationAdmin VALUES ('CSVExportSeparator', 'la_Text_CSV_Export', 'la_config_CSVExportSeparator', 'radio', NULL, '0=la_Linux,1=la_Windows', 40.3, 0, 1);
REPLACE INTO ConfigurationAdmin VALUES ('CSVExportEncoding', 'la_Text_CSV_Export', 'la_config_CSVExportEncoding', 'radio', NULL, '0=la_Unicode,1=la_Regular', 40.4, 0, 1);
REPLACE INTO ConfigurationValues VALUES (DEFAULT, 'CSVExportDelimiter', '0', 'In-Portal', 'in-portal:configure_general');
REPLACE INTO ConfigurationValues VALUES (DEFAULT, 'CSVExportEnclosure', '0', 'In-Portal', 'in-portal:configure_general');
REPLACE INTO ConfigurationValues VALUES (DEFAULT, 'CSVExportSeparator', '0', 'In-Portal', 'in-portal:configure_general');
REPLACE INTO ConfigurationValues VALUES (DEFAULT, 'CSVExportEncoding', '0', 'In-Portal', 'in-portal:configure_general');
# ===== v 4.2.2 =====
INSERT INTO ConfigurationAdmin VALUES ('UseColumnFreezer', 'la_Text_Website', 'la_config_UseColumnFreezer', 'checkbox', '', '', 10.22, 0, 0);
INSERT INTO ConfigurationValues VALUES (DEFAULT, 'UseColumnFreezer', '0', 'In-Portal', 'in-portal:configure_general');
INSERT INTO ConfigurationAdmin VALUES ('TrimRequiredFields', 'la_Text_Website', 'la_config_TrimRequiredFields', 'checkbox', '', '', 10.23, 0, 0);
INSERT INTO ConfigurationValues VALUES (DEFAULT, 'TrimRequiredFields', '0', 'In-Portal', 'in-portal:configure_general');
INSERT INTO ConfigurationAdmin VALUES ('MenuFrameWidth', 'la_title_General', 'la_prompt_MenuFrameWidth', 'text', NULL, NULL, '11', '0', '0');
INSERT INTO ConfigurationValues VALUES (DEFAULT, 'MenuFrameWidth', 200, 'Proj-Base', 'in-portal:configure_general');
INSERT INTO ConfigurationAdmin VALUES ('DefaultSettingsUserId', 'la_title_General', 'la_prompt_DefaultUserId', 'text', NULL, NULL, '12', '0', '0');
-INSERT INTO ConfigurationValues VALUES (DEFAULT, 'DefaultSettingsUserId', -1, 'Proj-Base', 'in-portal:configure_general');
\ No newline at end of file
+INSERT INTO ConfigurationValues VALUES (DEFAULT, 'DefaultSettingsUserId', -1, 'Proj-Base', 'in-portal:configure_general');
+
+INSERT INTO ConfigurationAdmin VALUES ('KeepSessionOnBrowserClose', 'la_title_General', 'la_prompt_KeepSessionOnBrowserClose', 'checkbox', NULL, NULL, '13', '0', '0');
+INSERT INTO ConfigurationValues VALUES (DEFAULT, 'KeepSessionOnBrowserClose', 0, 'Proj-Base', 'in-portal:configure_general');
+
Property changes on: branches/RC/core/install/upgrades.sql
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.19.2.17
\ No newline at end of property
+1.19.2.18
\ No newline at end of property

Event Timeline