Page MenuHomeIn-Portal Phabricator

in-portal
No OneTemporary

File Metadata

Created
Fri, Feb 21, 11:59 PM

in-portal

This file is larger than 256 KB, so syntax highlighting was skipped.
Index: branches/5.2.x/admin/system_presets/simple/session_logs_session-log.php
===================================================================
--- branches/5.2.x/admin/system_presets/simple/session_logs_session-log.php (revision 16796)
+++ branches/5.2.x/admin/system_presets/simple/session_logs_session-log.php (revision 16797)
@@ -1,51 +1,51 @@
<?php
defined('FULL_PATH') or die('restricted access!');
// section removal
$remove_sections = Array (
// 'in-portal:session_logs',
);
// section in debug mode
$debug_only_sections = Array (
'in-portal:session_logs',
);
// toolbar buttons
$remove_buttons = Array (
// list of sessions
// 'session_log_list' => Array ('delete', 'view'),
);
// fields to hide
$hidden_fields = Array (
- /*'SessionLogId', 'PortalUserId', 'SessionId', 'Status', 'SessionStart', 'SessionEnd', 'IP', 'AffectedItems',*/
+ /*'SessionLogId', 'PortalUserId', 'SessionKey', 'Status', 'SessionStart', 'SessionEnd', 'IP', 'AffectedItems',*/
);
// virtual fields to hide
$virtual_hidden_fields = Array (
/*'Duration', */
);
// fields to make required
$required_fields = Array (
- /*'SessionLogId', 'PortalUserId', 'SessionId', 'Status', 'SessionStart', 'SessionEnd', 'IP', 'AffectedItems',*/
+ /*'SessionLogId', 'PortalUserId', 'SessionKey', 'Status', 'SessionStart', 'SessionEnd', 'IP', 'AffectedItems',*/
);
// virtual fields to make required
$virtual_required_fields = Array (
/*'Duration', */
);
// tabs during editing
$hide_edit_tabs = Array (
);
// hide columns in grids
$hide_columns = Array (
// currently not in user
- 'Default' => Array (/* 'SessionLogId', 'PortalUserId', 'SessionId', 'Status', 'SessionStart', 'SessionEnd'
+ 'Default' => Array (/* 'SessionLogId', 'PortalUserId', 'SessionKey', 'Status', 'SessionStart', 'SessionEnd'
, 'IP', 'Duration', 'AffectedItems', */),
- );
\ No newline at end of file
+ );
Index: branches/5.2.x/core/kernel/session/inp_session_storage.php
===================================================================
--- branches/5.2.x/core/kernel/session/inp_session_storage.php (revision 16796)
+++ branches/5.2.x/core/kernel/session/inp_session_storage.php (revision 16797)
@@ -1,97 +1,98 @@
<?php
/**
* @version $Id$
* @package In-Portal
* @copyright Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license GNU/GPL
* In-Portal is Open Source software.
* This means that this software may have been modified pursuant
* the GNU General Public License, and as distributed it includes
* or is derivative of works licensed under the GNU General Public License
* or other free or open source software licenses.
* See http://www.in-portal.org/license for copyright notices and details.
*/
defined('FULL_PATH') or die('restricted access!');
class InpSessionStorage extends SessionStorage {
public function Init($prefix, $special)
{
parent::Init($prefix, $special);
$this->TableName = TABLE_PREFIX.'UserSessions';
$this->SessionDataTable = TABLE_PREFIX.'UserSessionData';
- $this->IDField = 'SessionKey';
+ $this->IDField = 'SessionId';
+ $this->sessionKeyField = 'SessionKey';
$this->TimestampField = 'LastAccessed';
$this->DataValueField = 'VariableValue';
$this->DataVarField = 'VariableName';
}
function LocateSession($sid)
{
$res = parent::LocateSession($sid);
if ($res) {
$this->Expiration += $this->SessionTimeout;
}
return $res;
}
function UpdateSession($timeout = 0)
{
$time = adodb_mktime();
// Update LastAccessed only if it's newer than 1/10 of session timeout - perfomance optimization to eliminate needless updates on every click
// if ($time - $this->DirectVars['LastAccessed'] > $this->SessionTimeout/10) {
$this->SetField($this->TimestampField, $time + $this->SessionTimeout);
// }
}
function GetSessionDefaults()
{
$fields_hash = Array (
'PortalUserId' => $this->Application->isAdmin ? 0 : USER_GUEST,
'Language' => $this->Application->GetDefaultLanguageId(true),
'Theme' => $this->Application->GetDefaultThemeId(),
'GroupId' => $this->Application->ConfigValue('User_GuestGroup'),
'GroupList' => $this->Application->ConfigValue('User_GuestGroup'),
'IpAddress' => $this->Application->getClientIp(),
);
if ( !$this->Application->isAdmin ) {
// Guest users on Front-End belongs to Everyone group too
$fields_hash['GroupList'] .= ',' . $this->Application->ConfigValue('User_LoggedInGroup');
}
return array_merge($fields_hash, parent::GetSessionDefaults());
}
function GetExpiredSIDs()
{
$query = ' SELECT '.$this->IDField.' FROM '.$this->TableName.' WHERE '.$this->TimestampField.' < '.(adodb_mktime());
$ret = $this->Conn->GetCol($query);
if($ret) {
$this->DeleteEditTables();
}
return $ret;
}
function DeleteEditTables()
{
$tables = $this->Conn->GetCol('SHOW TABLES');
$mask_edit_table = '/'.TABLE_PREFIX.'ses_(.*)_edit_(.*)/';
$mask_search_table = '/'.TABLE_PREFIX.'ses_(.*?)_(.*)/';
$sql='SELECT COUNT(*) FROM '.$this->TableName.' WHERE '.$this->IDField.' = \'%s\'';
foreach($tables as $table)
{
if( preg_match($mask_edit_table,$table,$rets) || preg_match($mask_search_table,$table,$rets) )
{
$sid = preg_replace('/(.*)_(.*)/', '\\1', $rets[1]); // remove popup's wid from sid
$is_alive = $this->Conn->GetOne( sprintf($sql,$sid) );
if(!$is_alive) $this->Conn->Query('DROP TABLE IF EXISTS '.$table);
}
}
}
-}
\ No newline at end of file
+}
Index: branches/5.2.x/core/kernel/session/session.php
===================================================================
--- branches/5.2.x/core/kernel/session/session.php (revision 16796)
+++ branches/5.2.x/core/kernel/session/session.php (revision 16797)
@@ -1,1135 +1,1153 @@
<?php
/**
* @version $Id$
* @package In-Portal
* @copyright Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license GNU/GPL
* In-Portal is Open Source software.
* This means that this software may have been modified pursuant
* the GNU General Public License, and as distributed it includes
* or is derivative of works licensed under the GNU General Public License
* or other free or open source software licenses.
* See http://www.in-portal.org/license for copyright notices and details.
*/
defined('FULL_PATH') or die('restricted access!');
/*
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:
- Session::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)
- Session::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.
- Session::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
- Session::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(Session::smAUTO); //Session::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>";
*/
class Session extends kBase {
const smAUTO = 1;
const smCOOKIES_ONLY = 2;
const smGET_ONLY = 3;
const smCOOKIES_AND_GET = 4;
+ const PURPOSE_TRANSPORT = 1;
+ const PURPOSE_STORAGE = 2;
+ const PURPOSE_REFERENCE = 3;
+
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;
var $CachedSID;
var $SessionSet = false;
/**
* Session ID is used from GET
*
* @var bool
*/
var $_fromGet = false;
/**
* Enter description here...
*
* @var SessionStorage
* @access protected
*/
protected $Storage;
var $CachedNeedQueryString = null;
/**
* Session Data array
*
* @var Params
*/
var $Data;
/**
* Names of optional session keys with their optional values (which does not need to be always stored)
*
* @var Array
*/
var $OptionalData = Array ();
/**
* Session expiration mark
*
* @var bool
*/
var $expired = false;
/**
* Creates session
*
* @param int $mode
* @access public
*/
public function __construct($mode = self::smAUTO)
{
parent::__construct();
$this->SetMode($mode);
}
function SetMode($mode)
{
$this->Mode = $mode;
$this->CachedNeedQueryString = null;
$this->CachedSID = null;
}
function SetCookiePath($path)
{
$this->CookiePath = str_replace(' ', '%20', $path);
}
/**
* Setting cookie domain. Set false for local domains, because they don't contain dots in their names.
*
* @param string $domain
*/
function SetCookieDomain($domain)
{
// 1. localhost or other like it without "." in domain name
if (!substr_count($domain, '.')) {
// don't use cookie domain at all
$this->CookieDomain = false;
return ;
}
// 2. match using predefined cookie domains from configuration
$cookie_domains = $this->Application->ConfigValue('SessionCookieDomains');
if ($cookie_domains) {
$cookie_domains = array_map('trim', explode("\n", $cookie_domains));
foreach ($cookie_domains as $cookie_domain) {
if (ltrim($cookie_domain, '.') == $domain) {
$this->CookieDomain = $cookie_domain; // as defined in configuration
return ;
}
}
}
// 3. only will execute, when none of domains were matched at previous step
$this->CookieDomain = $this->_autoGuessDomain($domain);
}
/**
* Auto-guess cookie domain based on $_SERVER['HTTP_HOST']
*
* @param $domain
* @return string
*/
function _autoGuessDomain($domain)
{
static $cache = Array ();
if (!array_key_exists($domain, $cache)) {
switch ( substr_count($domain, '.') ) {
case 2:
// 3rd level domain (3 parts)
$cache[$domain] = substr($domain, strpos($domain, '.')); // with leading "."
break;
case 1:
// 2rd level domain (2 parts)
$cache[$domain] = '.' . $domain; // with leading "."
break;
default:
// more then 3rd level
$cache[$domain] = ltrim($domain, '.'); // without leading "."
break;
}
}
return $cache[$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->setSession($this);
}
public function Init($prefix, $special)
{
parent::Init($prefix, $special);
if ( php_sapi_name() == 'cli' ) {
$this->SetMode(self::smGET_ONLY);
}
$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 ($this->Application->isAdmin) {
// 1. Front-End session may not be created (SID is present, but no data in database).
// Check expiration LATER from kApplication::Init, because template, used in session
// expiration redirect should be retrieved from mod-rewrite url first.
// 2. Admin sessions are always created, so case when SID is present,
// but session in database isn't is 100% session expired. Check expiration
// HERE because Session::SetSession will create missing session in database
// and when Session::ValidateExpired will be called later from kApplication::Init
// it won't consider such session as expired !!!
$this->ValidateExpired();
}
if ($check) {
$this->SID = $this->GetPassedSIDValue();
$this->Refresh();
$this->LoadData();
}
else {
$this->SetSession();
}
if (!is_null($this->OriginalMode)) $this->SetMode($this->OriginalMode);
}
function ValidateExpired()
{
if (defined('IS_INSTALL') && IS_INSTALL) {
return ;
}
// $this->DeleteExpired(); // called from u:OnDeleteExpiredSessions scheduled task now
if ($this->expired || ($this->CachedSID && !$this->_fromGet && !$this->SessionSet)) {
$this->RemoveSessionCookie();
// true was here to force new session creation, but I (kostja) used
// RemoveCookie a line above, to avoid redirect loop with expired sid
// not being removed setSession with true was used before, to set NEW
// session cookie
$this->SetSession();
// case #1: I've OR other site visitor expired my session
// case #2: I have no session in database, but SID is present
$this->expired = false;
$this->Application->HandleEvent(new kEvent('u:OnSessionExpire'));
}
}
/**
* Helper method for detecting cookie availability
*
* @return bool
*/
function _checkCookieReferer()
{
// removing /admin for compatability with in-portal (in-link/admin/add_link.php)
$path = preg_replace('/admin[\/]{0,1}$/', '', $this->CookiePath);
$reg = '#^'.preg_quote(PROTOCOL.ltrim($this->CookieDomain, '.').$path).'#';
return preg_match($reg, getArrayValue($_SERVER, 'HTTP_REFERER') );
}
function CheckIfCookiesAreOn()
{
if ( $this->Mode == self::smGET_ONLY ) {
//we don't need to bother checking if we would not use it
$this->CookiesEnabled = false;
return false;
}
/** @var kHTTPQuery $http_query */
$http_query = $this->Application->recallObject('HTTPQuery');
$cookies_on = array_key_exists('cookies_on', $http_query->Cookie); // not good here
$get_sid = getArrayValue($http_query->Get, $this->GETName);
if ( ($this->Application->HttpQuery->IsHTTPSRedirect() && $get_sid) || $this->getFlashSID() ) { // Redirect from http to https on different domain OR flash uploader
$this->OriginalMode = $this->Mode;
$this->SetMode(self::smGET_ONLY);
}
if ( !$cookies_on || $this->Application->HttpQuery->IsHTTPSRedirect() || $this->getFlashSID() ) {
//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->_checkCookieReferer() && !$this->Application->GetVar('admin') && !$this->Application->HttpQuery->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)
{
if (isset($expires) && $expires < adodb_mktime()) {
unset($this->Application->HttpQuery->Cookie[$name]);
}
else {
$this->Application->HttpQuery->Cookie[$name] = $value;
}
$old_style_domains = Array (
// domain like in pre 5.1.0 versions
'.' . SERVER_NAME,
// auto-guessed domain (when user specified other domain in configuration variable)
$this->_autoGuessDomain(SERVER_NAME)
);
foreach ($old_style_domains as $old_style_domain) {
if ($this->CookieDomain != $old_style_domain) {
// new style cookie domain -> delete old style cookie to prevent infinite redirect
setcookie($name, $value, adodb_mktime() - 3600, $this->CookiePath, $old_style_domain, $this->CookieSecure, true);
}
}
setcookie($name, $value, $expires, $this->CookiePath, $this->CookieDomain, $this->CookieSecure, true);
}
function Check()
{
// don't check referer here, because it doesn't provide any security option and can be easily falsified
$sid = $this->GetPassedSIDValue();
if (empty($sid)) {
return false;
}
//try to load session by sid, if everything is fine
$result = $this->LoadSession($sid);
$this->SessionSet = $result; // fake front-end session will given "false" here
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()) {
// when expired session is loaded, then SID is
// not assigned, but used in Destroy method
$this->SID = $sid;
$this->Destroy();
$this->expired = true;
// when Destory methods calls SetSession inside and new session get created
return $this->SessionSet;
}
// Otherwise it's ok
return true;
}
else {
// fake or deleted due to expiration SID
if (!$this->_fromGet) {
$this->expired = true;
}
return false;
}
}
function getFlashSID()
{
/** @var kHTTPQuery $http_query */
$http_query = $this->Application->recallObject('HTTPQuery');
return getArrayValue($http_query->Post, 'flashsid');
}
function GetPassedSIDValue($use_cache = 1)
{
if (!empty($this->CachedSID) && $use_cache) {
return $this->CachedSID;
}
// flash sid overrides regular sid
$get_sid = $this->getFlashSID();
if (!$get_sid) {
/** @var kHTTPQuery $http_query */
$http_query = $this->Application->recallObject('HTTPQuery');
$get_sid = getArrayValue($http_query->Get, $this->GETName);
}
$sid_from_get = $get_sid ? true : false;
if ($this->Application->GetVar('admin') == 1 && $get_sid) {
$sid = $get_sid;
}
else {
switch ($this->Mode) {
case self::smAUTO:
//Cookies has the priority - we ignore everything else
$sid = $this->CookiesEnabled ? $this->GetSessionCookie() : $get_sid;
if ($this->CookiesEnabled) {
$sid_from_get = false;
}
break;
case self::smCOOKIES_ONLY:
$sid = $this->GetSessionCookie();
break;
case self::smGET_ONLY:
$sid = $get_sid;
break;
case self::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 = '';
$sid_from_get = false;
}
break;
}
}
$this->CachedSID = $sid;
$this->_fromGet = $sid_from_get;
return $this->CachedSID;
}
/**
* Returns session id
*
- * @return int
- * @access public
+ * @param integer $purpose Purpose.
+ *
+ * @return integer
+ * @throws RuntimeException When unknown purpose is given.
*/
- function GetID()
+ public function GetID($purpose = self::PURPOSE_TRANSPORT)
{
- return $this->SID;
+ if ( $purpose === self::PURPOSE_TRANSPORT ) {
+ return $this->SID;
+ }
+
+ if ( $purpose === self::PURPOSE_STORAGE ) {
+ return $this->Storage->createSignatureFromSID($this->SID);
+ }
+
+ if ( $purpose === self::PURPOSE_REFERENCE ) {
+ return $this->Storage->GetID();
+ }
+
+ throw new RuntimeException('The "' . $purpose . '" purpose is not supported.');
}
/**
* Generates new session id
*
- * @return int
- * @access private
+ * @return string
*/
- function GenerateSID()
+ protected function GenerateSID()
{
- $this->setSID(
- SecurityGenerator::generateNumber(100000000, 999999999)
- ->resolveForPersisting(TABLE_PREFIX . 'UserSessions', 'SessionKey')
- );
+ $promise = SecurityGenerator::generateBytes(16);
+ $promise->asSignature()->resolveForPersisting(TABLE_PREFIX . 'UserSessions', 'SessionKey');
+ $new_sid = $promise->asValue()->resolve();
+
+ $this->setSID($new_sid);
return $this->SID;
}
/**
* Set's new session id
*
* @param int $new_sid
* @access private
*/
function setSID($new_sid)
{
$this->SID /*= $this->CachedSID*/ = $new_sid; // don't set cached sid here
$this->Application->SetVar($this->GETName,$new_sid);
}
function NeedSession()
{
$data = $this->Data->GetParams();
$data_keys = array_keys($data);
$optional_keys = array_keys($this->OptionalData);
$real_keys = array_diff($data_keys, $optional_keys);
return $real_keys ? true : false;
}
function SetSession($force = false)
{
if ( $this->SessionSet && !$force ) {
return true;
}
$this->Expiration = adodb_mktime() + $this->SessionTimeout;
if ( !$force && /*!$this->Application->isAdmin &&*/ !$this->Application->GetVar('admin') && !$this->NeedSession() ) {
// don't create session (in db) on Front-End, when sid is present (GPC), but data in db isn't
if ( $this->_fromGet ) {
// set sid, that was given in GET
$this->setSID($this->GetPassedSIDValue());
}
else {
// re-generate sid only, when cookies are used
$this->GenerateSID();
}
$this->Storage->StoreSession(false);
return false;
}
if ( !$this->SID || $force ) {
$this->GenerateSID();
}
switch ( $this->Mode ) {
case self::smAUTO:
if ( $this->CookiesEnabled ) {
$this->SetSessionCookie();
}
break;
case self::smGET_ONLY:
break;
case self::smCOOKIES_ONLY:
case self::smCOOKIES_AND_GET:
$this->SetSessionCookie();
break;
}
$this->Storage->StoreSession();
if ( $this->Application->isAdmin || $this->Special == 'admin' ) {
$this->StoreVar('admin', 1);
}
$this->SessionSet = true; // should be called before SaveData, because SaveData will try to SetSession again
if ( $this->Special != '' ) {
// front-session called from admin or otherwise, then save it's data
$this->SaveData();
}
$this->Application->resetCounters('UserSessions');
return true;
}
/**
* Returns SID from cookie.
*
* Use 2 cookies to have 2 expiration:
* - 1. for normal expiration when browser is not closed (30 minutes by default), configurable
* - 2. for advanced expiration when browser is closed
*
* @return int
*/
function GetSessionCookie()
{
$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
}
function RemoveSessionCookie()
{
$this->SetCookie($this->CookieName, '');
$this->SetCookie($this->CookieName.'_live', '');
$_COOKIE[$this->CookieName] = null; // for compatibility with in-portal
}
/**
* Refreshes session expiration time
*
* @access private
*/
function Refresh()
{
if ($this->Application->GetVar('skip_session_refresh')) {
return ;
}
if ($this->CookiesEnabled) {
// we need to refresh the cookie
$this->SetSessionCookie();
}
$this->Storage->UpdateSession();
}
function Destroy()
{
$this->Storage->DeleteSession();
$this->Data = new Params();
$this->SID = $this->CachedSID = '';
$this->SessionSet = false;
if ($this->CookiesEnabled) {
$this->SetSessionCookie(); //will remove the cookie due to value (sid) is empty
}
$this->SetSession(true); //will create a new session, true to force
}
function NeedQueryString($use_cache = 1)
{
if ( $this->CachedNeedQueryString !== null && $use_cache ) {
return $this->CachedNeedQueryString;
}
$result = false;
switch ($this->Mode) {
case self::smAUTO:
if ( !$this->CookiesEnabled && PHP_SAPI !== 'cli' ) {
$result = true;
}
break;
/*case self::smCOOKIES_ONLY:
break;*/
case self::smGET_ONLY:
case self::smCOOKIES_AND_GET:
if ( PHP_SAPI !== 'cli' ) {
$result = true;
}
break;
}
$this->CachedNeedQueryString = $result;
return $result;
}
function LoadData()
{
$this->Data->AddParams( $this->Storage->LoadData() );
}
/**
* Returns information about session contents
*
* @param bool $include_optional
* @return array
* @access public
*/
public function getSessionData($include_optional = true)
{
$session_data = $this->Data->GetParams();
ksort($session_data);
foreach ($session_data as $session_key => $session_value) {
if ( kUtil::IsSerialized($session_value) ) {
$session_data[$session_key] = unserialize($session_value);
}
}
if ( !$include_optional ) {
$optional_keys = array_keys($this->OptionalData);
foreach ($session_data as $session_key => $session_value) {
if ( in_array($session_key, $optional_keys) ) {
unset($session_data[$session_key]);
}
}
}
return $session_data;
}
/**
* Returns real session data, that was saved
*
* @param Array $session_data
* @return Array
* @access protected
*/
protected function _getRealSessionData($session_data)
{
$data_keys = array_keys($session_data);
$optional_keys = array_keys($this->OptionalData);
$real_keys = array_diff($data_keys, $optional_keys);
if ( !$real_keys ) {
return Array ();
}
$ret = Array ();
foreach ($real_keys as $real_key) {
$ret[$real_key] = $session_data[$real_key];
}
return $ret;
}
function PrintSession($comment = '')
{
if ( defined('DEBUG_MODE') && $this->Application->isDebugMode() && kUtil::constOn('DBG_SHOW_SESSIONDATA') ) {
// dump session data
$this->Application->Debugger->appendHTML('SessionStorage [' . ($this->RecallVar('admin') == 1 ? 'Admin' : 'Front-End') . '] (' . $comment . '):');
$session_data = $this->getSessionData();
$this->Application->Debugger->dumpVars($session_data);
if ( !$this->RecallVar('admin') ) {
// dump real keys (only for front-end)
$real_session_data = $this->_getRealSessionData($session_data);
if ( $real_session_data ) {
$this->Application->Debugger->appendHTML('Real Keys:');
$this->Application->Debugger->dumpVars($real_session_data);
}
}
}
if ( defined('DEBUG_MODE') && $this->Application->isDebugMode() && kUtil::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 ( kUtil::IsSerialized($session_value) ) {
$session_data[$session_key] = unserialize($session_value);
}
}
$this->Application->Debugger->dumpVars($session_data);
}
}
}
function SaveData($params = Array ())
{
if (!$this->SetSession()) { // call it here - it may be not set before, because there was no need; if there is a need, it will be set here
return;
}
if (!$this->Application->GetVar('skip_last_template') && $this->Application->GetVar('ajax') != 'yes') {
$this->SaveLastTemplate( $this->Application->GetVar('t'), $params );
}
$this->PrintSession('after save');
$this->Storage->SaveData();
}
/**
* Save last template
*
* @param string $t
* @param Array $params
*/
function SaveLastTemplate($t, $params = Array ())
{
$wid = $this->Application->GetVar('m_wid');
$last_env = $this->getLastTemplateENV($t, array('m_opener' => 'u'));
$last_template = basename($_SERVER['PHP_SELF']) . '|' . $last_env;
$this->StoreVar(rtrim('last_template_' . $wid, '_'), $last_template);
// prepare last_template for opener stack, module & session could be added later
$last_env = $this->getLastTemplateENV($t);
$last_template = basename($_SERVER['PHP_SELF']) . '|' . $last_env;
// save last_template in persistent 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 ( $this->Application->GetVarDirect('section', 'Get') !== false ) {
// check directly in GET, because 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')) {
// admin checking by session data to prevent recursive session save
static $admin_saved = null;
if (!$this->RecallVar('admin') && !isset($admin_saved)) {
// bug: we get recursion in this place, when cookies are disabled in browser and we are browsing
// front-end in admin's frame (front-end session is initialized using admin's sid and they are
// mixed together)
$admin_saved = true;
/** @var Session $admin_session */
$admin_session = $this->Application->recallObject('Session.admin');
// save to admin last_template too, because when F5 is pressed in frameset Front-End frame should reload as well
$admin_session->StoreVar('last_template_popup', '../' . $last_template);
$admin_session->StorePersistentVar('last_template_popup', '../' . $last_template);
$admin_session->SaveData( Array ('save_last_template' => false) );
}
else {
// don't allow admin=1 & editing_mode=* to get in admin last_template
$last_template = preg_replace('/&(admin|editing_mode)=[\d]/', '', $last_template);
}
}
}
// save other last... variables for mystical purposes (customizations may be)
$this->StoreVar('last_url', $_SERVER['REQUEST_URI']); // needed by ord:StoreContinueShoppingLink
$this->StoreVar('last_env', $last_env);
$save_last_template = array_key_exists('save_last_template', $params) ? $params['save_last_template'] : true;
if ($save_last_template) {
// save last template here, because section & module could be added before
$this->StoreVar(rtrim('last_template_popup_'.$wid, '_'), $last_template);
}
}
protected function getLastTemplateENV($t, $params = null)
{
if (!isset($params)) {
$params = Array ();
}
if ($this->Application->GetVar('admin') && !array_key_exists('admin', $params) && !defined('EDITING_MODE')) {
$params['editing_mode'] = ''; // used in kApplication::Run
}
$params = array_merge($this->Application->getPassThroughVariables($params), $params);
return $this->Application->BuildEnv($t, $params, 'all', false, false);
}
/**
* Stores variable $val in session under name $var
*
* Use this method to store variable in session. Later this variable could be recalled.
*
* @param string $name Variable name
* @param mixed $value Variable value
* @param bool $optional
* @return void
* @access public
* @see Session::RecallVar()
*/
public function StoreVar($name, $value, $optional = false)
{
$this->Data->Set($name, $value);
if ( $optional ) {
// make variable optional, also remember optional value
$this->OptionalData[$name] = $value;
}
elseif ( !$optional && array_key_exists($name, $this->OptionalData) ) {
if ( $this->OptionalData[$name] == $value ) {
// same value as optional -> don't remove optional mark
return;
}
// make variable non-optional
unset($this->OptionalData[$name]);
}
}
/**
* Stores variable to persistent session
*
* @param string $name
* @param mixed $value
* @param bool $optional
* @return void
* @access public
*/
public function StorePersistentVar($name, $value, $optional = false)
{
$this->Storage->StorePersistentVar($name, $value, $optional);
}
function LoadPersistentVars()
{
$this->Storage->LoadPersistentVars();
}
/**
* Stores default value for session variable
*
* @param string $name
* @param string $value
* @param bool $optional
* @return void
* @access public
* @see Session::RecallVar()
* @see Session::StoreVar()
*/
public function StoreVarDefault($name, $value, $optional = false)
{
$tmp = $this->RecallVar($name);
if ( $tmp === false || $tmp == '' ) {
$this->StoreVar($name, $value, $optional);
}
}
/**
* Returns session variable value
*
* Return value of $var variable stored in Session. An optional default value could be passed as second parameter.
*
* @param string $name Variable name
* @param mixed $default Default value to return if no $var variable found in session
* @return mixed
* @access public
*/
public function RecallVar($name, $default = false)
{
$ret = $this->Data->Get($name);
return ($ret === false) ? $default : $ret;
}
/**
* Returns variable value from persistent session
*
* @param string $name
* @param mixed $default
* @return mixed
* @access public
*/
public function RecallPersistentVar($name, $default = false)
{
return $this->Storage->RecallPersistentVar($name, $default);
}
/**
* Deletes Session variable
*
* @param string $var
* @return void
* @access public
*/
public function RemoveVar($name)
{
$this->Storage->RemoveFromData($name);
$this->Data->Remove($name);
}
/**
* Removes variable from persistent session
*
* @param string $name
* @return void
* @access public
*/
public function RemovePersistentVar($name)
{
$this->Storage->RemovePersistentVar($name);
}
/**
* Ignores session variable value set before
*
* @param string $name
* @return void
* @access public
*/
public function RestoreVar($name)
{
$value = $this->Storage->GetFromData($name, '__missing__');
if ( $value === '__missing__' ) {
// there is nothing to restore (maybe session was not saved), look in optional variable values
$value = array_key_exists($name, $this->OptionalData) ? $this->OptionalData[$name] : false;
}
$this->StoreVar($name, $value);
}
function GetField($var_name, $default = false)
{
return $this->Storage->GetField($var_name, $default);
}
function SetField($var_name, $value)
{
$this->Storage->SetField($var_name, $value);
}
/**
* Deletes expired sessions
*
* @return Array expired sids if any
* @access private
*/
function DeleteExpired()
{
return $this->Storage->DeleteExpired();
}
/**
* Deletes given sessions
*
* @param $session_ids
* @param int $delete_reason
* @return void
*/
function DeleteSessions($session_ids, $delete_reason = SESSION_LOG_EXPIRED)
{
$this->Storage->DeleteSessions($session_ids, $delete_reason);
}
/**
* 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 || defined('ADMIN')) && ($user_id == USER_ROOT)) {
$ret = true;
}
return $ret;
}
}
Index: branches/5.2.x/core/kernel/session/session_storage.php
===================================================================
--- branches/5.2.x/core/kernel/session/session_storage.php (revision 16796)
+++ branches/5.2.x/core/kernel/session/session_storage.php (revision 16797)
@@ -1,557 +1,619 @@
<?php
/**
* @version $Id$
* @package In-Portal
* @copyright Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license GNU/GPL
* In-Portal is Open Source software.
* This means that this software may have been modified pursuant
* the GNU General Public License, and as distributed it includes
* or is derivative of works licensed under the GNU General Public License
* or other free or open source software licenses.
* See http://www.in-portal.org/license for copyright notices and details.
*/
defined('FULL_PATH') or die('restricted access!');
/**
* Implements Session Store in the Database
*
*/
class SessionStorage extends kDBBase {
/**
* Reference to session
*
* @var Session
* @access protected
*/
protected $Session = null;
var $Expiration;
var $SessionTimeout = 0;
var $DirectVars = Array ();
var $ChangedDirectVars = Array ();
var $PersistentVars = Array ();
/**
* Default persistent vars
*
* @var array
*/
protected $defaultPersistentVars = array();
var $OriginalData = Array ();
+ /**
+ * Session key field.
+ *
+ * @var string
+ */
+ protected $sessionKeyField;
+
var $TimestampField;
var $SessionDataTable;
var $DataValueField;
var $DataVarField;
public function Init($prefix, $special)
{
parent::Init($prefix, $special);
$this->TableName = 'sessions';
- $this->IDField = 'sid';
+ $this->IDField = 'session_id';
+ $this->sessionKeyField = 'sid';
$this->TimestampField = 'expire';
$this->SessionDataTable = 'SessionData';
$this->DataValueField = 'value';
$this->DataVarField = 'var';
}
/**
+ * @inheritDoc
+ *
+ * @throws RuntimeException When session isn't found in the database.
+ */
+ public function GetID()
+ {
+ $session_id = $this->GetField($this->IDField);
+
+ if ( $session_id === null ) {
+ throw new RuntimeException(
+ 'Session with "' . $this->Session->GetID(Session::PURPOSE_STORAGE) . '" key not found in the database.'
+ );
+ }
+
+ return $session_id;
+ }
+
+ /**
* Sets reference to session
*
* @param Session $session
*/
public function setSession(&$session)
{
$this->Session =& $session;
$this->SessionTimeout = $session->SessionTimeout;
}
/**
* Calculates browser signature
*
* @return string
*/
function _getBrowserSignature()
{
$signature_parts = Array(
'HTTP_USER_AGENT', 'SERVER_PROTOCOL',
'HTTP_ACCEPT_CHARSET', 'HTTP_ACCEPT_ENCODING', 'HTTP_ACCEPT_LANGUAGE'
);
$ret = '';
foreach ($signature_parts as $signature_part) {
if (array_key_exists($signature_part, $_SERVER)) {
$ret .= '&|&' . $_SERVER[$signature_part];
}
}
return md5( substr($ret, 3) );
}
function GetSessionDefaults()
{
$fields_hash = Array (
- $this->IDField => $this->Session->SID,
+ $this->IDField => null,
+ $this->sessionKeyField => $this->Session->GetID(Session::PURPOSE_STORAGE),
$this->TimestampField => $this->Session->Expiration,
);
if (!defined('IS_INSTALL') || !IS_INSTALL) {
// this column was added only in 5.0.1 version,
// so accessing it while database is not upgraded
// will result in admin's inability to login inside
// installator
$fields_hash['BrowserSignature'] = $this->_getBrowserSignature();
}
// default values + values set during this script run
return array_merge($fields_hash, $this->DirectVars);
}
/**
* Stores session to database
*
* @param bool $to_database
*
* @return void
* @access public
*/
public function StoreSession($to_database = true)
{
if ( defined('IS_INSTALL') && IS_INSTALL && $to_database && !$this->Application->TableFound($this->TableName, true) ) {
return;
}
$fields_hash = $this->GetSessionDefaults();
if ( $to_database ) {
$this->Conn->doInsert($fields_hash, $this->TableName);
+ $fields_hash[$this->IDField] = $this->Conn->getInsertID();
}
foreach ($fields_hash as $field_name => $field_value) {
$this->SetField($field_name, $field_value);
}
// Reset change flags, because session is already saved to the database.
$this->ChangedDirectVars = array();
// ensure user groups are stored in a way, that kPermissionsHelper::CheckUserPermission can understand
$this->Session->StoreVar('UserGroups', $this->GetField('GroupList'), !$to_database);
}
function DeleteSession()
{
- $this->DeleteSessions( Array ($this->Session->SID), SESSION_LOG_LOGGED_OUT );
+ $this->DeleteSessions( Array ($this->GetID()), SESSION_LOG_LOGGED_OUT );
$this->DirectVars = $this->ChangedDirectVars = $this->OriginalData = Array();
}
function UpdateSession($timeout = 0)
{
$this->SetField($this->TimestampField, $this->Session->Expiration);
- $query = ' UPDATE '.$this->TableName.' SET '.$this->TimestampField.' = '.$this->Session->Expiration.' WHERE '.$this->IDField.' = '.$this->Conn->qstr($this->Session->SID);
- $this->Conn->Query($query);
+
+ $this->Conn->doUpdate(
+ array($this->TimestampField => $this->Session->Expiration),
+ $this->TableName,
+ $this->IDField . ' = ' . $this->GetID()
+ );
}
function LocateSession($sid)
{
$sql = 'SELECT *
FROM ' . $this->TableName . '
- WHERE ' . $this->IDField . ' = ' . $this->Conn->qstr($sid);
+ WHERE ' . $this->sessionKeyField . ' = ' . $this->Conn->qstr($this->createSignatureFromSID($sid));
$result = $this->Conn->GetRow($sql);
if ($result === false) {
return false;
}
// perform security checks to ensure, that session is used by it's creator
if ($this->Application->ConfigValue('SessionBrowserSignatureCheck') && ($result['BrowserSignature'] != $this->_getBrowserSignature()) && $this->Application->GetVar('flashsid') === false) {
return false;
}
if ($this->Application->ConfigValue('SessionIPAddressCheck') && ($result['IpAddress'] != $this->Application->getClientIp())) {
// most secure, except for cases where NAT (Network Address Translation)
// is used and two or more computers can have same IP address
return false;
}
$this->DirectVars = $result;
$this->Expiration = $result[$this->TimestampField];
return true;
}
+ /**
+ * Creates signature from SID.
+ *
+ * @param string $sid SID.
+ *
+ * @return string
+ */
+ public function createSignatureFromSID($sid)
+ {
+ /** @var SecurityEncrypter $encrypter */
+ $encrypter = $this->Application->recallObject('SecurityEncrypter');
+
+ return $encrypter->createSignature($sid);
+ }
+
function GetExpiration()
{
return $this->Expiration;
}
function LoadData()
{
- $query = 'SELECT '.$this->DataValueField.','.$this->DataVarField.' FROM '.$this->SessionDataTable.' WHERE '.$this->IDField.' = '.$this->Conn->qstr($this->Session->SID);
+ $sql = 'SELECT ' . $this->DataValueField . ',' . $this->DataVarField . '
+ FROM ' . $this->SessionDataTable . '
+ WHERE ' . $this->IDField . ' = ' . $this->GetID();
+ $this->OriginalData = $this->Conn->GetCol($sql, $this->DataVarField);
- $this->OriginalData = $this->Conn->GetCol($query, $this->DataVarField);
return $this->OriginalData;
}
/**
* Enter description here...
*
* @param string $var_name
* @param mixed $default
* @return mixed
*/
function GetField($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($this->Session->GetID()) );
+ return array_key_exists($var_name, $this->DirectVars) ? $this->DirectVars[$var_name] : $default;
}
function SetField($var_name, $value)
{
- $value_changed = !isset($this->DirectVars[$var_name]) || ($this->DirectVars[$var_name] != $value);
- if ($value_changed) {
+ $value_changed = !array_key_exists($var_name, $this->DirectVars) || ($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($this->Session->GetID()) );
}
/**
* Saves changes in session to database using single REPLACE query
*
* @return void
* @access public
*/
public function SaveData()
{
- if ( !$this->Session->SID ) {
- // can't save without sid
- return ;
+ $session_id = $this->GetID();
+
+ if ( !$session_id ) {
+ // Can't save without sid.
+ return;
}
$replace = '';
$ses_data = $this->Session->Data->GetParams();
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($this->Session->SID), $this->Conn->qstr($key), $this->Conn->qstr($value));
+ $replace .= sprintf('(%s, %s, %s),', $session_id, $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);
$this->OriginalData = $ses_data;
}
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($this->Session->GetID());
+ WHERE ' . $this->IDField . ' = ' . $session_id;
$this->Conn->Query($query);
$this->ChangedDirectVars = array();
}
}
function RemoveFromData($var)
{
- if ($this->Session->SessionSet) {
- // only, when session is stored in database
+ if ( $this->Session->SessionSet ) {
+ // Only, when session is stored in database.
+ $where_clause = array(
+ $this->IDField . ' = ' . $this->GetID(),
+ $this->DataVarField . ' = ' . $this->Conn->qstr($var),
+ );
$sql = 'DELETE FROM ' . $this->SessionDataTable . '
- WHERE ' . $this->IDField . ' = ' . $this->Conn->qstr($this->Session->SID) . ' AND ' . $this->DataVarField . ' = ' . $this->Conn->qstr($var);
+ WHERE (' . implode(') AND (', $where_clause) . ')';
$this->Conn->Query($sql);
}
unset($this->OriginalData[$var]);
}
function GetFromData($var, $default = false)
{
return array_key_exists($var, $this->OriginalData) ? $this->OriginalData[$var] : $default;
}
function GetExpiredSIDs()
{
$sql = 'SELECT ' . $this->IDField . '
FROM ' . $this->TableName . '
WHERE ' . $this->TimestampField . ' > ' . adodb_mktime();
return $this->Conn->GetCol($sql);
}
function DeleteExpired()
{
$expired_sids = $this->GetExpiredSIDs();
$this->DeleteSessions($expired_sids);
return $expired_sids;
}
function DeleteSessions($session_ids, $delete_reason = SESSION_LOG_EXPIRED)
{
if (!$session_ids) {
return ;
}
$log_table = $this->Application->getUnitOption('session-log', 'TableName');
if ($log_table) {
// mark session with proper status
$sub_sql = 'SELECT ' . $this->TimestampField . ' - ' . $this->SessionTimeout . '
FROM ' . $this->TableName . '
WHERE ' . $this->IDField . ' = ' . $log_table . '.SessionId';
$sql = 'UPDATE ' . $log_table . '
SET Status = ' . $delete_reason . ', SessionEnd = (' . $sub_sql . ')
WHERE Status = ' . SESSION_LOG_ACTIVE . ' AND SessionId IN (' . implode(',', $session_ids) . ')';
$this->Conn->Query($sql);
}
$where_clause = ' WHERE ' . $this->IDField . ' IN (' . implode(',', $session_ids) . ')';
+
+ $sql = 'SELECT SessionKey
+ FROM ' . $this->TableName .
+ $where_clause;
+ $session_keys = $this->Conn->GetCol($sql);
+
$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 deleted sessions
- foreach ($session_ids as $session_id) {
- $debug_file = (defined('RESTRICTED') ? RESTRICTED : WRITEABLE . '/cache') . '/debug_@' . $session_id . '@.txt';
- if (file_exists($debug_file)) {
+ // Delete debugger outputs left of deleted sessions.
+ foreach ( $session_keys as $session_key ) {
+ $debug_file = (defined('RESTRICTED') ? RESTRICTED : WRITEABLE . '/cache');
+ $debug_file .= '/debug_@' . $session_key . '@.txt';
+
+ if ( file_exists($debug_file) ) {
@unlink($debug_file);
- }
+ }
}
}
function LoadPersistentVars()
{
$user_id = $this->Session->RecallVar('user_id');
if ( $user_id != USER_GUEST ) {
// Root & normal users.
$this->PersistentVars = $this->getPersistentVars($user_id);
}
else {
$this->PersistentVars = Array ();
}
$default_user_id = (int)$this->Application->ConfigValue('DefaultSettingsUserId');
if ( !$default_user_id ) {
$default_user_id = USER_ROOT;
}
if ( $user_id != $default_user_id ) {
$this->defaultPersistentVars = $this->getPersistentVars($default_user_id);
}
}
/**
* Get persistent vars
*
* @param integer $user_id User Id.
*
* @return array
*/
protected function getPersistentVars($user_id)
{
$sql = 'SELECT VariableValue, VariableName
FROM ' . TABLE_PREFIX . 'UserPersistentSessionData
WHERE PortalUserId = ' . $user_id;
return $this->Conn->GetCol($sql, 'VariableName');
}
/**
* Stores variable to persistent session
*
* @param string $var_name
* @param mixed $var_value
* @param bool $optional
* @return void
* @access public
*/
public function StorePersistentVar($var_name, $var_value, $optional = false)
{
$user_id = $this->Session->RecallVar('user_id');
if ( $user_id == USER_GUEST || $user_id === false ) {
// -2 (when not logged in), false (when after u:OnLogout event)
$this->Session->StoreVar($var_name, $var_value, $optional);
return;
}
$this->PersistentVars[$var_name] = $var_value;
$key_clause = 'PortalUserId = ' . $user_id . ' AND VariableName = ' . $this->Conn->qstr($var_name);
$sql = 'SELECT VariableName
FROM ' . TABLE_PREFIX . 'UserPersistentSessionData
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 . 'UserPersistentSessionData', $key_clause);
}
else {
$this->Conn->doInsert($fields_hash, TABLE_PREFIX . 'UserPersistentSessionData');
}
}
/**
* Gets persistent variable
*
* @param string $var_name
* @param mixed $default
* @return mixed
* @access public
*/
public function RecallPersistentVar($var_name, $default = false)
{
if ( $this->Session->RecallVar('user_id') == USER_GUEST ) {
if ( $default == ALLOW_DEFAULT_SETTINGS ) {
$default = null;
}
return $this->Session->RecallVar($var_name, $default);
}
if ( array_key_exists($var_name, $this->PersistentVars) ) {
return $this->PersistentVars[$var_name];
}
elseif ( $default == ALLOW_DEFAULT_SETTINGS ) {
if ( isset($this->defaultPersistentVars[$var_name]) ) {
$value = $this->defaultPersistentVars[$var_name];
$this->StorePersistentVar($var_name, $value);
return $value;
}
$this->PersistentVars[$var_name] = false;
return false;
}
return $default;
}
/**
* Removes variable from persistent session
*
* @param string $var_name
* @return void
* @access public
*/
function RemovePersistentVar($var_name)
{
unset($this->PersistentVars[$var_name]);
$user_id = $this->Session->RecallVar('user_id');
if ( $user_id == USER_GUEST || $user_id === false ) {
// -2 (when not logged in), false (when after u:OnLogout event)
$this->Session->RemoveVar($var_name);
}
else {
$sql = 'DELETE FROM ' . TABLE_PREFIX . 'UserPersistentSessionData
WHERE PortalUserId = ' . $user_id . ' AND VariableName = ' . $this->Conn->qstr($var_name);
$this->Conn->Query($sql);
}
}
/**
* Checks of object has given field
*
* @param string $name
*
* @return bool
* @access public
* @throws BadMethodCallException Always.
*/
public function HasField($name)
{
throw new BadMethodCallException('Unsupported');
}
/**
* Returns field values
*
* @return Array
* @access public
* @throws BadMethodCallException Always.
*/
public function GetFieldValues()
{
throw new BadMethodCallException('Unsupported');
}
/**
* Returns unformatted field value
*
* @param string $field
*
* @return string
* @access public
* @throws BadMethodCallException Always.
*/
public function GetDBField($field)
{
throw new BadMethodCallException('Unsupported');
}
/**
* Returns true, when list/item was queried/loaded
*
* @return bool
* @access public
* @throws BadMethodCallException Always.
*/
public function isLoaded()
{
throw new BadMethodCallException('Unsupported');
}
/**
* Returns specified field value from all selected rows.
* Don't affect current record index
*
* @param string $field
*
* @return Array
* @access public
* @throws BadMethodCallException Always.
*/
public function GetCol($field)
{
throw new BadMethodCallException('Unsupported');
}
}
Index: branches/5.2.x/core/kernel/db/db_load_balancer.php
===================================================================
--- branches/5.2.x/core/kernel/db/db_load_balancer.php (revision 16796)
+++ branches/5.2.x/core/kernel/db/db_load_balancer.php (revision 16797)
@@ -1,897 +1,895 @@
<?php
/**
* @version $Id$
* @package In-Portal
* @copyright Copyright (C) 1997 - 2011 Intechnic. All rights reserved.
* @license GNU/GPL
* In-Portal is Open Source software.
* This means that this software may have been modified pursuant
* the GNU General Public License, and as distributed it includes
* or is derivative of works licensed under the GNU General Public License
* or other free or open source software licenses.
* See http://www.in-portal.org/license for copyright notices and details.
*/
defined('FULL_PATH') or die('restricted access!');
class kDBLoadBalancer extends kBase implements IDBConnection {
/**
* Current database type
*
* @var string
* @access protected
*/
protected $dbType = 'mysqli';
/**
* Function to handle sql errors
*
* @var callable
*/
protected $errorHandler = '';
/**
* Database connection settings
*
* @var Array
* @access protected
*/
protected $servers = Array ();
/**
* Load of each slave server, given
*
* @var Array
* @access protected
*/
protected $serverLoads = Array ();
/**
* Caches replication lag of servers
*
* @var Array
* @access protected
*/
protected $serverLagTimes = Array ();
/**
* Connection references to opened connections
*
* @var IDBConnection[]
*/
protected $connections = Array ();
/**
* Index of last user slave connection
*
* @var int
* @access protected
*/
protected $slaveIndex = false;
/**
* Index of the server, that was used last
*
* @var int
* @access protected
*/
protected $lastUsedIndex = 0;
/**
* Consider slave down if it isn't responding for N milliseconds
*
* @var int
* @access protected
*/
protected $DBClusterTimeout = 10;
/**
* Scale load balancer polling time so that under overload conditions, the database server
* receives a SHOW STATUS query at an average interval of this many microseconds
*
* @var int
* @access protected
*/
protected $DBAvgStatusPoll = 2000;
/**
* Indicates, that next database query could be cached, when memory caching is enabled
*
* @var bool
* @access public
*/
public $nextQueryCachable = false;
/**
* The "no debugging" tate of the SQL queries.
*
* @var boolean
*/
public $noDebuggingState = false;
/**
* Indicates, that next query should be sent to maser database
*
* @var bool
*/
public $nextQueryFromMaster = false;
/**
* Creates new instance of load balancer class
*
* @param string $db_type
* @param Array|string $error_handler
*/
function __construct($db_type, $error_handler = '')
{
parent::__construct();
$this->dbType = $db_type;
$this->setErrorHandler($error_handler);
$this->DBClusterTimeout *= 1e6; // convert to milliseconds
}
/**
* Setups load balancer according given configuration.
*
* @param Array $config
* @return void
* @access public
*/
public function setup($config)
{
$this->servers = Array ();
$this->servers[0] = Array (
'DBHost' => $config['Database']['DBHost'],
'DBUser' => $config['Database']['DBUser'],
'DBUserPassword' => $config['Database']['DBUserPassword'],
'DBName' => $config['Database']['DBName'],
'DBLoad' => 0,
);
if ( isset($config['Databases']) ) {
$this->servers = array_merge($this->servers, $config['Databases']);
}
foreach ($this->servers as $server_index => $server_setting) {
$this->serverLoads[$server_index] = $server_setting['DBLoad'];
}
}
/**
* Returns connection index to master database
*
* @return int
* @access protected
*/
protected function getMasterIndex()
{
return 0;
}
/**
* Returns connection index to slave database. This takes into account load ratios and lag times.
* Side effect: opens connections to databases
*
* @return int
* @access protected
*/
protected function getSlaveIndex()
{
if ( count($this->servers) == 1 || $this->Application->isAdmin || defined('CRON') ) {
// Skip the load balancing if there's only one server OR in admin console OR in CRON.
return 0;
}
elseif ( $this->slaveIndex !== false ) {
// shortcut if generic reader exists already
return $this->slaveIndex;
}
$total_elapsed = 0;
$non_error_loads = $this->serverLoads;
$i = $found = $lagged_slave_mode = false;
// first try quickly looking through the available servers for a server that meets our criteria
do {
$current_loads = $non_error_loads;
$overloaded_servers = $total_threads_connected = 0;
while ($current_loads) {
if ( $lagged_slave_mode ) {
// when all slave servers are too lagged, then ignore lag and pick random server
$i = $this->pickRandom($current_loads);
}
else {
$i = $this->getRandomNonLagged($current_loads);
if ( $i === false && $current_loads ) {
// all slaves lagged -> pick random lagged slave then
$lagged_slave_mode = true;
$i = $this->pickRandom( $current_loads );
}
}
if ( $i === false ) {
// all slaves are down -> use master as a slave
$this->slaveIndex = $this->getMasterIndex();
return $this->slaveIndex;
}
$conn =& $this->openConnection($i);
if ( !$conn ) {
unset($non_error_loads[$i], $current_loads[$i]);
continue;
}
// Perform post-connection backoff
$threshold = isset($this->servers[$i]['DBMaxThreads']) ? $this->servers[$i]['DBMaxThreads'] : false;
$backoff = $this->postConnectionBackoff($conn, $threshold);
if ( $backoff ) {
// post-connection overload, don't use this server for now
$total_threads_connected += $backoff;
$overloaded_servers++;
unset( $current_loads[$i] );
}
else {
// return this server
break 2;
}
}
// no server found yet
$i = false;
// if all servers were down, quit now
if ( !$non_error_loads ) {
break;
}
// back off for a while
// scale the sleep time by the number of connected threads, to produce a roughly constant global poll rate
$avg_threads = $total_threads_connected / $overloaded_servers;
usleep($this->DBAvgStatusPoll * $avg_threads);
$total_elapsed += $this->DBAvgStatusPoll * $avg_threads;
} while ( $total_elapsed < $this->DBClusterTimeout );
if ( $i !== false ) {
// slave connection successful
if ( $this->slaveIndex <= 0 && $this->serverLoads[$i] > 0 && $i !== false ) {
$this->slaveIndex = $i;
}
}
return $i;
}
/**
* Returns random non-lagged server
*
* @param Array $loads
* @return int
* @access protected
*/
protected function getRandomNonLagged($loads)
{
// unset excessively lagged servers
$lags = $this->getLagTimes();
foreach ($lags as $i => $lag) {
if ( $i != 0 && isset($this->servers[$i]['DBMaxLag']) ) {
if ( $lag === false ) {
unset( $loads[$i] ); // server is not replicating
}
elseif ( $lag > $this->servers[$i]['DBMaxLag'] ) {
unset( $loads[$i] ); // server is excessively lagged
}
}
}
// find out if all the slaves with non-zero load are lagged
if ( !$loads || array_sum($loads) == 0 ) {
return false;
}
// return a random representative of the remainder
return $this->pickRandom($loads);
}
/**
* Select an element from an array of non-normalised probabilities
*
* @param Array $weights
* @return int
* @access protected
*/
protected function pickRandom($weights)
{
if ( !is_array($weights) || !$weights ) {
return false;
}
$sum = array_sum($weights);
if ( $sum == 0 ) {
return false;
}
$max = mt_getrandmax();
$rand = mt_rand(0, $max) / $max * $sum;
$index = $sum = 0;
foreach ($weights as $index => $weight) {
$sum += $weight;
if ( $sum >= $rand ) {
break;
}
}
return $index;
}
/**
* Get lag time for each server
* Results are cached for a short time in memcached, and indefinitely in the process cache
*
* @return Array
* @access protected
*/
protected function getLagTimes()
{
if ( $this->serverLagTimes ) {
return $this->serverLagTimes;
}
$expiry = 5;
$request_rate = 10;
$cache_key = 'lag_times:' . $this->servers[0]['DBHost'];
$times = $this->Application->getCache($cache_key);
if ( $times ) {
// randomly recache with probability rising over $expiry
$elapsed = adodb_mktime() - $times['timestamp'];
$chance = max(0, ($expiry - $elapsed) * $request_rate);
if ( mt_rand(0, $chance) != 0 ) {
unset( $times['timestamp'] );
$this->serverLagTimes = $times;
return $times;
}
}
// cache key missing or expired
$times = Array();
foreach ($this->servers as $index => $server) {
if ($index == 0) {
$times[$index] = 0; // master
}
else {
$conn =& $this->openConnection($index);
if ($conn !== false) {
$times[$index] = $conn->getSlaveLag();
}
}
}
// add a timestamp key so we know when it was cached
$times['timestamp'] = adodb_mktime();
$this->Application->setCache($cache_key, $times, $expiry);
// but don't give the timestamp to the caller
unset($times['timestamp']);
$this->serverLagTimes = $times;
return $this->serverLagTimes;
}
/**
* Determines whatever server should not be used, even, when connection was made
*
* @param kDBConnection $conn
* @param int $threshold
* @return int
* @access protected
*/
protected function postConnectionBackoff(&$conn, $threshold)
{
if ( !$threshold ) {
return 0;
}
$status = $conn->getStatus('Thread%');
return $status['Threads_running'] > $threshold ? $status['Threads_connected'] : 0;
}
/**
* Open a connection to the server given by the specified index
* Index must be an actual index into the array.
* If the server is already open, returns it.
*
* On error, returns false.
*
* @param integer $i Server index
* @return kDBConnection|false
* @access protected
*/
protected function &openConnection($i)
{
if ( isset($this->connections[$i]) ) {
$conn =& $this->connections[$i];
$this->lastUsedIndex = $i;
}
else {
$server = $this->servers[$i];
$server['serverIndex'] = $i;
$conn =& $this->reallyOpenConnection($server, $i == $this->getMasterIndex());
if ( $conn->connectionOpened ) {
$this->connections[$i] =& $conn;
$this->lastUsedIndex = $i;
}
else {
$conn = false;
}
}
if ( is_object($conn) ) {
$conn->noDebuggingState = $this->noDebuggingState;
if ( $this->nextQueryCachable ) {
$conn->nextQueryCachable = true;
$this->nextQueryCachable = false;
}
}
return $conn;
}
/**
* Checks if previous query execution raised an error.
*
* @return bool
* @access public
*/
public function hasError()
{
$conn =& $this->openConnection($this->lastUsedIndex);
return $conn->hasError();
}
/**
* Checks if connection to the server given by the specified index is opened.
*
* @param integer $i Server index
* @return bool
* @access public
*/
public function connectionOpened($i = null)
{
$conn =& $this->openConnection(isset($i) ? $i : $this->getMasterIndex());
return $conn ? $conn->connectionOpened : false;
}
/**
* Really opens a connection.
* Returns a database object whether or not the connection was successful.
*
* @param Array $server
* @param bool $is_master
* @return kDBConnection
*/
protected function &reallyOpenConnection($server, $is_master)
{
$debug_mode = $this->Application->isDebugMode();
$db_class = $debug_mode ? 'kDBConnectionDebug' : 'kDBConnection';
/** @var kDBConnection $db */
$db = $this->Application->makeClass($db_class, Array ($this->dbType, $this->errorHandler, $server['serverIndex']));
$db->debugMode = $debug_mode;
$db->Connect($server['DBHost'], $server['DBUser'], $server['DBUserPassword'], $this->servers[0]['DBName'], !$is_master);
return $db;
}
/**
* Returns first field of first line of recordset if query ok or false otherwise.
*
* @param string $sql
* @param int $offset
* @return string
* @access public
*/
public function GetOne($sql, $offset = 0)
{
$conn =& $this->chooseConnection($sql);
return $conn->GetOne($sql, $offset);
}
/**
* Returns first row of recordset if query ok, false otherwise.
*
* @param string $sql
* @param int $offset
* @return Array
* @access public
*/
public function GetRow($sql, $offset = 0)
{
$conn =& $this->chooseConnection($sql);
return $conn->GetRow($sql, $offset);
}
/**
* Returns 1st column of recordset as one-dimensional array or false otherwise.
*
* Optional parameter $key_field can be used to set field name to be used as resulting array key.
*
* @param string $sql
* @param string $key_field
* @return Array
* @access public
*/
public function GetCol($sql, $key_field = null)
{
$conn =& $this->chooseConnection($sql);
return $conn->GetCol($sql, $key_field);
}
/**
* Returns iterator for 1st column of a recordset or false in case of error.
*
* Optional parameter $key_field can be used to set field name to be used as resulting array key.
*
* @param string $sql
* @param string $key_field
* @return bool|kMySQLQueryCol
*/
public function GetColIterator($sql, $key_field = null)
{
$conn =& $this->chooseConnection($sql);
return $conn->GetColIterator($sql, $key_field);
}
/**
* Queries db with $sql query supplied and returns rows selected if any, false otherwise.
*
* Optional parameter $key_field allows to set one of the query fields value as key in string array.
*
* @param string $sql
* @param string $key_field
* @param boolean|null $no_debug
* @return Array
* @access public
*/
public function Query($sql, $key_field = null, $no_debug = null)
{
$conn =& $this->chooseConnection($sql);
return $conn->Query($sql, $key_field, $no_debug);
}
/**
* Returns iterator to a recordset, produced from running $sql query.
*
* Queries db with $sql query supplied and returns kMySQLQuery iterator or false in case of error.
* Optional parameter $key_field allows to set one of the query fields value as key in string array.
*
* @param string $sql
* @param string $key_field
* @param boolean|null $no_debug
* @param string $iterator_class
* @return kMySQLQuery|bool
* @access public
*/
public function GetIterator($sql, $key_field = null, $no_debug = null, $iterator_class = 'kMySQLQuery')
{
$conn =& $this->chooseConnection($sql);
return $conn->GetIterator($sql, $key_field, $no_debug, $iterator_class);
}
/**
* Free memory used to hold recordset handle.
*
* @access public
*/
public function Destroy()
{
$conn =& $this->openConnection($this->lastUsedIndex);
$conn->Destroy();
}
/**
* Performs sql query, that will change database content.
*
* @param string $sql
* @return bool
* @access public
*/
public function ChangeQuery($sql)
{
$conn =& $this->chooseConnection($sql);
return $conn->ChangeQuery($sql);
}
/**
* Returns auto increment field value from insert like operation if any, zero otherwise.
*
* @return int
* @access public
*/
public function getInsertID()
{
$conn =& $this->openConnection($this->lastUsedIndex);
return $conn->getInsertID();
}
/**
* Returns row count affected by last query.
*
* @return int
* @access public
*/
public function getAffectedRows()
{
$conn =& $this->openConnection($this->lastUsedIndex);
return $conn->getAffectedRows();
}
/**
* Returns LIMIT sql clause part for specific db.
*
* @param int $offset
* @param int $rows
* @return string
* @access public
*/
public function getLimitClause($offset, $rows)
{
$conn =& $this->openConnection($this->lastUsedIndex);
return $conn->getLimitClause($offset, $rows);
}
/**
* If it's a string, adds quotes and backslashes. Otherwise returns as-is.
*
* @param mixed $string
* @return string
* @access public
*/
public function qstr($string)
{
$conn =& $this->openConnection($this->lastUsedIndex);
return $conn->qstr($string);
}
/**
* Calls "qstr" function for each given array element.
*
* @param Array $array
* @param string $function
* @return Array
*/
public function qstrArray($array, $function = 'qstr')
{
$conn =& $this->openConnection($this->lastUsedIndex);
return $conn->qstrArray($array, $function);
}
/**
* Escapes string.
*
* @param mixed $string
* @return string
* @access public
*/
public function escape($string)
{
$conn =& $this->openConnection($this->lastUsedIndex);
return $conn->escape($string);
}
/**
* Returns last error code occurred.
*
* @return int
* @access public
*/
public function getErrorCode()
{
$conn =& $this->openConnection($this->lastUsedIndex);
return $conn->getErrorCode();
}
/**
* Returns last error message.
*
* @return string
* @access public
*/
public function getErrorMsg()
{
$conn =& $this->openConnection($this->lastUsedIndex);
return $conn->getErrorMsg();
}
/**
* Performs insert of given data (useful with small number of queries)
* or stores it to perform multiple insert later (useful with large number of queries).
*
* @param Array $fields_hash
* @param string $table
* @param string $type
* @param bool $insert_now
* @return bool
* @access public
*/
public function doInsert($fields_hash, $table, $type = 'INSERT', $insert_now = true)
{
$conn =& $this->openConnection( $this->getMasterIndex() );
return $conn->doInsert($fields_hash, $table, $type, $insert_now);
}
/**
* Update given field values to given record using $key_clause.
*
* @param Array $fields_hash
* @param string $table
* @param string $key_clause
* @return bool
* @access public
*/
public function doUpdate($fields_hash, $table, $key_clause)
{
$conn =& $this->openConnection( $this->getMasterIndex() );
return $conn->doUpdate($fields_hash, $table, $key_clause);
}
/**
* Allows to detect table's presence in database.
*
* @param string $table_name
* @param bool $force
* @return bool
* @access public
*/
public function TableFound($table_name, $force = false)
{
$conn =& $this->openConnection($this->lastUsedIndex);
return $conn->TableFound($table_name, $force);
}
/**
* Returns query processing statistics.
*
* @return Array
* @access public
*/
public function getQueryStatistics()
{
$conn =& $this->openConnection($this->lastUsedIndex);
return $conn->getQueryStatistics();
}
/**
* Get status information from SHOW STATUS in an associative array.
*
* @param string $which
* @return Array
* @access public
*/
public function getStatus($which = '%')
{
$conn =& $this->openConnection($this->lastUsedIndex);
return $conn->getStatus($which);
}
/**
* When undefined method is called, then send it directly to last used slave server connection
*
* @param string $name
* @param Array $arguments
* @return mixed
* @access public
*/
public function __call($name, $arguments)
{
$conn =& $this->openConnection($this->lastUsedIndex);
return call_user_func_array( Array (&$conn, $name), $arguments );
}
/**
* Returns appropriate connection based on sql
*
* @param string $sql
* @return kDBConnection
* @access protected
*/
protected function &chooseConnection($sql)
{
if ( $this->nextQueryFromMaster ) {
$this->nextQueryFromMaster = false;
$index = $this->getMasterIndex();
}
else {
- $sid = isset($this->Application->Session) ? $this->Application->GetSID() : '9999999999999999999999';
-
- if ( preg_match('/(^[ \t\r\n]*(ALTER|CREATE|DROP|RENAME|DELETE|DO|INSERT|LOAD|REPLACE|TRUNCATE|UPDATE))|ses_' . $sid . '/', $sql) ) {
+ if ( preg_match('/(^[ \t\r\n]*(ALTER|CREATE|DROP|RENAME|DELETE|DO|INSERT|LOAD|REPLACE|TRUNCATE|UPDATE))|ses_[\d]+/', $sql) ) {
$index = $this->getMasterIndex();
}
else {
$index = $this->getSlaveIndex();
}
}
$this->lastUsedIndex = $index;
$conn =& $this->openConnection($index);
return $conn;
}
/**
* Get slave replication lag. It will only work if the DB user has the PROCESS privilege.
*
* @return int
* @access public
*/
public function getSlaveLag()
{
$conn =& $this->openConnection($this->lastUsedIndex);
return $conn->getSlaveLag();
}
/**
* Sets an error handler.
*
* @param callable $error_handler Error handler.
*
* @return void
*/
public function setErrorHandler(callable $error_handler)
{
$this->errorHandler = $error_handler;
foreach ( $this->connections as $connection ) {
$connection->setErrorHandler($error_handler);
}
}
}
Index: branches/5.2.x/core/kernel/db/db_event_handler.php
===================================================================
--- branches/5.2.x/core/kernel/db/db_event_handler.php (revision 16796)
+++ branches/5.2.x/core/kernel/db/db_event_handler.php (revision 16797)
@@ -1,3529 +1,3535 @@
<?php
/**
* @version $Id$
* @package In-Portal
* @copyright Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license GNU/GPL
* In-Portal is Open Source software.
* This means that this software may have been modified pursuant
* the GNU General Public License, and as distributed it includes
* or is derivative of works licensed under the GNU General Public License
* or other free or open source software licenses.
* See http://www.in-portal.org/license for copyright notices and details.
*/
defined('FULL_PATH') or die('restricted access!');
define('EH_CUSTOM_PROCESSING_BEFORE',1);
define('EH_CUSTOM_PROCESSING_AFTER',2);
/**
* Note:
* 1. When addressing variables from submit containing
* Prefix_Special as part of their name use
* $event->getPrefixSpecial(true) instead of
* $event->getPrefixSpecial() as usual. This is due PHP
* is converting "." symbols in variable names during
* submit info "_". $event->getPrefixSpecial optional
* 1st parameter returns correct current Prefix_Special
* for variables being 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->getPrefixSpecial().'_varname')
*
*/
/**
* EventHandler that is used to process
* any database related events
*
*/
class kDBEventHandler extends kEventHandler {
/**
* Checks permissions of user
*
* @param kEvent $event
* @return bool
* @access public
*/
public function CheckPermission(kEvent $event)
{
$section = $event->getSection();
if ( !$this->Application->isAdmin ) {
$allow_events = Array ('OnSearch', 'OnSearchReset', 'OnNew');
if ( in_array($event->Name, $allow_events) ) {
// allow search on front
return true;
}
}
elseif ( ($event->Name == 'OnPreSaveAndChangeLanguage') && !$this->UseTempTables($event) ) {
// allow changing language in grids, when not in editing mode
return $this->Application->CheckPermission($section . '.view', 1);
}
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 standard permission mapping
*
* @return void
* @access protected
* @see kEventHandler::$permMapping
*/
protected function mapPermissions()
{
parent::mapPermissions();
$permissions = Array (
'OnLoad' => Array ('self' => 'view', 'subitem' => 'view'),
'OnItemBuild' => Array ('self' => 'view', 'subitem' => 'view'),
'OnSuggestValues' => Array ('self' => 'admin', 'subitem' => 'admin'),
'OnSuggestValuesJSON' => Array ('self' => 'admin', 'subitem' => 'admin'),
'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'),
'OnDeleteAll' => 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'),
'OnStoreSelected' => 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'),
'OnDeleteExportPreset' => array('self' => 'view'),
'OnExport' => Array ('self' => 'view|advanced:export'),
'OnExportBegin' => Array ('self' => 'view|advanced:export'),
'OnExportProgress' => Array ('self' => 'view|advanced:export'),
'OnExportCancel' => Array ('self' => 'view|advanced:export'),
'OnSetAutoRefreshInterval' => Array ('self' => true, 'subitem' => true),
'OnAutoRefreshToggle' => Array ('self' => true, 'subitem' => true),
// 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),
'OnResetSorting' => 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),
'OnSetPage' => 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),
'OnDeleteFile' => Array ('self' => true, 'subitem' => true),
'OnViewFile' => Array ('self' => true, 'subitem' => true),
'OnSaveWidths' => Array ('self' => 'admin', 'subitem' => 'admin'),
'OnValidateMInputFields' => Array ('self' => 'view'),
'OnValidateField' => Array ('self' => true, 'subitem' => true),
);
$this->permMapping = array_merge($this->permMapping, $permissions);
}
/**
* Define alternative event processing method names
*
* @return void
* @see kEventHandler::$eventMethods
* @access protected
*/
protected 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
* @access public
*/
public function getPassedID(kEvent $event)
{
if ( $event->getEventParam('raise_warnings') === false ) {
$event->setEventParam('raise_warnings', 1);
}
if ( $event->Special == 'previous' || $event->Special == 'next' ) {
/** @var kDBItem $object */
$object = $this->Application->recallObject($event->getEventParam('item'));
/** @var ListHelper $list_helper */
$list_helper = $this->Application->recallObject('ListHelper');
$select_clause = $this->Application->getUnitOption($object->Prefix, 'NavigationSelectClause', NULL);
return $list_helper->getNavigationResource($object, $event->getEventParam('list'), $event->Special == 'next', $select_clause);
}
elseif ( $event->Special == 'filter' ) {
// temporary object, used to print filter options only
return 0;
}
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)
/** @var kDBItem $main_object */
$main_object = $this->Application->recallObject($regs[1]);
$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 !== false) && ($ret != '') ) {
$event->setEventParam(kEvent::FLAG_ID_FROM_REQUEST, true);
return $ret;
}
// 2. get id from env (used in front)
$ret = $this->Application->GetVar($event->getPrefixSpecial() . '_id');
if ( ($ret !== false) && ($ret != '') ) {
$event->setEventParam(kEvent::FLAG_ID_FROM_REQUEST, true);
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);
$event->setEventParam(kEvent::FLAG_ID_FROM_REQUEST, true);
}
}
else { // if selected ids are not yet stored
$this->StoreSelectedIDs($event);
// StoreSelectedIDs sets this variable.
$ret = $this->Application->GetVar($event->getPrefixSpecial() . '_id');
if ( ($ret !== false) && ($ret != '') ) {
$event->setEventParam(kEvent::FLAG_ID_FROM_REQUEST, true);
return $ret;
}
}
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 $direct_ids
* @return Array
* @access protected
*/
protected function StoreSelectedIDs(kEvent $event, $direct_ids = NULL)
{
$wid = $this->Application->GetTopmostWid($event->Prefix);
$session_name = rtrim($event->getPrefixSpecial() . '_selected_ids_' . $wid, '_');
$ids = $event->getEventParam('ids');
if ( isset($direct_ids) || ($ids !== false) ) {
// save ids directly if they given + reset array indexes
$resulting_ids = $direct_ids ? array_values($direct_ids) : ($ids ? array_values($ids) : false);
if ( $resulting_ids ) {
$this->Application->SetVar($event->getPrefixSpecial() . '_selected_ids', implode(',', $resulting_ids));
$this->Application->LinkVar($event->getPrefixSpecial() . '_selected_ids', $session_name, '', true);
$this->Application->SetVar($event->getPrefixSpecial() . '_id', $resulting_ids[0]);
return $resulting_ids;
}
return Array ();
}
$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, '', !$ret); // optional when IDs are missing
// 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 <strong>' . $event->getPrefixSpecial() . '</strong> <span class="debug_error">not passed</span>', E_USER_NOTICE);
}
$this->Application->SetVar($event->getPrefixSpecial() . '_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
* @access protected
*/
protected function getSelectedIDs(kEvent $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);
}
/**
* Stores IDs, selected in grid in session
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnStoreSelected(kEvent $event)
{
$this->StoreSelectedIDs($event);
$id = $this->Application->GetVar($event->getPrefixSpecial() . '_id');
if ( $id !== false ) {
$event->SetRedirectParam($event->getPrefixSpecial() . '_id', $id);
$event->SetRedirectParam('pass', 'all,' . $event->getPrefixSpecial());
}
}
/**
* Returns 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
* @return Array
* @access protected
*/
protected function getSubmittedFields(kEvent $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
* @return void
* @access protected
*/
protected function clearSelectedIDs(kEvent $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
}
/**
* Common builder part for Item & List
*
* @param kDBBase|kDBItem|kDBList $object
* @param kEvent $event
* @return void
* @access protected
*/
protected function dbBuild(&$object, kEvent $event)
{
// for permission checking inside item/list build events
$event->setEventParam('top_prefix', $this->Application->GetTopmostPrefix($event->Prefix, true));
if ( $event->getEventParam('form_name') !== false ) {
$form_name = $event->getEventParam('form_name');
}
else {
$request_forms = $this->Application->GetVar('forms', Array ());
$form_name = (string)getArrayValue($request_forms, $object->getPrefixSpecial());
}
$object->Configure($event->getEventParam('populate_ml_fields') || $this->Application->getUnitOption($event->Prefix, 'PopulateMlFields'), $form_name);
$this->PrepareObject($object, $event);
$parent_event = $event->getEventParam('parent_event');
if ( is_object($parent_event) ) {
$object->setParentEvent($parent_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->Application->setEvent($event->getPrefixSpecial(), '');
$save_event = $this->UseTempTables($event) && $this->Application->GetTopmostPrefix($event->Prefix) == $event->Prefix ? 'OnSave' : 'OnUpdate';
$this->Application->SetVar($event->getPrefixSpecial() . '_SaveEvent', $save_event);
}
/**
* Checks, that currently loaded item is allowed for viewing (non permission-based)
*
* @param kEvent $event
* @return bool
* @access protected
*/
protected function checkItemStatus(kEvent $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' ) {
/** @var kDBItem $object */
$object = $event->getObject();
if ( !$object->isLoaded() ) {
return true;
}
return $object->GetDBField($status_field) == STATUS_ACTIVE;
}
return true;
}
/**
* Shows not found template content
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function _errorNotFound(kEvent $event)
{
if ( $event->getEventParam('raise_warnings') === 0 ) {
// when it's possible, that autoload fails do nothing
return;
}
if ( $this->Application->isDebugMode() ) {
$this->Application->Debugger->appendTrace();
}
trigger_error('ItemLoad Permission Failed for prefix [' . $event->getPrefixSpecial() . '] in <strong>checkItemStatus</strong>, leading to "404 Not Found"', E_USER_NOTICE);
$this->Application->UrlManager->show404();
}
/**
* Builds item (loads if needed)
*
* Pattern: Prototype Manager
*
* @param kEvent $event
* @access protected
*/
protected function OnItemBuild(kEvent $event)
{
/** @var kDBItem $object */
$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_autoload = $event->getEventParam('skip_autoload');
if ( $auto_load && !$skip_autoload ) {
$perm_status = true;
$user_id = $this->Application->InitDone ? $this->Application->RecallVar('user_id') : USER_ROOT;
$event->setEventParam('top_prefix', $this->Application->GetTopmostPrefix($event->Prefix, true));
$status_checked = false;
if ( $this->Application->permissionCheckingDisabled($user_id) || $this->CheckPermission($event) ) {
// Don't autoload item, when user doesn't have view permission.
$this->LoadItem($event);
$status_checked = true;
$editing_mode = defined('EDITING_MODE') ? EDITING_MODE : false;
$id_from_request = $event->getEventParam(kEvent::FLAG_ID_FROM_REQUEST);
if ( !$this->Application->permissionCheckingDisabled($user_id)
&& !$this->Application->isAdmin
&& !($editing_mode || ($id_from_request ? $this->checkItemStatus($event) : true))
) {
// Permissions are being checked AND on Front-End AND (not editing mode || incorrect status).
$perm_status = false;
}
}
else {
$perm_status = false;
}
if ( !$perm_status ) {
// when no permission to view item -> redirect to no permission template
$this->_processItemLoadingError($event, $status_checked);
}
}
/** @var Params $actions */
$actions = $this->Application->recallObject('kActions');
$actions->Set($event->getPrefixSpecial() . '_GoTab', '');
$actions->Set($event->getPrefixSpecial() . '_GoId', '');
$actions->Set('forms[' . $event->getPrefixSpecial() . ']', $object->getFormName());
}
/**
* Processes case, when item wasn't loaded because of lack of permissions
*
* @param kEvent $event
* @param bool $status_checked
* @throws kNoPermissionException
* @return void
* @access protected
*/
protected function _processItemLoadingError($event, $status_checked)
{
$current_template = $this->Application->GetVar('t');
$redirect_template = $this->Application->isAdmin ? 'no_permission' : $this->Application->ConfigValue('NoPermissionTemplate');
$error_msg = 'ItemLoad Permission Failed for prefix [' . $event->getPrefixSpecial() . '] in <strong>' . ($status_checked ? 'checkItemStatus' : 'CheckPermission') . '</strong>';
if ( $current_template == $redirect_template ) {
// don't perform "no_permission" redirect if already on a "no_permission" template
if ( $this->Application->isDebugMode() ) {
$this->Application->Debugger->appendTrace();
}
trigger_error($error_msg, E_USER_NOTICE);
return;
}
if ( MOD_REWRITE ) {
$redirect_params = Array (
'm_cat_id' => 0,
'next_template' => 'external:' . $_SERVER['REQUEST_URI'],
'pass' => 'm',
);
}
else {
$redirect_params = Array (
'next_template' => $current_template,
'pass' => 'm',
);
}
$exception = new kNoPermissionException($error_msg);
$exception->setup($redirect_template, $redirect_params);
throw $exception;
}
/**
* Build sub-tables array from configs
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnTempHandlerBuild(kEvent $event)
{
/** @var kTempTablesHandler $object */
$object = $this->Application->recallObject($event->getPrefixSpecial() . '_TempHandler', 'kTempTablesHandler');
/** @var kEvent $parent_event */
$parent_event = $event->getEventParam('parent_event');
if ( is_object($parent_event) ) {
$object->setParentEvent($parent_event);
}
$object->BuildTables($event->Prefix, $this->getSelectedIDs($event));
}
/**
* Checks, that object used in event should use temp tables
*
* @param kEvent $event
* @return bool
* @access protected
*/
protected function UseTempTables(kEvent $event)
{
$top_prefix = $this->Application->GetTopmostPrefix($event->Prefix); // passed parent, not always actual
$special = ($top_prefix == $event->Prefix) ? $event->Special : $this->getMainSpecial($event);
return $this->Application->IsTempMode($event->Prefix, $special);
}
/**
* Load item if id is available
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function LoadItem(kEvent $event)
{
/** @var kDBItem $object */
$object = $event->getObject();
$id = $this->getPassedID($event);
if ( $object->isLoaded() && !is_array($id) && ($object->GetID() == $id) ) {
// object is already loaded by same id
return ;
}
if ( $object->Load($id) ) {
/** @var Params $actions */
$actions = $this->Application->recallObject('kActions');
$actions->Set($event->getPrefixSpecial() . '_id', $object->GetID());
}
else {
$object->setID( is_array($id) ? false : $id );
}
}
/**
* Builds list
*
* Pattern: Prototype Manager
*
* @param kEvent $event
* @access protected
*/
protected function OnListBuild(kEvent $event)
{
/** @var kDBList $object */
$object = $event->getObject();
/*if ( $this->Application->isDebugMode() ) {
$event_params = http_build_query($event->getEventParams());
$this->Application->Debugger->appendHTML('InitList "<strong>' . $event->getPrefixSpecial() . '</strong>" (' . $event_params . ')');
}*/
$this->dbBuild($object, $event);
if ( !$object->isMainList() && $event->getEventParam('main_list') ) {
// once list is set to main, then even "requery" parameter can't remove that
/*$passed = $this->Application->GetVar('passed');
$this->Application->SetVar('passed', $passed . ',' . $event->Prefix);*/
$object->becameMain();
}
$object->setGridName($event->getEventParam('grid'));
$sql = $this->ListPrepareQuery($event);
$sql = $this->Application->ReplaceLanguageTags($sql);
$object->setSelectSQL($sql);
$object->reset();
if ( $event->getEventParam('skip_parent_filter') === false ) {
$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);
/** @var Params $actions */
$actions = $this->Application->recallObject('kActions');
$actions->Set('remove_specials[' . $event->getPrefixSpecial() . ']', '0');
$actions->Set($event->getPrefixSpecial() . '_GoTab', '');
}
/**
* Returns special of main item for linking with sub-item
*
* @param kEvent $event
* @return string
* @access protected
*/
protected function getMainSpecial(kEvent $event)
{
$main_special = $event->getEventParam('main_special');
if ( $main_special === false ) {
// main item's special not passed
if ( substr($event->Special, -5) == '-item' ) {
// temp handler added "-item" to given special -> process that here
return substr($event->Special, 0, -5);
}
// by default subitem's special is used for main item searching
return $event->Special;
}
return $main_special;
}
/**
* Apply any custom changes to list's sql query
*
* @param kEvent $event
* @return void
* @access protected
* @see kDBEventHandler::OnListBuild()
*/
protected function SetCustomQuery(kEvent $event)
{
}
/**
* Set's new per-page for grid
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnSetPerPage(kEvent $event)
{
$per_page = $this->Application->GetVar($event->getPrefixSpecial(true) . '_PerPage');
$event->SetRedirectParam($event->getPrefixSpecial() . '_PerPage', $per_page);
$event->SetRedirectParam('pass', 'all,' . $event->getPrefixSpecial());
if ( !$this->Application->isAdminUser ) {
/** @var ListHelper $list_helper */
$list_helper = $this->Application->recallObject('ListHelper');
$this->_passListParams($event, 'per_page');
}
}
/**
* Occurs when page is changed (only for hooking)
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnSetPage(kEvent $event)
{
$page = $this->Application->GetVar($event->getPrefixSpecial(true) . '_Page');
$event->SetRedirectParam($event->getPrefixSpecial() . '_Page', $page);
$event->SetRedirectParam('pass', 'all,' . $event->getPrefixSpecial());
if ( !$this->Application->isAdminUser ) {
$this->_passListParams($event, 'page');
}
}
/**
* Passes through main list pagination and sorting
*
* @param kEvent $event
* @param string $skip_var
* @return void
* @access protected
*/
protected function _passListParams($event, $skip_var)
{
$param_names = array_diff(Array ('page', 'per_page', 'sort_by'), Array ($skip_var));
/** @var ListHelper $list_helper */
$list_helper = $this->Application->recallObject('ListHelper');
foreach ($param_names as $param_name) {
$value = $this->Application->GetVar($param_name);
switch ($param_name) {
case 'page':
if ( $value > 1 ) {
$event->SetRedirectParam('page', $value);
}
break;
case 'per_page':
if ( $value > 0 ) {
if ( $value != $list_helper->getDefaultPerPage($event->Prefix) ) {
$event->SetRedirectParam('per_page', $value);
}
}
break;
case 'sort_by':
$event->setPseudoClass('_List');
/** @var kDBList $object */
$object = $event->getObject(Array ('main_list' => 1));
if ( $list_helper->hasUserSorting($object) ) {
$event->SetRedirectParam('sort_by', $value);
}
break;
}
}
}
/**
* Set's correct page for list based on data provided with event
*
* @param kEvent $event
* @return void
* @access protected
* @see kDBEventHandler::OnListBuild()
*/
protected function SetPagination(kEvent $event)
{
/** @var kDBList $object */
$object = $event->getObject();
// get PerPage (forced -> session -> config -> 10)
$object->SetPerPage($this->getPerPage($event));
// Main lists on Front-End have special get parameter for page.
if ( $object->isMainList() ) {
$page = $this->Application->GetVarFiltered('page', false, FILTER_VALIDATE_INT);
}
else {
$page = false;
}
if ( !$page ) {
// Page is given in "env" variable for given prefix.
$page = $this->Application->GetVarFiltered(
$event->getPrefixSpecial() . '_Page',
false,
FILTER_VALIDATE_INT
);
}
if ( !$page && $event->Special ) {
/*
* When not part of env, then variables like "prefix.special_Page" are
* replaced (by PHP) with "prefix_special_Page", so check for that too.
*/
$page = $this->Application->GetVarFiltered(
$event->getPrefixSpecial(true) . '_Page',
false,
FILTER_VALIDATE_INT
);
}
if ( !$object->isMainList() ) {
// main lists doesn't use session for page storing
$this->Application->StoreVarDefault($event->getPrefixSpecial() . '_Page', 1, true); // true for optional
if ( $page ) {
// page found in request -> store in session
$this->Application->StoreVar($event->getPrefixSpecial() . '_Page', $page, true); //true for optional
}
else {
// page not found in request -> get from session
$page = $this->Application->RecallVar($event->getPrefixSpecial() . '_Page');
}
if ( !$event->getEventParam('skip_counting') ) {
// when stored page is larger, then maximal list page number
// (such case is also processed in kDBList::Query method)
$pages = $object->GetTotalPages();
if ( $page > $pages ) {
$page = 1;
$this->Application->StoreVar($event->getPrefixSpecial() . '_Page', 1, true);
}
}
}
$object->SetPage($page);
}
/**
* Returns current per-page setting for list
*
* @param kEvent $event
* @return int
* @access protected
*/
protected function getPerPage(kEvent $event)
{
/** @var kDBList $object */
$object = $event->getObject();
$per_page = $event->getEventParam('per_page');
if ( $per_page ) {
// per-page is passed as tag parameter to PrintList, InitList, etc.
$config_mapping = $this->Application->getUnitOption($event->Prefix, 'ConfigMapping');
// 2. per-page setting is stored in configuration variable
if ( $config_mapping ) {
// such pseudo per-pages are only defined in templates directly
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;
}
}
return $per_page;
}
if ( !$per_page && $object->isMainList() ) {
// Main lists on Front-End have special get parameter for per-page.
$per_page = $this->Application->GetVarFiltered(
'per_page',
false,
FILTER_VALIDATE_INT
);
}
if ( !$per_page ) {
// Per-page is given in "env" variable for given prefix.
$per_page = $this->Application->GetVarFiltered(
$event->getPrefixSpecial() . '_PerPage',
false,
FILTER_VALIDATE_INT
);
}
if ( !$per_page && $event->Special ) {
/*
* When not part of env, then variables like "prefix.special_PerPage" are
* replaced (by PHP) with "prefix_special_PerPage", so check for that too.
*/
$per_page = $this->Application->GetVarFiltered(
$event->getPrefixSpecial(true) . '_PerPage',
false,
FILTER_VALIDATE_INT
);
}
if ( !$object->isMainList() ) {
// per-page given in env and not in main list
$view_name = $this->Application->RecallVar($event->getPrefixSpecial() . '_current_view');
if ( $per_page ) {
// per-page found in request -> store in session and persistent session
$this->setListSetting($event, 'PerPage', $per_page);
}
else {
// per-page not found in request -> get from pesistent session (or session)
$per_page = $this->getListSetting($event, 'PerPage');
}
}
if ( !$per_page ) {
// per page wan't found in request/session/persistent session
/** @var ListHelper $list_helper */
$list_helper = $this->Application->recallObject('ListHelper');
// allow to override default per-page value from tag
$default_per_page = $event->getEventParam('default_per_page');
if ( !is_numeric($default_per_page) ) {
$default_per_page = $this->Application->ConfigValue('DefaultGridPerPage');
}
$per_page = $list_helper->getDefaultPerPage($event->Prefix, $default_per_page);
}
return $per_page;
}
/**
* Set's correct sorting for list based on data provided with event
*
* @param kEvent $event
* @return void
* @access protected
* @see kDBEventHandler::OnListBuild()
*/
protected function SetSorting(kEvent $event)
{
$event->setPseudoClass('_List');
/** @var kDBList $object */
$object = $event->getObject();
if ( $object->isMainList() ) {
$sort_by = $this->Application->GetVarFiltered(
'sort_by',
false,
FILTER_CALLBACK,
array('options' => array($this, 'sortByFilterCallback'))
);
$cur_sort1 = $cur_sort1_dir = $cur_sort2 = $cur_sort2_dir = false;
if ( $sort_by ) {
$sortings = explode('|', $sort_by);
list ($cur_sort1, $cur_sort1_dir) = explode(',', $sortings[0]);
if ( isset($sortings[1]) ) {
list ($cur_sort2, $cur_sort2_dir) = explode(',', $sortings[1]);
}
}
}
else {
$sorting_settings = $this->getListSetting($event, 'Sortings');
$cur_sort1 = getArrayValue($sorting_settings, 'Sort1');
$cur_sort1_dir = getArrayValue($sorting_settings, 'Sort1_Dir');
$cur_sort2 = getArrayValue($sorting_settings, 'Sort2');
$cur_sort2_dir = getArrayValue($sorting_settings, 'Sort2_Dir');
}
$tag_sort_by = $event->getEventParam('sort_by');
if ( $tag_sort_by ) {
if ( $tag_sort_by == 'random' ) {
$object->AddOrderField('RAND()', '');
}
else {
// multiple sortings could be specified at once
$tag_sort_by = explode('|', $tag_sort_by);
foreach ($tag_sort_by as $sorting_element) {
list ($by, $dir) = explode(',', $sorting_element);
$object->AddOrderField($by, $dir);
}
}
}
$list_sortings = $this->_getDefaultSorting($event);
// use default if not specified in session
if ( !$cur_sort1 || !$cur_sort1_dir ) {
$sorting = getArrayValue($list_sortings, 'Sorting');
if ( $sorting ) {
reset($sorting);
$cur_sort1 = key($sorting);
$cur_sort1_dir = current($sorting);
if ( next($sorting) ) {
$cur_sort2 = key($sorting);
$cur_sort2_dir = current($sorting);
}
}
}
// always add forced sorting before any user sorting fields
/** @var Array $forced_sorting */
$forced_sorting = getArrayValue($list_sortings, 'ForcedSorting');
if ( $forced_sorting ) {
foreach ($forced_sorting as $field => $dir) {
$object->AddOrderField($field, $dir);
}
}
// add user sorting fields
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);
}
}
/**
* Filters the "sort_by" request variable.
*
* @param string|boolean $value Value.
*
* @return string|boolean
*/
public function sortByFilterCallback($value)
{
if ( !$value ) {
return false;
}
$sortings = array_filter(
explode('|', $value),
function ($sorting) {
return preg_match('/^[a-z_][a-z0-9_]*,(asc|desc)$/i', $sorting);
}
);
return $sortings ? implode('|', $sortings) : false;
}
/**
* Returns default list sortings
*
* @param kEvent $event
* @return Array
* @access protected
*/
protected function _getDefaultSorting(kEvent $event)
{
$list_sortings = $this->Application->getUnitOption($event->Prefix, 'ListSortings', Array ());
$sorting_prefix = array_key_exists($event->Special, $list_sortings) ? $event->Special : '';
$sorting_configs = $this->Application->getUnitOption($event->Prefix, 'ConfigMapping');
if ( $sorting_configs && array_key_exists('DefaultSorting1Field', $sorting_configs) ) {
// sorting defined in configuration variables overrides one from unit config
$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']),
);
// TODO: lowercase configuration variable values in db, instead of here
$list_sortings[$sorting_prefix]['Sorting'] = array_map('strtolower', $list_sortings[$sorting_prefix]['Sorting']);
}
return isset($list_sortings[$sorting_prefix]) ? $list_sortings[$sorting_prefix] : Array ();
}
/**
* Gets list setting by name (persistent or real session)
*
* @param kEvent $event
* @param string $variable_name
* @return string|Array
* @access protected
*/
protected function getListSetting(kEvent $event, $variable_name)
{
$view_name = $this->Application->RecallVar($event->getPrefixSpecial() . '_current_view');
$storage_prefix = $event->getEventParam('same_special') ? $event->Prefix : $event->getPrefixSpecial();
// get sorting from persistent session
$default_value = $this->Application->isAdmin ? ALLOW_DEFAULT_SETTINGS : false;
$variable_value = $this->Application->RecallPersistentVar($storage_prefix . '_' . $variable_name . '.' . $view_name, $default_value);
/*if ( !$variable_value ) {
// get sorting from session
$variable_value = $this->Application->RecallVar($storage_prefix . '_' . $variable_name);
}*/
if ( kUtil::IsSerialized($variable_value) ) {
$variable_value = unserialize($variable_value);
}
return $variable_value;
}
/**
* Sets list setting by name (persistent and real session)
*
* @param kEvent $event
* @param string $variable_name
* @param string|Array $variable_value
* @return void
* @access protected
*/
protected function setListSetting(kEvent $event, $variable_name, $variable_value = NULL)
{
$view_name = $this->Application->RecallVar($event->getPrefixSpecial() . '_current_view');
// $this->Application->StoreVar($event->getPrefixSpecial() . '_' . $variable_name, $variable_value, true); //true for optional
if ( isset($variable_value) ) {
if ( is_array($variable_value) ) {
$variable_value = serialize($variable_value);
}
$this->Application->StorePersistentVar($event->getPrefixSpecial() . '_' . $variable_name . '.' . $view_name, $variable_value, true); //true for optional
}
else {
$this->Application->RemovePersistentVar($event->getPrefixSpecial() . '_' . $variable_name . '.' . $view_name);
}
}
/**
* Add filters found in session
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function AddFilters(kEvent $event)
{
/** @var kDBList $object */
$object = $event->getObject();
- $edit_mark = rtrim($this->Application->GetSID() . '_' . $this->Application->GetTopmostWid($event->Prefix), '_');
+ if ( $object->IsTempTable() ) {
+ $session_id = $this->Application->GetSID(Session::PURPOSE_REFERENCE);
+ $edit_mark = rtrim($session_id . '_' . $this->Application->GetTopmostWid($event->Prefix), '_');
+ }
+ else {
+ $edit_mark = '';
+ }
// 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') ? kDBList::HAVING_FILTER : kDBList::WHERE_FILTER;
$filter_value = str_replace(EDIT_MARK, $edit_mark, $filter_params['value']);
$object->addFilter($filter_field, $filter_value, $filter_type, kDBList::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) {
$field_options = current($field_options);
if ( isset($field_options['value']) && $field_options['value'] ) {
$filter_type = ($field_options['sql_filter_type'] == 'having') ? kDBList::HAVING_FILTER : kDBList::WHERE_FILTER;
$filter_value = str_replace(EDIT_MARK, $edit_mark, $field_options['value']);
$object->addFilter($field_name, $filter_value, $filter_type, kDBList::FLT_CUSTOM);
}
}
}
}
// add view filter
$view_filter = $this->Application->RecallVar($event->getPrefixSpecial() . '_view_filter');
if ( $view_filter ) {
$view_filter = unserialize($view_filter);
/** @var kMultipleFilter $temp_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('kDBList::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'], kDBList::FLT_VIEW);
$group_key++;
}
}
// add item filter
if ( $object->isMainList() ) {
$this->applyItemFilters($event);
}
}
/**
* Applies item filters
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function applyItemFilters($event)
{
$filter_values = $this->Application->GetVar('filters', Array ());
if ( !$filter_values ) {
return;
}
/** @var kDBList $object */
$object = $event->getObject();
$where_clause = Array (
'ItemPrefix = ' . $this->Conn->qstr($object->Prefix),
'FilterField IN (' . implode(',', $this->Conn->qstrArray(array_keys($filter_values))) . ')',
'Enabled = 1',
);
$sql = 'SELECT *
FROM ' . $this->Application->getUnitOption('item-filter', 'TableName') . '
WHERE (' . implode(') AND (', $where_clause) . ')';
$filters = $this->Conn->Query($sql, 'FilterField');
foreach ($filters as $filter_field => $filter_data) {
$filter_value = $filter_values[$filter_field];
if ( "$filter_value" === '' ) {
// ListManager don't pass empty values, but check here just in case
continue;
}
$table_name = $object->isVirtualField($filter_field) ? '' : '%1$s.';
switch ($filter_data['FilterType']) {
case 'radio':
$filter_value = $table_name . '`' . $filter_field . '` = ' . $this->Conn->qstr($filter_value);
break;
case 'checkbox':
$filter_value = explode('|', substr($filter_value, 1, -1));
$filter_value = $this->Conn->qstrArray($filter_value, 'escape');
if ( $object->GetFieldOption($filter_field, 'multiple') ) {
$filter_value = $table_name . '`' . $filter_field . '` LIKE "%|' . implode('|%" OR ' . $table_name . '`' . $filter_field . '` LIKE "%|', $filter_value) . '|%"';
}
else {
$filter_value = $table_name . '`' . $filter_field . '` IN (' . implode(',', $filter_value) . ')';
}
break;
case 'range':
$filter_value = $this->Conn->qstrArray(explode('-', $filter_value));
$filter_value = $table_name . '`' . $filter_field . '` BETWEEN ' . $filter_value[0] . ' AND ' . $filter_value[1];
break;
}
$object->addFilter('item_filter_' . $filter_field, $filter_value, $object->isVirtualField($filter_field) ? kDBList::HAVING_FILTER : kDBList::WHERE_FILTER);
}
}
/**
* Set's new sorting for list
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnSetSorting(kEvent $event)
{
$sorting_settings = $this->getListSetting($event, 'Sortings');
$cur_sort1 = getArrayValue($sorting_settings, 'Sort1');
$cur_sort1_dir = getArrayValue($sorting_settings, 'Sort1_Dir');
$use_double_sorting = $this->Application->ConfigValue('UseDoubleSorting');
if ( $use_double_sorting ) {
$cur_sort2 = getArrayValue($sorting_settings, 'Sort2');
$cur_sort2_dir = getArrayValue($sorting_settings, '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';
}
$sorting_settings = Array ('Sort1' => $cur_sort1, 'Sort1_Dir' => $cur_sort1_dir);
if ( $use_double_sorting ) {
$sorting_settings['Sort2'] = $cur_sort2;
$sorting_settings['Sort2_Dir'] = $cur_sort2_dir;
}
$this->setListSetting($event, 'Sortings', $sorting_settings);
}
/**
* Set sorting directly to session (used for category item sorting (front-end), grid sorting (admin, view menu)
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnSetSortingDirect(kEvent $event)
{
// used on Front-End in category item lists
$prefix_special = $event->getPrefixSpecial();
$combined = $this->Application->GetVar($event->getPrefixSpecial(true) . '_CombinedSorting');
if ( $combined ) {
list ($field, $dir) = explode('|', $combined);
if ( $this->Application->isAdmin || !$this->Application->GetVar('main_list') ) {
$this->setListSetting($event, 'Sortings', Array ('Sort1' => $field, 'Sort1_Dir' => $dir));
}
else {
$event->setPseudoClass('_List');
$this->Application->SetVar('sort_by', $field . ',' . $dir);
/** @var kDBList $object */
$object = $event->getObject(Array ('main_list' => 1));
/** @var ListHelper $list_helper */
$list_helper = $this->Application->recallObject('ListHelper');
$this->_passListParams($event, 'sort_by');
if ( $list_helper->hasUserSorting($object) ) {
$event->SetRedirectParam('sort_by', $field . ',' . strtolower($dir));
}
$event->SetRedirectParam('pass', 'm');
}
return;
}
// used in "View Menu -> Sort" menu in administrative console
$field_pos = $this->Application->GetVar($event->getPrefixSpecial(true) . '_SortPos');
$this->Application->LinkVar($event->getPrefixSpecial(true) . '_Sort' . $field_pos, $prefix_special . '_Sort' . $field_pos);
$this->Application->LinkVar($event->getPrefixSpecial(true) . '_Sort' . $field_pos . '_Dir', $prefix_special . '_Sort' . $field_pos . '_Dir');
}
/**
* Reset grid sorting to default (from config)
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnResetSorting(kEvent $event)
{
$this->setListSetting($event, 'Sortings');
}
/**
* Sets grid refresh interval
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnSetAutoRefreshInterval(kEvent $event)
{
$refresh_interval = $this->Application->GetVar('refresh_interval');
$view_name = $this->Application->RecallVar($event->getPrefixSpecial() . '_current_view');
$this->Application->StorePersistentVar($event->getPrefixSpecial() . '_refresh_interval.' . $view_name, $refresh_interval);
}
/**
* Changes auto-refresh state for grid
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnAutoRefreshToggle(kEvent $event)
{
$refresh_intervals = $this->Application->ConfigValue('AutoRefreshIntervals');
if ( !$refresh_intervals ) {
return;
}
$view_name = $this->Application->RecallVar($event->getPrefixSpecial() . '_current_view');
$auto_refresh = $this->Application->RecallPersistentVar($event->getPrefixSpecial() . '_auto_refresh.' . $view_name);
if ( $auto_refresh === false ) {
$refresh_intervals = explode(',', $refresh_intervals);
$this->Application->StorePersistentVar($event->getPrefixSpecial() . '_refresh_interval.' . $view_name, $refresh_intervals[0]);
}
$this->Application->StorePersistentVar($event->getPrefixSpecial() . '_auto_refresh.' . $view_name, $auto_refresh ? 0 : 1);
}
/**
* Creates needed sql query to load item,
* if no query is defined in config for
* special requested, then use list query
*
* @param kEvent $event
* @return string
* @access protected
*/
protected function ItemPrepareQuery(kEvent $event)
{
/** @var kDBItem $object */
$object = $event->getObject();
$sqls = $object->getFormOption('ItemSQLs', Array ());
$special = isset($sqls[$event->Special]) ? $event->Special : '';
// preferred special not found in ItemSQLs -> use analog from ListSQLs
return isset($sqls[$special]) ? $sqls[$special] : $this->ListPrepareQuery($event);
}
/**
* Creates needed sql query to load list,
* if no query is defined in config for
* special requested, then use default
* query
*
* @param kEvent $event
* @return string
* @access protected
*/
protected function ListPrepareQuery(kEvent $event)
{
/** @var kDBItem $object */
$object = $event->getObject();
$sqls = $object->getFormOption('ListSQLs', Array ());
return $sqls[array_key_exists($event->Special, $sqls) ? $event->Special : ''];
}
/**
* Apply custom processing to item
*
* @param kEvent $event
* @param string $type
* @return void
* @access protected
*/
protected function customProcessing(kEvent $event, $type)
{
}
/* Edit Events mostly used in Admin */
/**
* Creates new kDBItem
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnCreate(kEvent $event)
{
/** @var kDBItem $object */
$object = $event->getObject(Array ('skip_autoload' => true));
$items_info = $this->Application->GetVar($event->getPrefixSpecial(true));
if ( !$items_info ) {
return;
}
$id = key($items_info);
$field_values = $items_info[$id];
$object->setID($id);
$object->SetFieldsFromHash($field_values);
$event->setEventParam('form_data', $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')) ) {
$this->customProcessing($event, 'after');
$event->SetRedirectParam('opener', 'u');
return;
}
$event->redirect = false;
$event->status = kEvent::erFAIL;
$this->Application->SetVar($event->getPrefixSpecial() . '_SaveEvent', 'OnCreate');
}
/**
* Updates kDBItem
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnUpdate(kEvent $event)
{
if ( $this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1) ) {
$event->status = kEvent::erFAIL;
return;
}
$this->_update($event);
$event->SetRedirectParam('opener', 'u');
if ( $event->status == kEvent::erSUCCESS ) {
$this->saveChangesToLiveTable($event->Prefix);
}
}
/**
* Updates data in database based on request
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function _update(kEvent $event)
{
/** @var kDBItem $object */
$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);
$event->setEventParam('form_data', $field_values);
$this->customProcessing($event, 'before');
if ( $object->Update($id) ) {
$this->customProcessing($event, 'after');
$event->status = kEvent::erSUCCESS;
}
else {
$event->status = kEvent::erFAIL;
$event->redirect = false;
break;
}
}
}
}
/**
* Automatically saves data to live table after sub-item was updated in Content Mode.
*
* @param string $prefix Prefix.
*
* @return void
*/
protected function saveChangesToLiveTable($prefix)
{
$parent_prefix = $this->Application->getUnitOption($prefix, 'ParentPrefix');
if ( $parent_prefix === false ) {
return;
}
if ( $this->Application->GetVar('admin') && $this->Application->IsTempMode($parent_prefix) ) {
$this->Application->HandleEvent(new kEvent($parent_prefix . ':OnSave'));
}
}
/**
* Delete's kDBItem object
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnDelete(kEvent $event)
{
if ( $this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1) ) {
$event->status = kEvent::erFAIL;
return;
}
/** @var kTempTablesHandler $temp_handler */
$temp_handler = $this->Application->recallObject($event->getPrefixSpecial() . '_TempHandler', 'kTempTablesHandler', Array ('parent_event' => $event));
$temp_handler->DeleteItems($event->Prefix, $event->Special, Array ($this->getPassedID($event)));
}
/**
* Deletes all records from table
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnDeleteAll(kEvent $event)
{
$sql = 'SELECT ' . $this->Application->getUnitOption($event->Prefix, 'IDField') . '
FROM ' . $this->Application->getUnitOption($event->Prefix, 'TableName');
$ids = $this->Conn->GetCol($sql);
if ( $ids ) {
/** @var kTempTablesHandler $temp_handler */
$temp_handler = $this->Application->recallObject($event->getPrefixSpecial() . '_TempHandler', 'kTempTablesHandler', Array ('parent_event' => $event));
$temp_handler->DeleteItems($event->Prefix, $event->Special, $ids);
}
}
/**
* Prepares new kDBItem object
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnNew(kEvent $event)
{
/** @var kDBItem $object */
$object = $event->getObject(Array ('skip_autoload' => true));
$object->Clear(0);
$this->Application->SetVar($event->getPrefixSpecial() . '_SaveEvent', 'OnCreate');
if ( $event->getEventParam('top_prefix') != $event->Prefix ) {
// this is subitem prefix, so use main item special
$table_info = $object->getLinkedInfo($this->getMainSpecial($event));
}
else {
$table_info = $object->getLinkedInfo();
}
if ( $table_info !== false ) {
$object->SetDBField($table_info['ForeignKey'], $table_info['ParentId']);
}
$event->redirect = false;
}
/**
* Cancels kDBItem Editing/Creation
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnCancel(kEvent $event)
{
/** @var kDBItem $object */
$object = $event->getObject(Array ('skip_autoload' => true));
$items_info = $this->Application->GetVar($event->getPrefixSpecial(true));
if ( $items_info ) {
$delete_ids = Array ();
/** @var kTempTablesHandler $temp_handler */
$temp_handler = $this->Application->recallObject($event->getPrefixSpecial() . '_TempHandler', 'kTempTablesHandler', Array ('parent_event' => $event));
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_handler->DeleteItems($event->Prefix, $event->Special, $delete_ids);
}
}
$event->SetRedirectParam('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
* @return void
* @access protected
*/
protected function OnMassDelete(kEvent $event)
{
if ( $this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1) ) {
$event->status = kEvent::erFAIL;
return ;
}
/** @var kTempTablesHandler $temp_handler */
$temp_handler = $this->Application->recallObject($event->getPrefixSpecial() . '_TempHandler', 'kTempTablesHandler', Array ('parent_event' => $event));
$ids = $this->StoreSelectedIDs($event);
$event->setEventParam('ids', $ids);
$this->customProcessing($event, 'before');
$ids = $event->getEventParam('ids');
if ( $ids ) {
$temp_handler->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
* @return void
* @access protected
*/
protected function setTempWindowID(kEvent $event)
{
$prefixes = Array ($event->Prefix, $event->getPrefixSpecial(true));
foreach ($prefixes as $prefix) {
$mode = $this->Application->GetVar($prefix . '_mode');
if ($mode == 't') {
$wid = $this->Application->GetVar('m_wid');
$this->Application->SetVar(str_replace('_', '.', $prefix) . '_mode', 't' . $wid);
break;
}
}
}
/**
* Prepare temp tables and populate it
* with items selected in the grid
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnEdit(kEvent $event)
{
$this->setTempWindowID($event);
$ids = $this->StoreSelectedIDs($event);
/** @var kDBItem $object */
$object = $event->getObject(Array('skip_autoload' => true));
$object->setPendingActions(null, true);
$changes_var_name = $this->Prefix . '_changes_' . $this->Application->GetTopmostWid($this->Prefix);
$this->Application->RemoveVar($changes_var_name);
/** @var kTempTablesHandler $temp_handler */
$temp_handler = $this->Application->recallObject($event->getPrefixSpecial() . '_TempHandler', 'kTempTablesHandler', Array ('parent_event' => $event));
$temp_handler->PrepareEdit();
$event->SetRedirectParam('m_lang', $this->Application->GetDefaultLanguageId());
$event->SetRedirectParam($event->getPrefixSpecial() . '_id', array_shift($ids));
$event->SetRedirectParam('pass', 'all,' . $event->getPrefixSpecial());
$simultaneous_edit_message = $this->Application->GetVar('_simultaneous_edit_message');
if ( $simultaneous_edit_message ) {
$event->SetRedirectParam('_simultaneous_edit_message', $simultaneous_edit_message);
}
}
/**
* Saves content of temp table into live and
* redirects to event' default redirect (normally grid template)
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnSave(kEvent $event)
{
$event->CallSubEvent('OnPreSave');
if ( $event->status != kEvent::erSUCCESS ) {
return;
}
$skip_master = false;
/** @var kTempTablesHandler $temp_handler */
$temp_handler = $this->Application->recallObject($event->getPrefixSpecial() . '_TempHandler', 'kTempTablesHandler', Array ('parent_event' => $event));
$changes_var_name = $this->Prefix . '_changes_' . $this->Application->GetTopmostWid($this->Prefix);
if ( !$this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1) ) {
$live_ids = $temp_handler->SaveEdit($event->getEventParam('master_ids') ? $event->getEventParam('master_ids') : Array ());
if ( $live_ids === false ) {
// coping from table failed, because we have another coping process to same table, that wasn't finished
$event->status = kEvent::erFAIL;
return;
}
if ( $live_ids ) {
// ensure, that newly created item ids are available as if they were selected from grid
// NOTE: only works if main item has sub-items !!!
$this->StoreSelectedIDs($event, $live_ids);
}
/** @var kDBItem $object */
$object = $event->getObject();
$this->SaveLoggedChanges($changes_var_name, $object->ShouldLogChanges());
}
else {
$event->status = kEvent::erFAIL;
}
$this->clearSelectedIDs($event);
$event->SetRedirectParam('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', '');
}
/**
* Saves changes made in temporary table to log
*
* @param string $changes_var_name
* @param bool $save
* @return void
* @access public
*/
public function SaveLoggedChanges($changes_var_name, $save = true)
{
// 1. get changes, that were made
$changes = $this->Application->RecallVar($changes_var_name);
$changes = $changes ? unserialize($changes) : Array ();
$this->Application->RemoveVar($changes_var_name);
if (!$changes) {
// no changes, skip processing
return ;
}
// TODO: 2. optimize change log records (replace multiple changes to same record with one change record)
$to_increment = Array ();
// 3. collect serials to reset based on foreign keys
foreach ($changes as $index => $rec) {
if (array_key_exists('DependentFields', $rec)) {
foreach ($rec['DependentFields'] as $field_name => $field_value) {
// will be "ci|ItemResourceId:345"
$to_increment[] = $rec['Prefix'] . '|' . $field_name . ':' . $field_value;
// also reset sub-item prefix general serial
$to_increment[] = $rec['Prefix'];
}
unset($changes[$index]['DependentFields']);
}
unset($changes[$index]['ParentId'], $changes[$index]['ParentPrefix']);
}
// 4. collect serials to reset based on changed ids
foreach ($changes as $change) {
$to_increment[] = $change['MasterPrefix'] . '|' . $change['MasterId'];
if ($change['MasterPrefix'] != $change['Prefix']) {
// also reset sub-item prefix general serial
$to_increment[] = $change['Prefix'];
// will be "ci|ItemResourceId"
$to_increment[] = $change['Prefix'] . '|' . $change['ItemId'];
}
}
// 5. reset serials collected before
$to_increment = array_unique($to_increment);
$this->Application->incrementCacheSerial($this->Prefix);
foreach ($to_increment as $to_increment_mixed) {
if (strpos($to_increment_mixed, '|') !== false) {
list ($to_increment_prefix, $to_increment_id) = explode('|', $to_increment_mixed, 2);
$this->Application->incrementCacheSerial($to_increment_prefix, $to_increment_id);
}
else {
$this->Application->incrementCacheSerial($to_increment_mixed);
}
}
// save changes to database
$sesion_log_id = $this->Application->RecallVar('_SessionLogId_');
if (!$save || !$sesion_log_id) {
// saving changes to database disabled OR related session log missing
return ;
}
$add_fields = Array (
'PortalUserId' => $this->Application->RecallVar('user_id'),
'SessionLogId' => $sesion_log_id,
);
$change_log_table = $this->Application->getUnitOption('change-log', 'TableName');
foreach ($changes as $rec) {
$this->Conn->doInsert(array_merge($rec, $add_fields), $change_log_table);
}
$this->Application->incrementCacheSerial('change-log');
$sql = 'UPDATE ' . $this->Application->getUnitOption('session-log', 'TableName') . '
SET AffectedItems = AffectedItems + ' . count($changes) . '
WHERE SessionLogId = ' . $sesion_log_id;
$this->Conn->Query($sql);
$this->Application->incrementCacheSerial('session-log');
}
/**
* Cancels edit
* Removes all temp tables and clears selected ids
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnCancelEdit(kEvent $event)
{
/** @var kTempTablesHandler $temp_handler */
$temp_handler = $this->Application->recallObject($event->getPrefixSpecial() . '_TempHandler', 'kTempTablesHandler', Array ('parent_event' => $event));
$temp_handler->CancelEdit();
$this->clearSelectedIDs($event);
$this->Application->RemoveVar($event->getPrefixSpecial() . '_modified');
$changes_var_name = $this->Prefix . '_changes_' . $this->Application->GetTopmostWid($this->Prefix);
$this->Application->RemoveVar($changes_var_name);
$event->SetRedirectParam('opener', 'u');
}
/**
* Allows to determine if we are creating new item or editing already created item
*
* @param kEvent $event
* @return bool
* @access public
*/
public function isNewItemCreate(kEvent $event)
{
/** @var kDBItem $object */
$object = $event->getObject( Array ('raise_warnings' => 0) );
return !$object->isLoaded();
}
/**
* Saves edited item into temp table
* If there is no id, new item is created in temp table
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnPreSave(kEvent $event)
{
// 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 ;
}
// don't just call OnUpdate event here, since it maybe overwritten to Front-End specific behavior
$this->_update($event);
}
/**
* Analog of OnPreSave event for usage in AJAX request
*
* @param kEvent $event
*
* @return void
*/
protected function OnPreSaveAjax(kEvent $event)
{
/** @var AjaxFormHelper $ajax_form_helper */
$ajax_form_helper = $this->Application->recallObject('AjaxFormHelper');
$ajax_form_helper->transitEvent($event, 'OnPreSave');
}
/**
* [HOOK] Saves sub-item
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnPreSaveSubItem(kEvent $event)
{
$not_created = $this->isNewItemCreate($event);
$event->CallSubEvent($not_created ? 'OnCreate' : 'OnUpdate');
if ( $event->status == kEvent::erSUCCESS ) {
/** @var kDBItem $object */
$object = $event->getObject();
$this->Application->SetVar($event->getPrefixSpecial() . '_id', $object->GetID());
}
else {
$event->MasterEvent->status = $event->status;
}
$event->SetRedirectParam('opener', 's');
}
/**
* Saves edited item in temp table and loads
* item with passed id in current template
* Used in Prev/Next buttons
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnPreSaveAndGo(kEvent $event)
{
$event->CallSubEvent('OnPreSave');
if ( $event->status == kEvent::erSUCCESS ) {
$id = $this->Application->GetVar($event->getPrefixSpecial(true) . '_GoId');
$event->SetRedirectParam($event->getPrefixSpecial() . '_id', $id);
}
}
/**
* Saves edited item in temp table and goes
* to passed tabs, by redirecting to it with OnPreSave event
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnPreSaveAndGoToTab(kEvent $event)
{
$event->CallSubEvent('OnPreSave');
if ( $event->status == kEvent::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
* @return void
* @access protected
*/
protected function OnUpdateAndGoToTab(kEvent $event)
{
$event->setPseudoClass('_List');
$event->CallSubEvent('OnUpdate');
if ( $event->status == kEvent::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
* @return void
* @access protected
*/
protected function OnPreCreate(kEvent $event)
{
$this->setTempWindowID($event);
$this->clearSelectedIDs($event);
$this->Application->SetVar('m_lang', $this->Application->GetDefaultLanguageId());
/** @var kDBItem $object */
$object = $event->getObject(Array ('skip_autoload' => true));
/** @var kTempTablesHandler $temp_handler */
$temp_handler = $this->Application->recallObject($event->Prefix . '_TempHandler', 'kTempTablesHandler', Array ('parent_event' => $event));
$temp_handler->PrepareEdit();
$object->setID(0);
$this->Application->SetVar($event->getPrefixSpecial() . '_id', 0);
$this->Application->SetVar($event->getPrefixSpecial() . '_PreCreate', 1);
$changes_var_name = $this->Prefix . '_changes_' . $this->Application->GetTopmostWid($this->Prefix);
$this->Application->RemoveVar($changes_var_name);
$event->redirect = false;
}
/**
* Creates a new item in temp table and
* stores item id in App vars and Session on success
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnPreSaveCreated(kEvent $event)
{
/** @var kDBItem $object */
$object = $event->getObject( Array('skip_autoload' => true) );
$object->setID(0);
$field_values = $this->getSubmittedFields($event);
$object->SetFieldsFromHash($field_values);
$event->setEventParam('form_data', $field_values);
$this->customProcessing($event, 'before');
if ( $object->Create() ) {
$this->customProcessing($event, 'after');
$event->SetRedirectParam($event->getPrefixSpecial(true) . '_id', $object->GetID());
}
else {
$event->status = kEvent::erFAIL;
$event->redirect = false;
}
}
/**
* Reloads form to loose all changes made during item editing
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnReset(kEvent $event)
{
//do nothing - should reset :)
if ( $this->isNewItemCreate($event) ) {
// just reset id to 0 in case it was create
/** @var kDBItem $object */
$object = $event->getObject( Array ('skip_autoload' => true) );
$object->setID(0);
$this->Application->SetVar($event->getPrefixSpecial() . '_id', 0);
}
}
/**
* Apply same processing to each item being selected in grid
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function iterateItems(kEvent $event)
{
if ( $this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1) ) {
$event->status = kEvent::erFAIL;
return ;
}
/** @var kDBItem $object */
$object = $event->getObject(Array ('skip_autoload' => true));
$ids = $this->StoreSelectedIDs($event);
if ( $ids ) {
$status_field = $object->getStatusField();
$order_field = $this->Application->getUnitOption($event->Prefix, 'OrderField');
if ( !$order_field ) {
$order_field = 'Priority';
}
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($order_field, $object->GetDBField($order_field) + 1);
break;
case 'OnMassMoveDown':
$object->SetDBField($order_field, $object->GetDBField($order_field) - 1);
break;
}
$object->Update();
}
}
$this->clearSelectedIDs($event);
}
/**
* Clones selected items in list
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnMassClone(kEvent $event)
{
if ( $this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1) ) {
$event->status = kEvent::erFAIL;
return;
}
/** @var kTempTablesHandler $temp_handler */
$temp_handler = $this->Application->recallObject($event->getPrefixSpecial() . '_TempHandler', 'kTempTablesHandler', Array ('parent_event' => $event));
$ids = $this->StoreSelectedIDs($event);
if ( $ids ) {
$temp_handler->CloneItems($event->Prefix, $event->Special, $ids);
}
$this->clearSelectedIDs($event);
}
/**
* Checks if given value is present in given array
*
* @param Array $records
* @param string $field
* @param mixed $value
* @return bool
* @access protected
*/
protected function check_array($records, $field, $value)
{
foreach ($records as $record) {
if ($record[$field] == $value) {
return true;
}
}
return false;
}
/**
* Saves data from editing form to database without checking required fields
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnPreSavePopup(kEvent $event)
{
/** @var kDBItem $object */
$object = $event->getObject();
$this->RemoveRequiredFields($object);
$event->CallSubEvent('OnPreSave');
$event->SetRedirectParam('opener', 'u');
}
/* End of Edit events */
// III. Events that allow to put some code before and after Update,Load,Create and Delete methods of item
/**
* Occurs before loading item, 'id' parameter
* allows to get id of item being loaded
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnBeforeItemLoad(kEvent $event)
{
}
/**
* Occurs after loading item, 'id' parameter
* allows to get id of item that was loaded
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnAfterItemLoad(kEvent $event)
{
}
/**
* Occurs before creating item
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnBeforeItemCreate(kEvent $event)
{
}
/**
* Occurs after creating item
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnAfterItemCreate(kEvent $event)
{
/** @var kDBItem $object */
$object = $event->getObject();
if ( !$object->IsTempTable() ) {
$this->_processPendingActions($event);
}
}
/**
* Occurs before updating item
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnBeforeItemUpdate(kEvent $event)
{
}
/**
* Occurs after updating item
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnAfterItemUpdate(kEvent $event)
{
/** @var kDBItem $object */
$object = $event->getObject();
if ( !$object->IsTempTable() ) {
$this->_processPendingActions($event);
}
}
/**
* Occurs before deleting item, id of item being
* deleted is stored as 'id' event param
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnBeforeItemDelete(kEvent $event)
{
}
/**
* Occurs after deleting item, id of deleted item
* is stored as 'id' param of event
*
* Also deletes subscriptions to that particual item once it's deleted
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnAfterItemDelete(kEvent $event)
{
/** @var kDBItem $object */
$object = $event->getObject();
// 1. delete direct subscriptions to item, that was deleted
$this->_deleteSubscriptions($event->Prefix, 'ItemId', $object->GetID());
/** @var Array $sub_items */
$sub_items = $this->Application->getUnitOption($event->Prefix, 'SubItems', Array ());
// 2. delete this item sub-items subscriptions, that reference item, that was deleted
foreach ($sub_items as $sub_prefix) {
$this->_deleteSubscriptions($sub_prefix, 'ParentItemId', $object->GetID());
}
}
/**
* Deletes all subscriptions, associated with given item
*
* @param string $prefix
* @param string $field
* @param int $value
* @return void
* @access protected
*/
protected function _deleteSubscriptions($prefix, $field, $value)
{
$sql = 'SELECT TemplateId
FROM ' . $this->Application->getUnitOption('email-template', 'TableName') . '
WHERE BindToSystemEvent REGEXP "' . $this->Conn->escape($prefix) . '(\\\\.[^:]*:.*|:.*)"';
$email_template_ids = $this->Conn->GetCol($sql);
if ( !$email_template_ids ) {
return;
}
// e-mail events, connected to that unit prefix are found
$sql = 'SELECT SubscriptionId
FROM ' . TABLE_PREFIX . 'SystemEventSubscriptions
WHERE ' . $field . ' = ' . $value . ' AND EmailTemplateId IN (' . implode(',', $email_template_ids) . ')';
$ids = $this->Conn->GetCol($sql);
if ( !$ids ) {
return;
}
/** @var kTempTablesHandler $temp_handler */
$temp_handler = $this->Application->recallObject('system-event-subscription_TempHandler', 'kTempTablesHandler');
$temp_handler->DeleteItems('system-event-subscription', '', $ids);
}
/**
* Occurs before validation attempt
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnBeforeItemValidate(kEvent $event)
{
}
/**
* Occurs after successful item validation
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnAfterItemValidate(kEvent $event)
{
}
/**
* Occurs after an item has been copied to temp
* Id of copied item is passed as event' 'id' param
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnAfterCopyToTemp(kEvent $event)
{
}
/**
* Occurs 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
* @return void
* @access protected
*/
protected function OnBeforeDeleteFromLive(kEvent $event)
{
}
/**
* Occurs 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
* @return void
* @access protected
*/
protected function OnBeforeCopyToLive(kEvent $event)
{
}
/**
* Occurs after an item has been copied to live table
* Id of copied item is passed as event' 'id' param
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnAfterCopyToLive(kEvent $event)
{
/** @var kDBItem $object */
$object = $event->getObject(array('skip_autoload' => true));
$object->SwitchToLive();
$object->Load($event->getEventParam('id'));
$this->_processPendingActions($event);
}
/**
* Processing file pending actions (e.g. delete scheduled files)
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function _processPendingActions(kEvent $event)
{
/** @var kDBItem $object */
$object = $event->getObject();
$update_required = false;
$temp_id = $event->getEventParam('temp_id');
$id = $temp_id !== false ? $temp_id : $object->GetID();
foreach ($object->getPendingActions($id) as $data) {
switch ( $data['action'] ) {
case 'delete':
unlink($data['file']);
break;
case 'make_live':
/** @var FileHelper $file_helper */
$file_helper = $this->Application->recallObject('FileHelper');
if ( !file_exists($data['file']) ) {
// File removal was requested too.
break;
}
$old_name = basename($data['file']);
$new_name = $file_helper->ensureUniqueFilename(dirname($data['file']), kUtil::removeTempExtension($old_name));
rename($data['file'], dirname($data['file']) . '/' . $new_name);
$db_value = $object->GetDBField($data['field']);
$object->SetDBField($data['field'], str_replace($old_name, $new_name, $db_value));
$update_required = true;
break;
default:
trigger_error('Unsupported pending action "' . $data['action'] . '" for "' . $event->getPrefixSpecial() . '" unit', E_USER_WARNING);
break;
}
}
// remove pending actions before updating to prevent recursion
$object->setPendingActions();
if ( $update_required ) {
$object->Update();
}
}
/**
* Occurs before an item has been cloned
* Id of newly created item is passed as event' 'id' param
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnBeforeClone(kEvent $event)
{
}
/**
* Occurs after an item has been cloned
* Id of newly created item is passed as event' 'id' param
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnAfterClone(kEvent $event)
{
}
/**
* Occurs after list is queried
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnAfterListQuery(kEvent $event)
{
}
/**
* Ensures that popup will be closed automatically
* and parent window will be refreshed with template
* passed
*
* @param kEvent $event
* @return void
* @access protected
* @deprecated
*/
protected function finalizePopup(kEvent $event)
{
$event->SetRedirectParam('opener', 'u');
}
/**
* Create search filters based on search query
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnSearch(kEvent $event)
{
$event->setPseudoClass('_List');
/** @var kSearchHelper $search_helper */
$search_helper = $this->Application->recallObject('SearchHelper');
$search_helper->performSearch($event);
}
/**
* Clear search keywords
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnSearchReset(kEvent $event)
{
/** @var kSearchHelper $search_helper */
$search_helper = $this->Application->recallObject('SearchHelper');
$search_helper->resetSearch($event);
}
/**
* Set's new filter value (filter_id meaning from config)
*
* @param kEvent $event
* @return void
* @access protected
* @deprecated
*/
protected function OnSetFilter(kEvent $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));
}
/**
* Sets view filter based on request
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnSetFilterPattern(kEvent $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
* @return void
* @access protected
*/
protected function FilterAction(kEvent $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;
default:
$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
* @access protected
*/
protected function OnPreSaveAndOpenTranslator(kEvent $event)
{
$this->Application->SetVar('allow_translation', true);
/** @var kDBItem $object */
$object = $event->getObject();
$this->RemoveRequiredFields($object);
$event->CallSubEvent('OnPreSave');
if ( $event->status == kEvent::erSUCCESS ) {
$resource_id = $this->Application->GetVar('translator_resource_id');
if ( $resource_id ) {
$t_prefixes = explode(',', $this->Application->GetVar('translator_prefixes'));
/** @var kDBItem $cdata */
$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');
$redirect_params = Array (
'pass' => 'all,trans,' . $this->Application->GetVar('translator_prefixes'),
'opener' => 's',
$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'),
);
$event->setRedirectParams($redirect_params);
// 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'));
}
}
/**
* Makes all fields non-required
*
* @param kDBItem $object
* @return void
* @access protected
*/
protected function RemoveRequiredFields(&$object)
{
// making all field non-required to achieve successful presave
$fields = array_keys( $object->getFields() );
foreach ($fields as $field) {
if ( $object->isRequired($field) ) {
$object->setRequired($field, false);
}
}
}
/**
* Saves selected user in needed field
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnSelectUser(kEvent $event)
{
/** @var kDBItem $object */
$object = $event->getObject();
$items_info = $this->Application->GetVar('u');
if ( $items_info ) {
$user_id = key($items_info);
$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();
}
else {
$object->Update();
}
}
$event->SetRedirectParam($event->getPrefixSpecial() . '_id', $object->GetID());
$event->SetRedirectParam('opener', 'u');
}
/** EXPORT RELATED **/
/**
* Shows export dialog
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnExport(kEvent $event)
{
$selected_ids = $this->StoreSelectedIDs($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) : '');
$this->Application->LinkVar('export_finish_t');
$this->Application->LinkVar('export_progress_t');
$this->Application->StoreVar('export_special', $event->Special);
$this->Application->StoreVar('export_grid', $this->Application->GetVar('grid', 'Default'));
$redirect_params = Array (
$this->Prefix . '.export_event' => 'OnNew',
'pass' => 'all,' . $this->Prefix . '.export'
);
$event->setRedirectParams($redirect_params);
}
/**
* Apply some special processing to object being
* recalled before using it in other events that
* call prepareObject
*
* @param kDBItem|kDBList $object
* @param kEvent $event
* @return void
* @access protected
*/
protected function prepareObject(&$object, kEvent $event)
{
if ( $event->Special == 'export' || $event->Special == 'import' ) {
/** @var kCatDBItemExportHelper $export_helper */
$export_helper = $this->Application->recallObject('CatItemExportHelper');
$export_helper->prepareExportColumns($event);
}
}
/**
* Returns specific to each item type columns only
*
* @param kEvent $event
* @return Array
* @access public
*/
public function getCustomExportColumns(kEvent $event)
{
return Array ();
}
/**
* Export form validation & processing
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnExportBegin(kEvent $event)
{
/** @var kCatDBItemExportHelper $export_helper */
$export_helper = $this->Application->recallObject('CatItemExportHelper');
$export_helper->OnExportBegin($event);
}
/**
* Enter description here...
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnExportCancel(kEvent $event)
{
$this->OnGoBack($event);
}
/**
* Allows configuring export options
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnBeforeExportBegin(kEvent $event)
{
}
/**
* Deletes export preset
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnDeleteExportPreset(kEvent $event)
{
$delete_preset_name = $this->Application->GetVar('delete_preset_name');
if ( !$delete_preset_name ) {
return;
}
$where_clause = array(
'ItemPrefix = ' . $this->Conn->qstr($event->Prefix),
'PortalUserId = ' . $this->Application->RecallVar('user_id'),
'PresetName = ' . $this->Conn->qstr($delete_preset_name),
);
$sql = 'DELETE
FROM ' . TABLE_PREFIX . 'ExportUserPresets
WHERE (' . implode(') AND (', $where_clause) . ')';
$this->Conn->Query($sql);
}
/**
* Saves changes & changes language
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnPreSaveAndChangeLanguage(kEvent $event)
{
if ( $this->UseTempTables($event) ) {
$event->CallSubEvent('OnPreSave');
}
if ( $event->status == kEvent::erSUCCESS ) {
$this->Application->SetVar('m_lang', $this->Application->GetVar('language'));
$data = $this->Application->GetVar('st_id');
if ( $data ) {
$event->SetRedirectParam('st_id', $data);
}
}
}
/**
* Used to save files uploaded via Plupload
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnUploadFile(kEvent $event)
{
$event->status = kEvent::erSTOP;
/** @var kUploadHelper $upload_helper */
$upload_helper = $this->Application->recallObject('kUploadHelper');
try {
$filename = $upload_helper->handle($event);
$response = array(
'jsonrpc' => '2.0',
'status' => 'success',
'result' => $filename,
);
}
catch ( kUploaderException $e ) {
$response = array(
'jsonrpc' => '2.0',
'status' => 'error',
'error' => array('code' => $e->getCode(), 'message' => $e->getMessage()),
);
}
echo json_encode($response);
}
/**
* Remembers, that file should be deleted on item's save from temp table
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnDeleteFile(kEvent $event)
{
$event->status = kEvent::erSTOP;
$field_id = $this->Application->GetVar('field_id');
if ( !preg_match_all('/\[([^\[\]]*)\]/', $field_id, $regs) ) {
return;
}
$field = $regs[1][1];
$record_id = $regs[1][0];
/** @var kUploadHelper $upload_helper */
$upload_helper = $this->Application->recallObject('kUploadHelper');
$object = $upload_helper->prepareUploadedFile($event, $field);
if ( !$object->GetDBField($field) ) {
return;
}
$pending_actions = $object->getPendingActions($record_id);
$pending_actions[] = Array (
'action' => 'delete',
'id' => $record_id,
'field' => $field,
'file' => $object->GetField($field, 'full_path'),
);
$object->setPendingActions($pending_actions, $record_id);
}
/**
* Returns url for viewing uploaded file
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnViewFile(kEvent $event)
{
$event->status = kEvent::erSTOP;
$field = $this->Application->GetVar('field');
/** @var kUploadHelper $upload_helper */
$upload_helper = $this->Application->recallObject('kUploadHelper');
$object = $upload_helper->prepareUploadedFile($event, $field);
if ( !$object->GetDBField($field) ) {
return;
}
// get url to uploaded file
if ( $this->Application->GetVar('thumb') ) {
$url = $object->GetField($field, $object->GetFieldOption($field, 'thumb_format'));
}
else {
$url = $object->GetField($field, 'raw_url');
}
/** @var FileHelper $file_helper */
$file_helper = $this->Application->recallObject('FileHelper');
$path = $file_helper->urlToPath($url);
if ( !file_exists($path) ) {
exit;
}
header('Content-Length: ' . filesize($path));
$this->Application->setContentType(kUtil::mimeContentType($path), false);
header('Content-Disposition: inline; filename="' . kUtil::removeTempExtension($object->GetDBField($field)) . '"');
readfile($path);
}
/**
* Validates MInput control fields
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnValidateMInputFields(kEvent $event)
{
/** @var MInputHelper $minput_helper */
$minput_helper = $this->Application->recallObject('MInputHelper');
$minput_helper->OnValidateMInputFields($event);
}
/**
* Validates individual object field and returns the result
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnValidateField(kEvent $event)
{
$event->status = kEvent::erSTOP;
$field = $this->Application->GetVar('field');
if ( ($this->Application->GetVar('ajax') != 'yes') || !$field ) {
return;
}
/** @var kDBItem $object */
$object = $event->getObject(Array ('skip_autoload' => true));
$items_info = $this->Application->GetVar($event->getPrefixSpecial(true));
if ( !$items_info ) {
return;
}
$id = key($items_info);
$field_values = $items_info[$id];
$object->Load($id);
$object->SetFieldsFromHash($field_values);
$event->setEventParam('form_data', $field_values);
$object->setID($id);
$response = Array ('status' => 'OK');
$event->CallSubEvent($object->isLoaded() ? 'OnBeforeItemUpdate' : 'OnBeforeItemCreate');
// validate all fields, since "Password_plain" field sets error to "Password" field, which is passed here
$error_field = $object->GetFieldOption($field, 'error_field', false, $field);
if ( !$object->Validate() && $object->GetErrorPseudo($error_field) ) {
$response['status'] = $object->GetErrorMsg($error_field, false);
}
/** @var AjaxFormHelper $ajax_form_helper */
$ajax_form_helper = $this->Application->recallObject('AjaxFormHelper');
$response['other_errors'] = $ajax_form_helper->getErrorMessages($object);
$response['uploader_info'] = $ajax_form_helper->getUploaderInfo($object, array_keys($field_values));
$event->status = kEvent::erSTOP; // since event's OnBefore... events can change this event status
echo json_encode($response);
}
/**
* Returns auto-complete values for ajax-dropdown
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnSuggestValues(kEvent $event)
{
$event->status = kEvent::erSTOP;
$this->Application->XMLHeader();
$data = $this->getAutoCompleteSuggestions($event, $this->Application->GetVar('cur_value'));
$fields = $this->Application->getUnitOption($event->Prefix, 'Fields');
echo '<suggestions>';
if ( kUtil::isAssoc($data) ) {
foreach ($data as $key => $title) {
echo '<item value="' . kUtil::escape($key, kUtil::ESCAPE_HTML) . '">' . kUtil::escape($title, kUtil::ESCAPE_HTML) . '</item>';
}
}
else {
foreach ($data as $title) {
echo '<item>' . kUtil::escape($title, kUtil::ESCAPE_HTML) . '</item>';
}
}
echo '</suggestions>';
}
/**
* Returns auto-complete values for jQueryUI.AutoComplete
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnSuggestValuesJSON(kEvent $event)
{
$event->status = kEvent::erSTOP;
$data = $this->getAutoCompleteSuggestions($event, $this->Application->GetVar('term'));
if ( kUtil::isAssoc($data) ) {
$transformed_data = array();
foreach ($data as $key => $title) {
$transformed_data[] = array('value' => $key, 'label' => $title);
}
$data = $transformed_data;
}
echo json_encode($data);
}
/**
* Prepares a suggestion list based on a given term.
*
* @param kEvent $event Event.
* @param string $term Term.
*
* @return Array
* @access protected
*/
protected function getAutoCompleteSuggestions(kEvent $event, $term)
{
/** @var kDBItem $object */
$object = $event->getObject(array('skip_autoload' => true));
$field = $this->Application->GetVar('field');
if ( !$field || !$term || !$object->isField($field) ) {
return array();
}
$limit = $this->Application->GetVar('limit');
if ( !$limit ) {
$limit = 20;
}
$sql = 'SELECT DISTINCT ' . $field . '
FROM ' . $this->Application->getUnitOption($event->Prefix, 'TableName') . '
WHERE ' . $field . ' LIKE ' . $this->Conn->qstr($term . '%') . '
ORDER BY ' . $field . '
LIMIT 0,' . $limit;
return $this->Conn->GetCol($sql);
}
/**
* Enter description here...
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnSaveWidths(kEvent $event)
{
$event->status = kEvent::erSTOP;
// $this->Application->setContentType('text/xml');
$picker_helper = new kColumnPickerHelper(
$event->getPrefixSpecial(),
$this->Application->GetVar('grid_name')
);
$picker_helper->saveWidths($this->Application->GetVar('widths'));
echo 'OK';
}
/**
* Called from CSV import script after item fields
* are set and validated, but before actual item create/update.
* If event status is kEvent::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
* @return void
* @access protected
*/
protected function OnBeforeCSVLineImport(kEvent $event)
{
// abstract, for hooking
}
/**
* [HOOK] Allows to add cloned subitem to given prefix
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnCloneSubItem(kEvent $event)
{
$clones = $this->Application->getUnitOption($event->MasterEvent->Prefix, 'Clones');
$subitem_prefix = $event->Prefix . '-' . preg_replace('/^#/', '', $event->MasterEvent->Prefix);
$clones[$subitem_prefix] = Array ('ParentPrefix' => $event->Prefix);
$this->Application->setUnitOption($event->MasterEvent->Prefix, 'Clones', $clones);
}
/**
* Returns constrain for priority calculations
*
* @param kEvent $event
* @return void
* @see PriorityEventHandler
* @access protected
*/
protected function OnGetConstrainInfo(kEvent $event)
{
$event->setEventParam('constrain_info', Array ('', ''));
}
}
Index: branches/5.2.x/core/kernel/application.php
===================================================================
--- branches/5.2.x/core/kernel/application.php (revision 16796)
+++ branches/5.2.x/core/kernel/application.php (revision 16797)
@@ -1,3184 +1,3184 @@
<?php
/**
* @version $Id$
* @package In-Portal
* @copyright Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license GNU/GPL
* In-Portal is Open Source software.
* This means that this software may have been modified pursuant
* the GNU General Public License, and as distributed it includes
* or is derivative of works licensed under the GNU General Public License
* or other free or open source software licenses.
* See http://www.in-portal.org/license for copyright notices and details.
*/
defined('FULL_PATH') or die('restricted access!');
/**
* Basic class for Kernel4-based Application
*
* This class is a Facade for any other class which needs to deal with Kernel4 framework.<br>
* The class encapsulates the main run-cycle of the script, provide access to all other objects in the framework.<br>
* <br>
* The class is a singleton, which means that there could be only one instance of kApplication in the script.<br>
* This could be guaranteed by NOT calling the class constructor directly, but rather calling kApplication::Instance() method,
* which returns an instance of the application. The method guarantees that it will return exactly the same instance for any call.<br>
* See singleton pattern by GOF.
*/
class kApplication implements kiCacheable {
/**
* Location of module helper class (used in installator too)
*/
const MODULE_HELPER_PATH = '/../units/helpers/modules_helper.php';
/**
* Is true, when Init method was called already, prevents double initialization
*
* @var bool
*/
public $InitDone = false;
/**
* Holds internal NParser object
*
* @var NParser
* @access public
*/
public $Parser;
/**
* Holds parser output buffer
*
* @var string
* @access protected
*/
protected $HTML = '';
/**
* The main Factory used to create
* almost any class of kernel and
* modules
*
* @var kFactory
* @access protected
*/
protected $Factory;
/**
* Template names, that will be used instead of regular templates
*
* @var Array
* @access public
*/
public $ReplacementTemplates = Array ();
/**
* Mod-Rewrite listeners used during url building and parsing
*
* @var Array
* @access public
*/
public $RewriteListeners = Array ();
/**
* Reference to debugger
*
* @var Debugger
* @access public
*/
public $Debugger = null;
/**
* Holds all phrases used
* in code and template
*
* @var PhrasesCache
* @access public
*/
public $Phrases;
/**
* Modules table content, key - module name
*
* @var Array
* @access public
*/
public $ModuleInfo = Array ();
/**
* Holds DBConnection
*
* @var IDBConnection
* @access public
*/
public $Conn = null;
/**
* Reference to event log
*
* @var Array|kLogger
* @access public
*/
protected $_logger = Array ();
// performance needs:
/**
* Holds a reference to httpquery
*
* @var kHttpQuery
* @access public
*/
public $HttpQuery = null;
/**
* Holds a reference to UnitConfigReader
*
* @var kUnitConfigReader
* @access public
*/
public $UnitConfigReader = null;
/**
* Holds a reference to Session
*
* @var Session
* @access public
*/
public $Session = null;
/**
* Holds a ref to kEventManager
*
* @var kEventManager
* @access public
*/
public $EventManager = null;
/**
* Holds a ref to kUrlManager
*
* @var kUrlManager
* @access public
*/
public $UrlManager = null;
/**
* Ref for TemplatesCache
*
* @var TemplatesCache
* @access public
*/
public $TemplatesCache = null;
/**
* Holds current NParser tag while parsing, can be used in error messages to display template file and line
*
* @var _BlockTag
* @access public
*/
public $CurrentNTag = null;
/**
* Object of unit caching class
*
* @var kCacheManager
* @access public
*/
public $cacheManager = null;
/**
* Tells, that administrator has authenticated in administrative console
* Should be used to manipulate data change OR data restrictions!
*
* @var bool
* @access public
*/
public $isAdminUser = false;
/**
* Tells, that admin version of "index.php" was used, nothing more!
* Should be used to manipulate data display!
*
* @var bool
* @access public
*/
public $isAdmin = false;
/**
* Instance of site domain object
*
* @var kDBItem
* @access public
* @todo move away into separate module
*/
public $siteDomain = null;
/**
* Prevent kApplication class to be created directly, only via Instance method
*
* @access private
*/
private function __construct()
{
}
final private function __clone() {}
/**
* Returns kApplication instance anywhere in the script.
*
* This method should be used to get single kApplication object instance anywhere in the
* Kernel-based application. The method is guaranteed to return the SAME instance of kApplication.
* Anywhere in the script you could write:
* <code>
* $application =& kApplication::Instance();
* </code>
* or in an object:
* <code>
* $this->Application =& kApplication::Instance();
* </code>
* to get the instance of kApplication. Note that we call the Instance method as STATIC - directly from the class.
* To use descendant of standard kApplication class in your project you would need to define APPLICATION_CLASS constant
* BEFORE calling kApplication::Instance() for the first time. If APPLICATION_CLASS is not defined the method would
* create and return default KernelApplication instance.
*
* Pattern: Singleton
*
* @static
* @return kApplication
* @access public
*/
public static function &Instance()
{
static $instance = false;
if ( !$instance ) {
$class = defined('APPLICATION_CLASS') ? APPLICATION_CLASS : 'kApplication';
$instance = new $class();
}
return $instance;
}
/**
* Initializes the Application
*
* @param string $factory_class
* @return bool Was Init actually made now or before
* @access public
* @see kHTTPQuery
* @see Session
* @see TemplatesCache
*/
public function Init($factory_class = 'kFactory')
{
if ( $this->InitDone ) {
return false;
}
if ( preg_match('/utf-8/i', CHARSET) ) {
setlocale(LC_ALL, 'en_US.UTF-8');
mb_internal_encoding('UTF-8');
}
$this->isAdmin = kUtil::constOn('ADMIN');
if ( !kUtil::constOn('SKIP_OUT_COMPRESSION') ) {
ob_start(); // collect any output from method (other then tags) into buffer
}
if ( defined('DEBUG_MODE') && $this->isDebugMode() && kUtil::constOn('DBG_PROFILE_MEMORY') ) {
$this->Debugger->appendMemoryUsage('Application before Init:');
}
$this->_logger = new kLogger($this->_logger);
$this->Factory = new $factory_class();
$this->registerDefaultClasses();
$system_config = new kSystemConfig(true);
$vars = $system_config->getData();
$db_class = isset($vars['Databases']) ? 'kDBLoadBalancer' : ($this->isDebugMode() ? 'kDBConnectionDebug' : 'kDBConnection');
$this->Conn = $this->Factory->makeClass($db_class, Array (SQL_TYPE, Array ($this->_logger, 'handleSQLError')));
$this->Conn->setup($vars);
$this->cacheManager = $this->makeClass('kCacheManager');
$this->cacheManager->InitCache();
define('MAX_UPLOAD_SIZE', $this->getMaxUploadSize());
if ( defined('DEBUG_MODE') && $this->isDebugMode() ) {
$this->Debugger->appendTimestamp('Before UnitConfigReader');
}
// init config reader and all managers
$this->UnitConfigReader = $this->makeClass('kUnitConfigReader');
$this->UnitConfigReader->scanModules(MODULES_PATH); // will also set RewriteListeners when existing cache is read
$this->registerModuleConstants();
if ( defined('DEBUG_MODE') && $this->isDebugMode() ) {
$this->Debugger->appendTimestamp('After UnitConfigReader');
}
define('MOD_REWRITE', $this->ConfigValue('UseModRewrite') && !$this->isAdmin ? 1 : 0);
// start processing request
$this->HttpQuery = $this->recallObject('HTTPQuery');
$this->HttpQuery->process();
if ( defined('DEBUG_MODE') && $this->isDebugMode() ) {
$this->Debugger->appendTimestamp('Processed HTTPQuery initial');
}
$this->Session = $this->recallObject('Session');
if ( defined('DEBUG_MODE') && $this->isDebugMode() ) {
$this->Debugger->appendTimestamp('Processed Session');
}
$this->Session->ValidateExpired(); // needs mod_rewrite url already parsed to keep user at proper template after session expiration
if ( defined('DEBUG_MODE') && $this->isDebugMode() ) {
$this->Debugger->appendTimestamp('Processed HTTPQuery AfterInit');
}
$this->cacheManager->LoadApplicationCache();
$site_timezone = $this->ConfigValue('Config_Site_Time');
if ( $site_timezone ) {
date_default_timezone_set($site_timezone);
}
if ( defined('DEBUG_MODE') && $this->isDebugMode() ) {
$this->Debugger->appendTimestamp('Loaded cache and phrases');
}
$this->ValidateLogin(); // must be called before AfterConfigRead, because current user should be available there
$this->UnitConfigReader->AfterConfigRead(); // will set RewriteListeners when missing cache is built first time
if ( defined('DEBUG_MODE') && $this->isDebugMode() ) {
$this->Debugger->appendTimestamp('Processed AfterConfigRead');
}
if ( $this->GetVar('m_cat_id') === false ) {
$this->SetVar('m_cat_id', 0);
}
if ( !$this->RecallVar('curr_iso') && !(defined('IS_INSTALL') && IS_INSTALL) ) {
$this->StoreVar('curr_iso', $this->GetPrimaryCurrency(), true); // true for optional
}
$visit_id = $this->RecallVar('visit_id');
if ( $visit_id !== false ) {
$this->SetVar('visits_id', $visit_id);
}
if ( defined('DEBUG_MODE') && $this->isDebugMode() ) {
$this->Debugger->profileFinish('kernel4_startup');
}
$this->InitDone = true;
if ( PHP_SAPI !== 'cli' && !$this->isAdmin ) {
$this->HandleEvent(new kEvent('adm:OnStartup'));
}
else {
// User can't edit anything in Admin Console or in CLI mode.
kUtil::safeDefine('EDITING_MODE', '');
}
return true;
}
/**
* Calculates maximal upload file size
*
* @return integer
*/
protected function getMaxUploadSize()
{
$cache_key = 'max_upload_size';
$max_upload_size = $this->getCache($cache_key);
if ( $max_upload_size === false ) {
$max_upload_size = kUtil::parseIniSize(ini_get('upload_max_filesize'));
$post_max_size = ini_get('post_max_size');
if ( $post_max_size !== '0' ) {
$max_upload_size = min($max_upload_size, kUtil::parseIniSize($post_max_size));
}
$memory_limit = ini_get('memory_limit');
if ( $memory_limit !== '-1' ) {
$max_upload_size = min($max_upload_size, kUtil::parseIniSize($memory_limit));
}
$this->setCache($cache_key, $max_upload_size);
}
return $max_upload_size;
}
/**
* Performs initialization of manager classes, that can be overridden from unit configs
*
* @return void
* @access public
* @throws Exception
*/
public function InitManagers()
{
if ( $this->InitDone ) {
throw new Exception('Duplicate call of ' . __METHOD__, E_USER_ERROR);
return;
}
$this->UrlManager = $this->makeClass('kUrlManager');
$this->EventManager = $this->makeClass('EventManager');
$this->Phrases = $this->makeClass('kPhraseCache');
$this->RegisterDefaultBuildEvents();
}
/**
* Returns module information. Searches module by requested field
*
* @param string $field
* @param mixed $value
* @param string $return_field field value to returns, if not specified, then return all fields
* @return Array
*/
public function findModule($field, $value, $return_field = null)
{
$found = $module_info = false;
foreach ($this->ModuleInfo as $module_info) {
if ( strtolower($module_info[$field]) == strtolower($value) ) {
$found = true;
break;
}
}
if ( $found ) {
return isset($return_field) ? $module_info[$return_field] : $module_info;
}
return false;
}
/**
* Refreshes information about loaded modules
*
* @return void
* @access public
*/
public function refreshModuleInfo()
{
if ( defined('IS_INSTALL') && IS_INSTALL && !$this->TableFound('Modules', true) ) {
$this->registerModuleConstants();
return;
}
// use makeClass over recallObject, since used before kApplication initialization during installation
/** @var kModulesHelper $modules_helper */
$modules_helper = $this->makeClass('ModulesHelper');
$this->Conn->nextQueryCachable = true;
$sql = 'SELECT *
FROM ' . TABLE_PREFIX . 'Modules
WHERE ' . $modules_helper->getWhereClause() . '
ORDER BY LoadOrder';
$this->ModuleInfo = $this->Conn->Query($sql, 'Name');
$this->registerModuleConstants();
}
/**
* Checks if passed language id if valid and sets it to primary otherwise
*
* @return void
* @access public
*/
public function VerifyLanguageId()
{
/** @var LanguagesItem $lang */
$lang = $this->recallObject('lang.current');
if ( !$lang->isLoaded() || (!$this->isAdmin && !$lang->GetDBField('Enabled')) ) {
if ( !defined('IS_INSTALL') ) {
$this->ApplicationDie('Unknown or disabled language');
}
}
}
/**
* Checks if passed theme id if valid and sets it to primary otherwise
*
* @return void
* @access public
*/
public function VerifyThemeId()
{
if ( $this->isAdmin ) {
kUtil::safeDefine('THEMES_PATH', '/core/admin_templates');
return;
}
$path = $this->GetFrontThemePath();
if ( $path === false ) {
$this->ApplicationDie('No Primary Theme Selected or Current Theme is Unknown or Disabled');
}
kUtil::safeDefine('THEMES_PATH', $path);
}
/**
* Returns relative path to current front-end theme
*
* @param bool $force
* @return string
* @access public
*/
public function GetFrontThemePath($force = false)
{
static $path = null;
if ( !$force && isset($path) ) {
return $path;
}
/** @var ThemeItem $theme */
$theme = $this->recallObject('theme.current');
if ( !$theme->isLoaded() || !$theme->GetDBField('Enabled') ) {
return false;
}
// assign & then return, since it's static variable
$path = '/themes/' . $theme->GetDBField('Name');
return $path;
}
/**
* Returns primary front/admin language id
*
* @param bool $init
* @return int
* @access public
*/
public function GetDefaultLanguageId($init = false)
{
$cache_key = 'primary_language_info[%LangSerial%]';
$language_info = $this->getCache($cache_key);
if ( $language_info === false ) {
// cache primary language info first
$table = $this->getUnitOption('lang', 'TableName');
$id_field = $this->getUnitOption('lang', 'IDField');
$this->Conn->nextQueryCachable = true;
$sql = 'SELECT ' . $id_field . ', IF(AdminInterfaceLang, "Admin", "Front") AS LanguageKey
FROM ' . $table . '
WHERE (AdminInterfaceLang = 1 OR PrimaryLang = 1) AND (Enabled = 1)';
$language_info = $this->Conn->GetCol($sql, 'LanguageKey');
if ( $language_info !== false ) {
$this->setCache($cache_key, $language_info);
}
}
$language_key = ($this->isAdmin && $init) || count($language_info) == 1 ? 'Admin' : 'Front';
if ( array_key_exists($language_key, $language_info) && $language_info[$language_key] > 0 ) {
// get from cache
return $language_info[$language_key];
}
$language_id = $language_info && array_key_exists($language_key, $language_info) ? $language_info[$language_key] : false;
if ( !$language_id && defined('IS_INSTALL') && IS_INSTALL ) {
$language_id = 1;
}
return $language_id;
}
/**
* Returns front-end primary theme id (even, when called from admin console)
*
* @param bool $force_front
* @return int
* @access public
*/
public function GetDefaultThemeId($force_front = false)
{
static $cache = array('force_front=yes' => 0, 'force_front=no' => 0);
$static_cache_key = $force_front ? 'force_front=yes' : 'force_front=no';
if ( $cache[$static_cache_key] > 0 ) {
return $cache[$static_cache_key];
}
if ( kUtil::constOn('DBG_FORCE_THEME') ) {
$cache[$static_cache_key] = DBG_FORCE_THEME;
}
elseif ( !$force_front && $this->isAdmin ) {
$cache[$static_cache_key] = 999;
}
else {
$cache_key = 'primary_theme[%ThemeSerial%]';
$cache[$static_cache_key] = $this->getCache($cache_key);
if ( $cache[$static_cache_key] === false ) {
$this->Conn->nextQueryCachable = true;
$sql = 'SELECT ' . $this->getUnitOption('theme', 'IDField') . '
FROM ' . $this->getUnitOption('theme', 'TableName') . '
WHERE (PrimaryTheme = 1) AND (Enabled = 1)';
$cache[$static_cache_key] = $this->Conn->GetOne($sql);
if ( $cache[$static_cache_key] !== false ) {
$this->setCache($cache_key, $cache[$static_cache_key]);
}
}
}
return $cache[$static_cache_key];
}
/**
* Returns site primary currency ISO code
*
* @return string
* @access public
* @todo Move into In-Commerce
*/
public function GetPrimaryCurrency()
{
$cache_key = 'primary_currency[%CurrSerial%][%SiteDomainSerial%]:' . $this->siteDomainField('DomainId');
$currency_iso = $this->getCache($cache_key);
if ( $currency_iso === false ) {
if ( $this->prefixRegistred('curr') ) {
$this->Conn->nextQueryCachable = true;
$currency_id = $this->siteDomainField('PrimaryCurrencyId');
$sql = 'SELECT ISO
FROM ' . $this->getUnitOption('curr', 'TableName') . '
WHERE ' . ($currency_id > 0 ? 'CurrencyId = ' . $currency_id : 'IsPrimary = 1');
$currency_iso = $this->Conn->GetOne($sql);
}
else {
$currency_iso = 'USD';
}
$this->setCache($cache_key, $currency_iso);
}
return $currency_iso;
}
/**
* Returns site domain field. When none of site domains are found false is returned.
*
* @param string $field
* @param bool $formatted
* @param string $format
* @return mixed
* @todo Move into separate module
*/
public function siteDomainField($field, $formatted = false, $format = null)
{
if ( $this->isAdmin ) {
// don't apply any filtering in administrative console
return false;
}
if ( !$this->siteDomain ) {
$this->siteDomain = $this->recallObject('site-domain.current', null, Array ('live_table' => true));
/** @var kDBItem $site_domain */
}
if ( $this->siteDomain->isLoaded() ) {
return $formatted ? $this->siteDomain->GetField($field, $format) : $this->siteDomain->GetDBField($field);
}
return false;
}
/**
* Registers default classes such as kDBEventHandler, kUrlManager
*
* Called automatically while initializing kApplication
*
* @return void
* @access public
*/
public function RegisterDefaultClasses()
{
$this->registerClass('kHelper', KERNEL_PATH . '/kbase.php');
$this->registerClass('kMultipleFilter', KERNEL_PATH . '/utility/filters.php');
$this->registerClass('kiCacheable', KERNEL_PATH . '/interfaces/cacheable.php');
$this->registerClass('kEventManager', KERNEL_PATH . '/event_manager.php', 'EventManager');
$this->registerClass('kHookManager', KERNEL_PATH . '/managers/hook_manager.php');
$this->registerClass('kScheduledTaskManager', KERNEL_PATH . '/managers/scheduled_task_manager.php');
$this->registerClass('kRequestManager', KERNEL_PATH . '/managers/request_manager.php');
$this->registerClass('kSubscriptionManager', KERNEL_PATH . '/managers/subscription_manager.php');
$this->registerClass('kSubscriptionItem', KERNEL_PATH . '/managers/subscription_manager.php');
$this->registerClass('kUrlManager', KERNEL_PATH . '/managers/url_manager.php');
$this->registerClass('kUrlProcessor', KERNEL_PATH . '/managers/url_processor.php');
$this->registerClass('kPlainUrlProcessor', KERNEL_PATH . '/managers/plain_url_processor.php');
$this->registerClass('kRewriteUrlProcessor', KERNEL_PATH . '/managers/rewrite_url_processor.php');
$this->registerClass('kCacheManager', KERNEL_PATH . '/managers/cache_manager.php');
$this->registerClass('PhrasesCache', KERNEL_PATH . '/languages/phrases_cache.php', 'kPhraseCache');
$this->registerClass('kTempTablesHandler', KERNEL_PATH . '/utility/temp_handler.php');
$this->registerClass('kValidator', KERNEL_PATH . '/utility/validator.php');
$this->registerClass('kOpenerStack', KERNEL_PATH . '/utility/opener_stack.php');
$this->registerClass('kLogger', KERNEL_PATH . '/utility/logger.php');
$this->registerClass('kUnitConfigReader', KERNEL_PATH . '/utility/unit_config_reader.php');
$this->registerClass('PasswordHash', KERNEL_PATH . '/utility/php_pass.php');
// Params class descendants
$this->registerClass('kArray', KERNEL_PATH . '/utility/params.php');
$this->registerClass('Params', KERNEL_PATH . '/utility/params.php');
$this->registerClass('Params', KERNEL_PATH . '/utility/params.php', 'kActions');
$this->registerClass('kCache', KERNEL_PATH . '/utility/cache.php', 'kCache', 'Params');
$this->registerClass('kHTTPQuery', KERNEL_PATH . '/utility/http_query.php', 'HTTPQuery');
// security
$this->registerClass('SecurityGenerator', KERNEL_PATH . '/security/SecurityGenerator.php');
$this->registerClass('SecurityGeneratorPromise', KERNEL_PATH . '/security/SecurityGeneratorPromise.php');
$this->registerClass('SecurityEncrypter', KERNEL_PATH . '/security/SecurityEncrypter.php');
// session
$this->registerClass('Session', KERNEL_PATH . '/session/session.php');
$this->registerClass('SessionStorage', KERNEL_PATH . '/session/session_storage.php');
$this->registerClass('InpSession', KERNEL_PATH . '/session/inp_session.php', 'Session');
$this->registerClass('InpSessionStorage', KERNEL_PATH . '/session/inp_session_storage.php', 'SessionStorage');
// template parser
$this->registerClass('kTagProcessor', KERNEL_PATH . '/processors/tag_processor.php');
$this->registerClass('kMainTagProcessor', KERNEL_PATH . '/processors/main_processor.php', 'm_TagProcessor');
$this->registerClass('kDBTagProcessor', KERNEL_PATH . '/db/db_tag_processor.php');
$this->registerClass('kCatDBTagProcessor', KERNEL_PATH . '/db/cat_tag_processor.php');
$this->registerClass('NParser', KERNEL_PATH . '/nparser/nparser.php');
$this->registerClass('TemplatesCache', KERNEL_PATH . '/nparser/template_cache.php');
// database
$this->registerClass('kDBConnection', KERNEL_PATH . '/db/db_connection.php');
$this->registerClass('kDBConnectionDebug', KERNEL_PATH . '/db/db_connection.php');
$this->registerClass('kDBLoadBalancer', KERNEL_PATH . '/db/db_load_balancer.php');
$this->registerClass('kDBItem', KERNEL_PATH . '/db/dbitem.php');
$this->registerClass('kCatDBItem', KERNEL_PATH . '/db/cat_dbitem.php');
$this->registerClass('kDBList', KERNEL_PATH . '/db/dblist.php');
$this->registerClass('kCatDBList', KERNEL_PATH . '/db/cat_dblist.php');
$this->registerClass('kDBEventHandler', KERNEL_PATH . '/db/db_event_handler.php');
$this->registerClass('kCatDBEventHandler', KERNEL_PATH . '/db/cat_event_handler.php');
// email sending
$this->registerClass('kEmail', KERNEL_PATH . '/utility/email.php');
$this->registerClass('kEmailSendingHelper', KERNEL_PATH . '/utility/email_send.php', 'EmailSender');
$this->registerClass('kSocket', KERNEL_PATH . '/utility/socket.php', 'Socket');
// Testing.
$this->registerClass('Page', KERNEL_PATH . '/tests/Page/Page.php');
$this->registerClass('QAToolsUrlBuilder', KERNEL_PATH . '/tests/Url/QAToolsUrlBuilder.php');
$this->registerClass('QAToolsUrlFactory', KERNEL_PATH . '/tests/Url/QAToolsUrlFactory.php');
$this->registerClass('AbstractTestCase', KERNEL_PATH . '/../tests/AbstractTestCase.php');
$this->registerClass('AbstractBrowserTestCase', KERNEL_PATH . '/../tests/AbstractBrowserTestCase.php');
// do not move to config - this helper is used before configs are read
$this->registerClass('kModulesHelper', KERNEL_PATH . self::MODULE_HELPER_PATH, 'ModulesHelper');
$this->registerClass('CKEditor', FULL_PATH . '/core/ckeditor/ckeditor_php5.php');
}
/**
* Registers default build events
*
* @return void
*/
public function RegisterDefaultBuildEvents()
{
$this->EventManager->registerBuildEvent('kTempTablesHandler', 'OnTempHandlerBuild');
}
/**
* Returns cached category information by given cache name. All given category
* information is recached, when at least one of 4 caches is missing.
*
* @param int $category_id
* @param string $name cache name = {filenames, category_designs, category_tree}
* @return string
* @access public
*/
public function getCategoryCache($category_id, $name)
{
return $this->cacheManager->getCategoryCache($category_id, $name);
}
/**
* Returns caching type (none, memory, temporary)
*
* @param int $caching_type
* @return bool
* @access public
*/
public function isCachingType($caching_type)
{
return $this->cacheManager->isCachingType($caching_type);
}
/**
* Increments serial based on prefix and it's ID (optional)
*
* @param string $prefix
* @param int $id ID (value of IDField) or ForeignKeyField:ID
* @param bool $increment
* @return string
* @access public
*/
public function incrementCacheSerial($prefix, $id = null, $increment = true)
{
return $this->cacheManager->incrementCacheSerial($prefix, $id, $increment);
}
/**
* Returns cached $key value from cache named $cache_name
*
* @param int $key key name from cache
* @param bool $store_locally store data locally after retrieved
* @param int $max_rebuild_seconds
* @return mixed
* @access public
*/
public function getCache($key, $store_locally = true, $max_rebuild_seconds = 0)
{
return $this->cacheManager->getCache($key, $store_locally, $max_rebuild_seconds);
}
/**
* Stores new $value in cache with $name name.
*
* @param string $name Key name to add to cache.
* @param mixed $value Value of cached record.
* @param integer|null $expiration When value expires (0 - doesn't expire).
*
* @return boolean
*/
public function setCache($name, $value, $expiration = null)
{
return $this->cacheManager->setCache($name, $value, $expiration);
}
/**
* Stores new $value in cache with $key name (only if it's not there)
*
* @param string $name Key name to add to cache.
* @param mixed $value Value of cached record.
* @param integer|null $expiration When value expires (0 - doesn't expire).
*
* @return boolean
*/
public function addCache($name, $value, $expiration = null)
{
return $this->cacheManager->addCache($name, $value, $expiration);
}
/**
* Sets rebuilding mode for given cache
*
* @param string $name
* @param int $mode
* @param int $max_rebuilding_time
* @return bool
* @access public
*/
public function rebuildCache($name, $mode = null, $max_rebuilding_time = 0)
{
return $this->cacheManager->rebuildCache($name, $mode, $max_rebuilding_time);
}
/**
* Deletes key from cache
*
* @param string $key
* @return void
* @access public
*/
public function deleteCache($key)
{
$this->cacheManager->deleteCache($key);
}
/**
* Reset's all memory cache at once
*
* @return void
* @access public
*/
public function resetCache()
{
$this->cacheManager->resetCache();
}
/**
* Returns value from database cache
*
* @param string $name key name
* @param int $max_rebuild_seconds
* @return mixed
* @access public
*/
public function getDBCache($name, $max_rebuild_seconds = 0)
{
return $this->cacheManager->getDBCache($name, $max_rebuild_seconds);
}
/**
* Sets value to database cache.
*
* @param string $name Key name to add to cache.
* @param mixed $value Value of cached record.
* @param integer|null $expiration When value expires (0 - doesn't expire).
*
* @return void
*/
public function setDBCache($name, $value, $expiration = null)
{
$this->cacheManager->setDBCache($name, $value, $expiration);
}
/**
* Sets rebuilding mode for given cache
*
* @param string $name
* @param int $mode
* @param int $max_rebuilding_time
* @return bool
* @access public
*/
public function rebuildDBCache($name, $mode = null, $max_rebuilding_time = 0)
{
return $this->cacheManager->rebuildDBCache($name, $mode, $max_rebuilding_time);
}
/**
* Deletes key from database cache
*
* @param string $name
* @return void
* @access public
*/
public function deleteDBCache($name)
{
$this->cacheManager->deleteDBCache($name);
}
/**
* Registers each module specific constants if any found
*
* @return bool
* @access protected
*/
protected function registerModuleConstants()
{
if ( file_exists(KERNEL_PATH . '/constants.php') ) {
kUtil::includeOnce(KERNEL_PATH . '/constants.php');
}
if ( !$this->ModuleInfo ) {
return false;
}
foreach ($this->ModuleInfo as $module_info) {
$constants_file = FULL_PATH . '/' . $module_info['Path'] . 'constants.php';
if ( file_exists($constants_file) ) {
kUtil::includeOnce($constants_file);
}
}
return true;
}
/**
* Performs redirect to hard maintenance template
*
* @return void
* @access public
*/
public function redirectToMaintenance()
{
$maintenance_page = WRITEBALE_BASE . '/maintenance.html';
$query_string = ''; // $this->isAdmin ? '' : '?next_template=' . kUtil::escape($_SERVER['REQUEST_URI'], kUtil::ESCAPE_URL);
if ( file_exists(FULL_PATH . $maintenance_page) ) {
header('Location: ' . BASE_PATH . $maintenance_page . $query_string);
exit;
}
}
/**
* Actually runs the parser against current template and stores parsing result
*
* This method gets 't' variable passed to the script, loads the template given in 't' variable and
* parses it. The result is store in {@link $this->HTML} property.
*
* @return void
* @access public
*/
public function Run()
{
// process maintenance mode redirect: begin
$maintenance_mode = $this->getMaintenanceMode();
if ( $maintenance_mode == MaintenanceMode::HARD ) {
$this->redirectToMaintenance();
}
elseif ( $maintenance_mode == MaintenanceMode::SOFT ) {
$maintenance_template = $this->isAdmin ? 'login' : $this->ConfigValue('SoftMaintenanceTemplate');
if ( $this->GetVar('t') != $maintenance_template ) {
$redirect_params = Array ();
if ( !$this->isAdmin ) {
$redirect_params['next_template'] = $_SERVER['REQUEST_URI'];
}
$this->Redirect($maintenance_template, $redirect_params);
}
}
// process maintenance mode redirect: end
if ( defined('DEBUG_MODE') && $this->isDebugMode() && kUtil::constOn('DBG_PROFILE_MEMORY') ) {
$this->Debugger->appendMemoryUsage('Application before Run:');
}
if ( $this->isAdminUser ) {
// for permission checking in events & templates
$this->LinkVar('module'); // for common configuration templates
$this->LinkVar('module_key'); // for common search templates
$this->LinkVar('section'); // for common configuration templates
if ( $this->GetVar('m_opener') == 'p' ) {
$this->LinkVar('main_prefix'); // window prefix, that opened selector
$this->LinkVar('dst_field'); // field to set value choosed in selector
}
if ( $this->GetVar('ajax') == 'yes' && !$this->GetVar('debug_ajax') ) {
// hide debug output from ajax requests automatically
kUtil::safeDefine('DBG_SKIP_REPORTING', 1); // safeDefine, because debugger also defines it
}
}
$this->Phrases->setPhraseEditing();
$this->EventManager->ProcessRequest();
$this->InitParser();
$t = $this->GetVar('render_template', $this->GetVar('t'));
if ( !$this->TemplatesCache->TemplateExists($t) && !$this->isAdmin ) {
/** @var CategoriesEventHandler $cms_handler */
$cms_handler = $this->recallObject('st_EventHandler');
$t = ltrim($cms_handler->GetDesignTemplate(), '/');
if ( defined('DEBUG_MODE') && $this->isDebugMode() ) {
$this->Debugger->appendHTML('<strong>Design Template</strong>: ' . $t . '; <strong>CategoryID</strong>: ' . $this->GetVar('m_cat_id'));
}
}
/*else {
$cms_handler->SetCatByTemplate();
}*/
if ( defined('DEBUG_MODE') && $this->isDebugMode() && kUtil::constOn('DBG_PROFILE_MEMORY') ) {
$this->Debugger->appendMemoryUsage('Application before Parsing:');
}
$this->HTML = $this->Parser->Run($t);
if ( defined('DEBUG_MODE') && $this->isDebugMode() && kUtil::constOn('DBG_PROFILE_MEMORY') ) {
$this->Debugger->appendMemoryUsage('Application after Parsing:');
}
}
/**
* Replaces current rendered template with given one.
*
* @param string|null $template Template.
*
* @return void
*/
public function QuickRun($template)
{
/** @var kThemesHelper $themes_helper */
$themes_helper = $this->recallObject('ThemesHelper');
// Set Web Request variables to affect link building on template itself.
$this->SetVar('t', $template);
$this->SetVar('m_cat_id', $themes_helper->getPageByTemplate($template));
$this->SetVar('passed', 'm');
// Replace current page content with given template.
$this->InitParser();
$this->Parser->Clear();
$this->HTML = $this->Parser->Run($template);
}
/**
* Performs template parser/cache initialization
*
* @param bool|string $theme_name
* @return void
* @access public
*/
public function InitParser($theme_name = false)
{
if ( !is_object($this->Parser) ) {
$this->Parser = $this->recallObject('NParser');
$this->TemplatesCache = $this->recallObject('TemplatesCache');
}
$this->TemplatesCache->forceThemeName = $theme_name;
}
/**
* Send the parser results to browser
*
* Actually send everything stored in {@link $this->HTML}, to the browser by echoing it.
*
* @return void
* @access public
*/
public function Done()
{
$this->HandleEvent(new kEvent('adm:OnBeforeShutdown'));
$debug_mode = defined('DEBUG_MODE') && $this->isDebugMode();
if ( $debug_mode ) {
if ( kUtil::constOn('DBG_PROFILE_MEMORY') ) {
$this->Debugger->appendMemoryUsage('Application before Done:');
}
$this->Session->SaveData(); // adds session data to debugger report
$this->HTML = ob_get_clean() . $this->HTML . $this->Debugger->printReport(true);
}
else {
// send "Set-Cookie" header before any output is made
$this->Session->SetSession();
$this->HTML = ob_get_clean() . $this->HTML;
}
$this->_outputPage();
$this->cacheManager->UpdateApplicationCache();
if ( !$debug_mode ) {
$this->Session->SaveData();
}
$this->EventManager->runScheduledTasks();
if ( defined('DBG_CAPTURE_STATISTICS') && DBG_CAPTURE_STATISTICS && !$this->isAdmin ) {
$this->_storeStatistics();
}
}
/**
* Outputs generated page content to end-user
*
* @return void
* @access protected
*/
protected function _outputPage()
{
$this->setContentType();
ob_start();
if ( $this->UseOutputCompression() ) {
$compression_level = $this->ConfigValue('OutputCompressionLevel');
if ( !$compression_level || $compression_level < 0 || $compression_level > 9 ) {
$compression_level = 7;
}
header('Content-Encoding: gzip');
echo gzencode($this->HTML, $compression_level);
}
else {
// when gzip compression not used connection won't be closed early!
echo $this->HTML;
}
// send headers to tell the browser to close the connection
header('Content-Length: ' . ob_get_length());
header('Connection: close');
// flush all output
ob_end_flush();
if ( ob_get_level() ) {
ob_flush();
}
flush();
// close current session
if ( session_id() ) {
session_write_close();
}
}
/**
* Stores script execution statistics to database
*
* @return void
* @access protected
*/
protected function _storeStatistics()
{
global $start;
$this->Conn->noDebuggingState = true;
$script_time = microtime(true) - $start;
$query_statistics = $this->Conn->getQueryStatistics(); // time & count
$sql = 'SELECT *
FROM ' . TABLE_PREFIX . 'StatisticsCapture
WHERE TemplateName = ' . $this->Conn->qstr($this->GetVar('t'));
$data = $this->Conn->GetRow($sql);
if ( $data ) {
$this->_updateAverageStatistics($data, 'ScriptTime', $script_time);
$this->_updateAverageStatistics($data, 'SqlTime', $query_statistics['time']);
$this->_updateAverageStatistics($data, 'SqlCount', $query_statistics['count']);
$data['Hits']++;
$data['LastHit'] = adodb_mktime();
$this->Conn->doUpdate($data, TABLE_PREFIX . 'StatisticsCapture', 'StatisticsId = ' . $data['StatisticsId']);
}
else {
$data = array();
$data['ScriptTimeMin'] = $data['ScriptTimeAvg'] = $data['ScriptTimeMax'] = $script_time;
$data['SqlTimeMin'] = $data['SqlTimeAvg'] = $data['SqlTimeMax'] = $query_statistics['time'];
$data['SqlCountMin'] = $data['SqlCountAvg'] = $data['SqlCountMax'] = $query_statistics['count'];
$data['TemplateName'] = $this->GetVar('t');
$data['Hits'] = 1;
$data['LastHit'] = adodb_mktime();
$this->Conn->doInsert($data, TABLE_PREFIX . 'StatisticsCapture');
}
$this->Conn->noDebuggingState = false;
}
/**
* Calculates average time for statistics
*
* @param Array $data
* @param string $field_prefix
* @param float $current_value
* @return void
* @access protected
*/
protected function _updateAverageStatistics(&$data, $field_prefix, $current_value)
{
$data[$field_prefix . 'Avg'] = (($data['Hits'] * $data[$field_prefix . 'Avg']) + $current_value) / ($data['Hits'] + 1);
if ( $current_value < $data[$field_prefix . 'Min'] ) {
$data[$field_prefix . 'Min'] = $current_value;
}
if ( $current_value > $data[$field_prefix . 'Max'] ) {
$data[$field_prefix . 'Max'] = $current_value;
}
}
/**
* Remembers slow query SQL and execution time into log
*
* @param string $slow_sql
* @param int $time
* @return void
* @access public
*/
public function logSlowQuery($slow_sql, $time)
{
$this->Conn->noDebuggingState = true;
$query_crc = kUtil::crc32($slow_sql);
$sql = 'SELECT *
FROM ' . TABLE_PREFIX . 'SlowSqlCapture
WHERE QueryCrc = ' . $query_crc;
$data = $this->Conn->Query($sql);
if ( $data ) {
$data = array_shift($data); // Because "Query" method (supports $no_debug) is used instead of "GetRow".
$this->_updateAverageStatistics($data, 'Time', $time);
$template_names = explode(',', $data['TemplateNames']);
array_push($template_names, $this->GetVar('t'));
$data['TemplateNames'] = implode(',', array_unique($template_names));
$data['Hits']++;
$data['LastHit'] = adodb_mktime();
$this->Conn->doUpdate($data, TABLE_PREFIX . 'SlowSqlCapture', 'CaptureId = ' . $data['CaptureId']);
}
else {
$data = array();
$data['TimeMin'] = $data['TimeAvg'] = $data['TimeMax'] = $time;
$data['SqlQuery'] = $slow_sql;
$data['QueryCrc'] = $query_crc;
$data['TemplateNames'] = $this->GetVar('t');
$data['Hits'] = 1;
$data['LastHit'] = adodb_mktime();
$this->Conn->doInsert($data, TABLE_PREFIX . 'SlowSqlCapture');
}
$this->Conn->noDebuggingState = false;
}
/**
* Checks if output compression options is available
*
* @return bool
* @access protected
*/
protected function UseOutputCompression()
{
if ( kUtil::constOn('IS_INSTALL') || kUtil::constOn('DBG_ZEND_PRESENT') || kUtil::constOn('SKIP_OUT_COMPRESSION') ) {
return false;
}
$accept_encoding = isset($_SERVER['HTTP_ACCEPT_ENCODING']) ? $_SERVER['HTTP_ACCEPT_ENCODING'] : '';
return $this->ConfigValue('UseOutputCompression') && function_exists('gzencode') && strstr($accept_encoding, 'gzip');
}
// Facade
/**
* Returns current session id (SID)
*
- * @return int
- * @access public
+ * @param integer $purpose Purpose.
+ *
+ * @return integer
*/
- public function GetSID()
+ public function GetSID($purpose = Session::PURPOSE_TRANSPORT)
{
/** @var Session $session */
$session = $this->recallObject('Session');
- return $session->GetID();
+ return $session->GetID($purpose);
}
/**
* Destroys current session
*
* @return void
* @access public
* @see UserHelper::logoutUser()
*/
public function DestroySession()
{
/** @var Session $session */
$session = $this->recallObject('Session');
$session->Destroy();
}
/**
* Returns variable passed to the script as GET/POST/COOKIE
*
* @param string $name Name of variable to retrieve
* @param mixed $default default value returned in case if variable not present
* @return mixed
* @access public
*/
public function GetVar($name, $default = false)
{
return isset($this->HttpQuery->_Params[$name]) ? $this->HttpQuery->_Params[$name] : $default;
}
/**
* Returns filtered variable passed to the script as GET/POST/COOKIE
*
* @param string $name Name of variable to retrieve.
* @param mixed $default Default value returned in case if variable not present.
* @param integer $filter The ID of the filter to apply.
* @param array|integer $options Associative array of options or bitwise disjunction of flags.
*
* @return mixed
*/
public function GetVarFiltered($name, $default = false, $filter = FILTER_DEFAULT, $options = 0)
{
if ( isset($this->HttpQuery->_Params[$name]) ) {
$filtered_value = filter_var($this->HttpQuery->_Params[$name], $filter, $options);
if ( $filtered_value !== false ) {
return $filtered_value;
}
}
return $default;
}
/**
* Removes forceful escaping done to the variable upon Front-End submission.
*
* @param string|array $value Value.
*
* @return string|array
* @see kHttpQuery::StripSlashes
* @todo Temporary method for marking problematic places to take care of, when forceful escaping will be removed.
*/
public function unescapeRequestVariable($value)
{
return $this->HttpQuery->unescapeRequestVariable($value);
}
/**
* Returns variable passed to the script as $type
*
* @param string $name Name of variable to retrieve
* @param string $type Get/Post/Cookie
* @param mixed $default default value returned in case if variable not present
* @return mixed
* @access public
*/
public function GetVarDirect($name, $type, $default = false)
{
// $type = ucfirst($type);
$array = $this->HttpQuery->$type;
return isset($array[$name]) ? $array[$name] : $default;
}
/**
* Returns ALL variables passed to the script as GET/POST/COOKIE
*
* @return Array
* @access public
* @deprecated
*/
public function GetVars()
{
return $this->HttpQuery->GetParams();
}
/**
* Set the variable 'as it was passed to the script through GET/POST/COOKIE'
*
* This could be useful to set the variable when you know that
* other objects would relay on variable passed from GET/POST/COOKIE
* or you could use SetVar() / GetVar() pairs to pass the values between different objects.<br>
*
* @param string $var Variable name to set
* @param mixed $val Variable value
* @return void
* @access public
*/
public function SetVar($var,$val)
{
$this->HttpQuery->Set($var, $val);
}
/**
* Deletes kHTTPQuery variable
*
* @param string $var
* @return void
* @todo Think about method name
*/
public function DeleteVar($var)
{
$this->HttpQuery->Remove($var);
}
/**
* Deletes Session variable
*
* @param string $var
* @return void
* @access public
*/
public function RemoveVar($var)
{
$this->Session->RemoveVar($var);
}
/**
* Removes variable from persistent session
*
* @param string $var
* @return void
* @access public
*/
public function RemovePersistentVar($var)
{
$this->Session->RemovePersistentVar($var);
}
/**
* Restores Session variable to it's db version
*
* @param string $var
* @return void
* @access public
*/
public function RestoreVar($var)
{
$this->Session->RestoreVar($var);
}
/**
* Returns session variable value
*
* Return value of $var variable stored in Session. An optional default value could be passed as second parameter.
*
* @param string $var Variable name
* @param mixed $default Default value to return if no $var variable found in session
* @return mixed
* @access public
* @see Session::RecallVar()
*/
public function RecallVar($var,$default=false)
{
return $this->Session->RecallVar($var,$default);
}
/**
* Returns variable value from persistent session
*
* @param string $var
* @param mixed $default
* @return mixed
* @access public
* @see Session::RecallPersistentVar()
*/
public function RecallPersistentVar($var, $default = false)
{
return $this->Session->RecallPersistentVar($var, $default);
}
/**
* Stores variable $val in session under name $var
*
* Use this method to store variable in session. Later this variable could be recalled.
*
* @param string $var Variable name
* @param mixed $val Variable value
* @param bool $optional
* @return void
* @access public
* @see kApplication::RecallVar()
*/
public function StoreVar($var, $val, $optional = false)
{
/** @var Session $session */
$session = $this->recallObject('Session');
$this->Session->StoreVar($var, $val, $optional);
}
/**
* Stores variable to persistent session
*
* @param string $var
* @param mixed $val
* @param bool $optional
* @return void
* @access public
*/
public function StorePersistentVar($var, $val, $optional = false)
{
$this->Session->StorePersistentVar($var, $val, $optional);
}
/**
* Stores default value for session variable
*
* @param string $var
* @param string $val
* @param bool $optional
* @return void
* @access public
* @see Session::RecallVar()
* @see Session::StoreVar()
*/
public function StoreVarDefault($var, $val, $optional = false)
{
/** @var Session $session */
$session = $this->recallObject('Session');
$this->Session->StoreVarDefault($var, $val, $optional);
}
/**
* Links HTTP Query variable with session variable
*
* If variable $var is passed in HTTP Query it is stored in session for later use. If it's not passed it's recalled from session.
* This method could be used for making sure that GetVar will return query or session value for given
* variable, when query variable should overwrite session (and be stored there for later use).<br>
* This could be used for passing item's ID into popup with multiple tab -
* in popup script you just need to call LinkVar('id', 'current_id') before first use of GetVar('id').
* After that you can be sure that GetVar('id') will return passed id or id passed earlier and stored in session
*
* @param string $var HTTP Query (GPC) variable name
* @param mixed $ses_var Session variable name
* @param mixed $default Default variable value
* @param bool $optional
* @return void
* @access public
*/
public function LinkVar($var, $ses_var = null, $default = '', $optional = false)
{
if ( !isset($ses_var) ) {
$ses_var = $var;
}
if ( $this->GetVar($var) !== false ) {
$this->StoreVar($ses_var, $this->GetVar($var), $optional);
}
else {
$this->SetVar($var, $this->RecallVar($ses_var, $default));
}
}
/**
* Returns variable from HTTP Query, or from session if not passed in HTTP Query
*
* The same as LinkVar, but also returns the variable value taken from HTTP Query if passed, or from session if not passed.
* Returns the default value if variable does not exist in session and was not passed in HTTP Query
*
* @param string $var HTTP Query (GPC) variable name
* @param mixed $ses_var Session variable name
* @param mixed $default Default variable value
* @return mixed
* @access public
* @see LinkVar
*/
public function GetLinkedVar($var, $ses_var = null, $default = '')
{
$this->LinkVar($var, $ses_var, $default);
return $this->GetVar($var);
}
/**
* Renders given tag and returns it's output
*
* @param string $prefix
* @param string $tag
* @param Array $params
* @return mixed
* @access public
* @see kApplication::InitParser()
*/
public function ProcessParsedTag($prefix, $tag, $params)
{
/** @var kDBTagProcessor $processor */
$processor = $this->Parser->GetProcessor($prefix);
return $processor->ProcessParsedTag($tag, $params, $prefix);
}
/**
* Return object of IDBConnection interface
*
* Return object of IDBConnection interface already connected to the project database, configurable in config.php
*
* @return IDBConnection
* @access public
*/
public function &GetADODBConnection()
{
return $this->Conn;
}
/**
* Allows to parse given block name or include template
*
* @param Array $params Parameters to pass to block. Reserved parameter "name" used to specify block name.
* @param bool $pass_params Forces to pass current parser params to this block/template. Use with caution, because you can accidentally pass "block_no_data" parameter.
* @param bool $as_template
* @return string
* @access public
*/
public function ParseBlock($params, $pass_params = false, $as_template = false)
{
if ( substr($params['name'], 0, 5) == 'html:' ) {
return substr($params['name'], 5);
}
return $this->Parser->ParseBlock($params, $pass_params, $as_template);
}
/**
* Checks, that we have given block defined
*
* @param string $name
* @return bool
* @access public
*/
public function ParserBlockFound($name)
{
return $this->Parser->blockFound($name);
}
/**
* Allows to include template with a given name and given parameters
*
* @param Array $params Parameters to pass to template. Reserved parameter "name" used to specify template name.
* @return string
* @access public
*/
public function IncludeTemplate($params)
{
return $this->Parser->IncludeTemplate($params, isset($params['is_silent']) ? 1 : 0);
}
/**
* Return href for template
*
* @param string $t Template path
* @param string $prefix index.php prefix - could be blank, 'admin'
* @param Array $params
* @param string $index_file
* @return string
*/
public function HREF($t, $prefix = '', $params = Array (), $index_file = null)
{
return $this->UrlManager->HREF($t, $prefix, $params, $index_file);
}
/**
* Returns theme template filename and it's corresponding page_id based on given seo template
*
* @param string $seo_template
* @return string
* @access public
*/
public function getPhysicalTemplate($seo_template)
{
return $this->UrlManager->getPhysicalTemplate($seo_template);
}
/**
* Returns template name, that corresponds with given virtual (not physical) page id
*
* @param int $page_id
* @return string|bool
* @access public
*/
public function getVirtualPageTemplate($page_id)
{
return $this->UrlManager->getVirtualPageTemplate($page_id);
}
/**
* Returns section template for given physical/virtual template
*
* @param string $template
* @param int $theme_id
* @return string
* @access public
*/
public function getSectionTemplate($template, $theme_id = null)
{
return $this->UrlManager->getSectionTemplate($template, $theme_id);
}
/**
* Returns variables with values that should be passed through with this link + variable list
*
* @param Array $params
* @return Array
* @access public
*/
public function getPassThroughVariables(&$params)
{
return $this->UrlManager->getPassThroughVariables($params);
}
/**
* Builds url
*
* @param string $t
* @param Array $params
* @param string $pass
* @param bool $pass_events
* @param bool $env_var
* @return string
* @access public
*/
public function BuildEnv($t, $params, $pass = 'all', $pass_events = false, $env_var = true)
{
return $this->UrlManager->plain->build($t, $params, $pass, $pass_events, $env_var);
}
/**
* Process QueryString only, create
* events, ids, based on config
* set template name and sid in
* desired application variables.
*
* @param string $env_var environment string value
* @param string $pass_name
* @return Array
* @access public
*/
public function processQueryString($env_var, $pass_name = 'passed')
{
return $this->UrlManager->plain->parse($env_var, $pass_name);
}
/**
* Parses rewrite url and returns parsed variables
*
* @param string $url
* @param string $pass_name
* @return Array
* @access public
*/
public function parseRewriteUrl($url, $pass_name = 'passed')
{
return $this->UrlManager->rewrite->parse($url, $pass_name);
}
/**
* Returns base part of all urls, build on website
*
* @param string $prefix
* @param bool $ssl
* @param bool $add_port
* @return string
* @access public
*/
public function BaseURL($prefix = '', $ssl = null, $add_port = true)
{
if ( $ssl === null ) {
// stay on same encryption level
return PROTOCOL . SERVER_NAME . ($add_port && defined('PORT') ? ':' . PORT : '') . BASE_PATH . $prefix . '/';
}
if ( $ssl ) {
// going from http:// to https://
$base_url = $this->isAdmin ? $this->ConfigValue('AdminSSL_URL') : false;
if ( !$base_url ) {
$ssl_url = $this->siteDomainField('SSLUrl');
$base_url = $ssl_url !== false ? $ssl_url : $this->ConfigValue('SSL_URL');
}
return rtrim($base_url, '/') . $prefix . '/';
}
// going from https:// to http://
$domain = $this->siteDomainField('DomainName');
if ( $domain === false ) {
$domain = DOMAIN;
}
return 'http://' . $domain . ($add_port && defined('PORT') ? ':' . PORT : '') . BASE_PATH . $prefix . '/';
}
/**
* Redirects user to url, that's build based on given parameters
*
* @param string $t
* @param Array $params
* @param string $prefix
* @param string $index_file
* @return void
* @access public
*/
public function Redirect($t = '', $params = Array(), $prefix = '', $index_file = null)
{
$js_redirect = getArrayValue($params, 'js_redirect');
if ( $t == '' || $t === true ) {
$t = $this->GetVar('t');
}
// pass prefixes and special from previous url
if ( array_key_exists('js_redirect', $params) ) {
unset($params['js_redirect']);
}
// allows to send custom responce code along with redirect header
if ( array_key_exists('response_code', $params) ) {
$response_code = (int)$params['response_code'];
unset($params['response_code']);
}
else {
$response_code = 302; // Found
}
if ( !array_key_exists('pass', $params) ) {
$params['pass'] = 'all';
}
if ( $this->GetVar('ajax') == 'yes' && $t == $this->GetVar('t') ) {
// redirects to the same template as current
$params['ajax'] = 'yes';
}
$location = $this->HREF($t, $prefix, $params, $index_file);
if ( $this->isDebugMode() && (kUtil::constOn('DBG_REDIRECT') || (kUtil::constOn('DBG_RAISE_ON_WARNINGS') && $this->Debugger->WarningCount)) ) {
$this->Debugger->appendTrace();
echo '<strong>Debug output above !!!</strong><br/>' . "\n";
if ( array_key_exists('HTTP_REFERER', $_SERVER) ) {
echo 'Referer: <strong>' . kUtil::escape($_SERVER['HTTP_REFERER'], kUtil::ESCAPE_HTML) . '</strong><br/>' . "\n";
}
echo "Proceed to redirect: <a href=\"{$location}\">{$location}</a><br/>\n";
}
else {
if ( $js_redirect ) {
// show "redirect" template instead of redirecting,
// because "Set-Cookie" header won't work, when "Location"
// header is used later
$this->SetVar('t', 'redirect');
$this->SetVar('redirect_to', $location);
// make all additional parameters available on "redirect" template too
foreach ($params as $name => $value) {
$this->SetVar($name, $value);
}
return;
}
else {
if ( $this->GetVar('ajax') == 'yes' && ($t != $this->GetVar('t') || !$this->isSOPSafe($location, $t)) ) {
// redirection to other then current template during ajax request OR SOP violation
kUtil::safeDefine('DBG_SKIP_REPORTING', 1);
echo '#redirect#' . $location;
}
elseif ( headers_sent() != '' ) {
// some output occurred -> redirect using javascript
echo '<script type="text/javascript">window.location.href = \'' . kUtil::escape($location, kUtil::ESCAPE_JS) . '\';</script>';
}
else {
// no output before -> redirect using HTTP header
// header('HTTP/1.1 302 Found');
header('Location: ' . $location, true, $response_code);
}
}
}
// session expiration is called from session initialization,
// that's why $this->Session may be not defined here
/** @var Session $session */
$session = $this->recallObject('Session');
if ( $this->InitDone ) {
// if redirect happened in the middle of application initialization don't call event,
// that presumes that application was successfully initialized
$this->HandleEvent(new kEvent('adm:OnBeforeShutdown'));
}
$session->SaveData();
ob_end_flush();
exit;
}
/**
* Determines if real redirect should be made within AJAX request.
*
* @param string $url Location.
* @param string $template Template.
*
* @return boolean
* @link http://en.wikipedia.org/wiki/Same-origin_policy
*/
protected function isSOPSafe($url, $template)
{
$parsed_url = parse_url($url);
if ( $parsed_url['scheme'] . '://' != PROTOCOL ) {
return false;
}
if ( $parsed_url['host'] != SERVER_NAME ) {
return false;
}
if ( defined('PORT') && isset($parsed_url['port']) && $parsed_url['port'] != PORT ) {
return false;
}
return true;
}
/**
* Returns translation of given label
*
* @param string $label
* @param bool $allow_editing return translation link, when translation is missing on current language
* @param bool $use_admin use current Admin Console language to translate phrase
* @return string
* @access public
*/
public function Phrase($label, $allow_editing = true, $use_admin = false)
{
return $this->Phrases->GetPhrase($label, $allow_editing, $use_admin);
}
/**
* Replace language tags in exclamation marks found in text
*
* @param string $text
* @param bool $force_escape force escaping, not escaping of resulting string
* @return string
* @access public
*/
public function ReplaceLanguageTags($text, $force_escape = null)
{
return $this->Phrases->ReplaceLanguageTags($text, $force_escape);
}
/**
* Checks if user is logged in, and creates
* user object if so. User object can be recalled
* later using "u.current" prefix_special. Also you may
* get user id by getting "u.current_id" variable.
*
* @return void
* @access protected
*/
protected function ValidateLogin()
{
/** @var Session $session */
$session = $this->recallObject('Session');
$user_id = $session->GetField('PortalUserId');
if ( !$user_id && $user_id != USER_ROOT ) {
$user_id = USER_GUEST;
}
$this->SetVar('u.current_id', $user_id);
if ( !$this->isAdmin ) {
// needed for "profile edit", "registration" forms ON FRONT ONLY
$this->SetVar('u_id', $user_id);
}
$this->StoreVar('user_id', $user_id, $user_id == USER_GUEST); // storing Guest user_id (-2) is optional
$this->isAdminUser = $this->isAdmin && $this->LoggedIn();
if ( $this->GetVar('expired') == 1 ) {
// this parameter is set only from admin
/** @var UsersItem $user */
$user = $this->recallObject('u.login-admin', null, Array ('form_name' => 'login'));
$user->SetError('UserLogin', 'session_expired', 'la_text_sess_expired');
}
$this->HandleEvent(new kEvent('adm:OnLogHttpRequest'));
if ( $user_id != USER_GUEST ) {
// normal users + root
$this->LoadPersistentVars();
}
$user_timezone = $this->Session->GetField('TimeZone');
if ( $user_timezone ) {
date_default_timezone_set($user_timezone);
}
}
/**
* Loads current user persistent session data
*
* @return void
* @access public
*/
public function LoadPersistentVars()
{
$this->Session->LoadPersistentVars();
}
/**
* Returns configuration option value by name
*
* @param string $name
* @return string
* @access public
*/
public function ConfigValue($name)
{
return $this->cacheManager->ConfigValue($name);
}
/**
* Changes value of individual configuration variable (+resets cache, when needed)
*
* @param string $name
* @param string $value
* @param bool $local_cache_only
* @return string
* @access public
*/
public function SetConfigValue($name, $value, $local_cache_only = false)
{
return $this->cacheManager->SetConfigValue($name, $value, $local_cache_only);
}
/**
* Allows to process any type of event
*
* @param kEvent $event
* @param Array $params
* @param Array $specific_params
* @return void
* @access public
*/
public function HandleEvent($event, $params = null, $specific_params = null)
{
if ( isset($params) ) {
$event = new kEvent($params, $specific_params);
}
$this->EventManager->HandleEvent($event);
}
/**
* Notifies event subscribers, that event has occured
*
* @param kEvent $event
* @return void
*/
public function notifyEventSubscribers(kEvent $event)
{
$this->EventManager->notifySubscribers($event);
}
/**
* Allows to process any type of event
*
* @param kEvent $event
* @return bool
* @access public
*/
public function eventImplemented(kEvent $event)
{
return $this->EventManager->eventImplemented($event);
}
/**
* Registers new class in the factory
*
* @param string $real_class Real name of class as in class declaration
* @param string $file Filename in what $real_class is declared
* @param string $pseudo_class Name under this class object will be accessed using getObject method
* @return void
* @access public
*/
public function registerClass($real_class, $file, $pseudo_class = null)
{
$this->Factory->registerClass($real_class, $file, $pseudo_class);
}
/**
* Unregisters existing class from factory
*
* @param string $real_class Real name of class as in class declaration
* @param string $pseudo_class Name under this class object is accessed using getObject method
* @return void
* @access public
*/
public function unregisterClass($real_class, $pseudo_class = null)
{
$this->Factory->unregisterClass($real_class, $pseudo_class);
}
/**
* Finds the absolute path to the file where the class is defined.
*
* @param string $class The name of the class.
*
* @return string|false
*/
public function findClassFile($class)
{
return $this->Factory->findClassFile($class);
}
/**
* Add new scheduled task
*
* @param string $short_name name to be used to store last maintenance run info
* @param string $event_string
* @param int $run_schedule run schedule like for Cron
* @param int $status
* @access public
*/
public function registerScheduledTask($short_name, $event_string, $run_schedule, $status = STATUS_ACTIVE)
{
$this->EventManager->registerScheduledTask($short_name, $event_string, $run_schedule, $status);
}
/**
* Registers Hook from subprefix event to master prefix event
*
* Pattern: Observer
*
* @param string $hook_event
* @param string $do_event
* @param int $mode
* @param bool $conditional
* @access public
*/
public function registerHook($hook_event, $do_event, $mode = hAFTER, $conditional = false)
{
$this->EventManager->registerHook($hook_event, $do_event, $mode, $conditional);
}
/**
* Registers build event for given pseudo class
*
* @param string $pseudo_class
* @param string $event_name
* @access public
*/
public function registerBuildEvent($pseudo_class, $event_name)
{
$this->EventManager->registerBuildEvent($pseudo_class, $event_name);
}
/**
* Allows one TagProcessor tag act as other TagProcessor tag
*
* @param Array $tag_info
* @return void
* @access public
*/
public function registerAggregateTag($tag_info)
{
/** @var kArray $aggregator */
$aggregator = $this->recallObject('TagsAggregator', 'kArray');
$tag_data = Array (
$tag_info['LocalPrefix'],
$tag_info['LocalTagName'],
getArrayValue($tag_info, 'LocalSpecial')
);
$aggregator->SetArrayValue($tag_info['AggregateTo'], $tag_info['AggregatedTagName'], $tag_data);
}
/**
* Returns object using params specified, creates it if is required
*
* @param string $name
* @param string $pseudo_class
* @param Array $event_params
* @param Array $arguments
* @return kBase
*/
public function recallObject($name, $pseudo_class = null, array $event_params = array(), array $arguments = array())
{
/*if ( !$this->hasObject($name) && $this->isDebugMode() && ($name == '_prefix_here_') ) {
// first time, when object with "_prefix_here_" prefix is accessed
$this->Debugger->appendTrace();
}*/
return $this->Factory->getObject($name, $pseudo_class, $event_params, $arguments);
}
/**
* Returns tag processor for prefix specified
*
* @param string $prefix
* @return kDBTagProcessor
* @access public
*/
public function recallTagProcessor($prefix)
{
$this->InitParser(); // because kDBTagProcesor is in NParser dependencies
return $this->recallObject($prefix . '_TagProcessor');
}
/**
* Checks if object with prefix passes was already created in factory
*
* @param string $name object pseudo_class, prefix
* @return bool
* @access public
*/
public function hasObject($name)
{
return $this->Factory->hasObject($name);
}
/**
* Removes object from storage by given name
*
* @param string $name Object's name in the Storage
* @return void
* @access public
*/
public function removeObject($name)
{
$this->Factory->DestroyObject($name);
}
/**
* Get's real class name for pseudo class, includes class file and creates class instance
*
* Pattern: Factory Method
*
* @param string $pseudo_class
* @param Array $arguments
* @return kBase
* @access public
*/
public function makeClass($pseudo_class, array $arguments = array())
{
return $this->Factory->makeClass($pseudo_class, $arguments);
}
/**
* Checks if application is in debug mode
*
* @param bool $check_debugger check if kApplication debugger is initialized too, not only for defined DEBUG_MODE constant
* @return bool
* @author Alex
* @access public
*/
public function isDebugMode($check_debugger = true)
{
$debug_mode = defined('DEBUG_MODE') && DEBUG_MODE;
if ($check_debugger) {
$debug_mode = $debug_mode && is_object($this->Debugger);
}
return $debug_mode;
}
/**
* Apply url rewriting used by mod_rewrite or not
*
* @param bool|null $ssl Force ssl link to be build
* @return bool
* @access public
*/
public function RewriteURLs($ssl = false)
{
// case #1,#4:
// we want to create https link from http mode
// we want to create https link from https mode
// conditions: ($ssl || PROTOCOL == 'https://') && $this->ConfigValue('UseModRewriteWithSSL')
// case #2,#3:
// we want to create http link from https mode
// we want to create http link from http mode
// conditions: !$ssl && (PROTOCOL == 'https://' || PROTOCOL == 'http://')
$allow_rewriting =
(!$ssl && (PROTOCOL == 'https://' || PROTOCOL == 'http://')) // always allow mod_rewrite for http
|| // or allow rewriting for redirect TO httpS or when already in httpS
(($ssl || PROTOCOL == 'https://') && $this->ConfigValue('UseModRewriteWithSSL')); // but only if it's allowed in config!
return kUtil::constOn('MOD_REWRITE') && $allow_rewriting;
}
/**
* Reads unit (specified by $prefix)
* option specified by $option
*
* @param string $prefix
* @param string $option
* @param mixed $default
* @return string
* @access public
*/
public function getUnitOption($prefix, $option, $default = false)
{
return $this->UnitConfigReader->getUnitOption($prefix, $option, $default);
}
/**
* Set's new unit option value
*
* @param string $prefix
* @param string $option
* @param string $value
* @access public
*/
public function setUnitOption($prefix, $option, $value)
{
$this->UnitConfigReader->setUnitOption($prefix,$option,$value);
}
/**
* Read all unit with $prefix options
*
* @param string $prefix
* @return Array
* @access public
*/
public function getUnitOptions($prefix)
{
return $this->UnitConfigReader->getUnitOptions($prefix);
}
/**
* Returns true if config exists and is allowed for reading
*
* @param string $prefix
* @return bool
*/
public function prefixRegistred($prefix)
{
return $this->UnitConfigReader->prefixRegistred($prefix);
}
/**
* Splits any mixing of prefix and
* special into correct ones
*
* @param string $prefix_special
* @return Array
* @access public
*/
public function processPrefix($prefix_special)
{
return $this->Factory->processPrefix($prefix_special);
}
/**
* Set's new event for $prefix_special
* passed
*
* @param string $prefix_special
* @param string $event_name
* @return void
* @access public
*/
public function setEvent($prefix_special, $event_name)
{
$this->EventManager->setEvent($prefix_special, $event_name);
}
/**
* SQL Error Handler
*
* @param int $code
* @param string $msg
* @param string $sql
* @return bool
* @access public
* @throws Exception
* @deprecated
*/
public function handleSQLError($code, $msg, $sql)
{
return $this->_logger->handleSQLError($code, $msg, $sql);
}
/**
* Returns & blocks next ResourceId available in system
*
* @return int
* @access public
*/
public function NextResourceId()
{
$table_name = TABLE_PREFIX . 'IdGenerator';
$this->Conn->Query('LOCK TABLES ' . $table_name . ' WRITE');
$this->Conn->Query('UPDATE ' . $table_name . ' SET lastid = lastid + 1');
$id = $this->Conn->GetOne('SELECT lastid FROM ' . $table_name);
if ( $id === false ) {
$this->Conn->Query('INSERT INTO ' . $table_name . ' (lastid) VALUES (2)');
$id = 2;
}
$this->Conn->Query('UNLOCK TABLES');
return $id - 1;
}
/**
* Returns genealogical main prefix for sub-table prefix passes
* OR prefix, that has been found in REQUEST and some how is parent of passed sub-table prefix
*
* @param string $current_prefix
* @param bool $real_top if set to true will return real topmost prefix, regardless of its id is passed or not
* @return string
* @access public
*/
public function GetTopmostPrefix($current_prefix, $real_top = false)
{
// 1. get genealogical tree of $current_prefix
$prefixes = Array ($current_prefix);
while ($parent_prefix = $this->getUnitOption($current_prefix, 'ParentPrefix')) {
if ( !$this->prefixRegistred($parent_prefix) ) {
// stop searching, when parent prefix is not registered
break;
}
$current_prefix = $parent_prefix;
array_unshift($prefixes, $current_prefix);
}
if ( $real_top ) {
return $current_prefix;
}
// 2. find what if parent is passed
$passed = explode(',', $this->GetVar('all_passed'));
foreach ($prefixes as $a_prefix) {
if ( in_array($a_prefix, $passed) ) {
return $a_prefix;
}
}
return $current_prefix;
}
/**
* Triggers email event of type Admin
*
* @param string $email_template_name
* @param int $to_user_id
* @param array $send_params associative array of direct send params, possible keys: to_email, to_name, from_email, from_name, message, message_text
* @return kEvent
* @access public
*/
public function emailAdmin($email_template_name, $to_user_id = null, $send_params = Array ())
{
return $this->_email($email_template_name, EmailTemplate::TEMPLATE_TYPE_ADMIN, $to_user_id, $send_params);
}
/**
* Triggers email event of type User
*
* @param string $email_template_name
* @param int $to_user_id
* @param array $send_params associative array of direct send params, possible keys: to_email, to_name, from_email, from_name, message, message_text
* @return kEvent
* @access public
*/
public function emailUser($email_template_name, $to_user_id = null, $send_params = Array ())
{
return $this->_email($email_template_name, EmailTemplate::TEMPLATE_TYPE_FRONTEND, $to_user_id, $send_params);
}
/**
* Triggers general email event
*
* @param string $email_template_name
* @param int $email_template_type (0 for User, 1 for Admin)
* @param int $to_user_id
* @param array $send_params associative array of direct send params,
* possible keys: to_email, to_name, from_email, from_name, message, message_text
* @return kEvent
* @access protected
*/
protected function _email($email_template_name, $email_template_type, $to_user_id = null, $send_params = Array ())
{
/** @var kEmail $email */
$email = $this->makeClass('kEmail');
if ( !$email->findTemplate($email_template_name, $email_template_type) ) {
return false;
}
$email->setParams($send_params);
return $email->send($to_user_id);
}
/**
* Allows to check if user in this session is logged in or not
*
* @return bool
* @access public
*/
public function LoggedIn()
{
// no session during expiration process
return is_null($this->Session) ? false : $this->Session->LoggedIn();
}
/**
* Determines if access permissions should not be checked.
*
* @param integer|null $user_id User ID.
*
* @return boolean
*/
public function permissionCheckingDisabled($user_id = null)
{
if ( !isset($user_id) ) {
$user_id = $this->RecallVar('user_id');
}
return $user_id == USER_ROOT;
}
/**
* Check current user permissions based on it's group permissions in specified category
*
* @param string $name permission name
* @param int $cat_id category id, current used if not specified
* @param int $type permission type {1 - system, 0 - per category}
* @return int
* @access public
*/
public function CheckPermission($name, $type = 1, $cat_id = null)
{
/** @var kPermissionsHelper $perm_helper */
$perm_helper = $this->recallObject('PermissionsHelper');
return $perm_helper->CheckPermission($name, $type, $cat_id);
}
/**
* Check current admin permissions based on it's group permissions in specified category
*
* @param string $name permission name
* @param int $cat_id category id, current used if not specified
* @param int $type permission type {1 - system, 0 - per category}
* @return int
* @access public
*/
public function CheckAdminPermission($name, $type = 1, $cat_id = null)
{
/** @var kPermissionsHelper $perm_helper */
$perm_helper = $this->recallObject('PermissionsHelper');
return $perm_helper->CheckAdminPermission($name, $type, $cat_id);
}
/**
* Set's any field of current visit
*
* @param string $field
* @param mixed $value
* @return void
* @access public
* @todo move to separate module
*/
public function setVisitField($field, $value)
{
if ( $this->isAdmin || !$this->ConfigValue('UseVisitorTracking') ) {
// admin logins are not registered in visits list
return;
}
/** @var kDBItem $visit */
$visit = $this->recallObject('visits', null, Array ('raise_warnings' => 0));
if ( $visit->isLoaded() ) {
$visit->SetDBField($field, $value);
$visit->Update();
}
}
/**
* Allows to check if in-portal is installed
*
* @return bool
* @access public
*/
public function isInstalled()
{
return $this->InitDone && (count($this->ModuleInfo) > 0);
}
/**
* Allows to determine if module is installed & enabled
*
* @param string $module_name
* @return bool
* @access public
*/
public function isModuleEnabled($module_name)
{
return $this->findModule('Name', $module_name) !== false;
}
/**
* Returns Window ID of passed prefix main prefix (in edit mode)
*
* @param string $prefix
* @return int
* @access public
*/
public function GetTopmostWid($prefix)
{
$top_prefix = $this->GetTopmostPrefix($prefix);
$mode = $this->GetVar($top_prefix . '_mode');
return $mode != '' ? substr($mode, 1) : '';
}
/**
* Get temp table name
*
* @param string $table
* @param mixed $wid
* @return string
* @access public
*/
public function GetTempName($table, $wid = '')
{
return $this->GetTempTablePrefix($wid) . $table;
}
/**
* Builds temporary table prefix based on given window id
*
- * @param string $wid
+ * @param string $wid Window ID.
+ *
* @return string
- * @access public
*/
public function GetTempTablePrefix($wid = '')
{
if ( preg_match('/prefix:(.*)/', $wid, $regs) ) {
$wid = $this->GetTopmostWid($regs[1]);
}
- return TABLE_PREFIX . 'ses_' . $this->GetSID() . ($wid ? '_' . $wid : '') . '_edit_';
+ return TABLE_PREFIX . 'ses_' . $this->GetSID(Session::PURPOSE_REFERENCE) . ($wid ? '_' . $wid : '') . '_edit_';
}
/**
* Checks if given table is a temporary table
*
* @param string $table
* @return bool
* @access public
*/
public function IsTempTable($table)
{
static $cache = Array ();
if ( !array_key_exists($table, $cache) ) {
- $cache[$table] = preg_match('/' . TABLE_PREFIX . 'ses_' . $this->GetSID() . '(_[\d]+){0,1}_edit_(.*)/', $table);
+ $cache[$table] = $table !== $this->GetLiveName($table);
}
return (bool)$cache[$table];
}
/**
* Checks, that given prefix is in temp mode
*
* @param string $prefix
* @param string $special
* @return bool
* @access public
*/
public function IsTempMode($prefix, $special = '')
{
$top_prefix = $this->GetTopmostPrefix($prefix);
$var_names = Array (
$top_prefix,
rtrim($top_prefix . '_' . $special, '_'), // from post
rtrim($top_prefix . '.' . $special, '.'), // assembled locally
);
$var_names = array_unique($var_names);
$temp_mode = false;
foreach ($var_names as $var_name) {
$value = $this->GetVar($var_name . '_mode');
if ( $value && (substr($value, 0, 1) == 't') ) {
$temp_mode = true;
break;
}
}
return $temp_mode;
}
/**
* Return live table name based on temp table name
*
* @param string $temp_table
* @return string
*/
public function GetLiveName($temp_table)
{
- if ( preg_match('/' . TABLE_PREFIX . 'ses_' . $this->GetSID() . '(_[\d]+){0,1}_edit_(.*)/', $temp_table, $rets) ) {
- // cut wid from table end if any
- return $rets[2];
- }
- else {
- return $temp_table;
+ if ( preg_match('/' . TABLE_PREFIX . 'ses_([\d]+)(_[\d]+){0,1}_edit_(.*)/', $temp_table, $rets) ) {
+ // Cut wid from table end if any.
+ return $rets[3];
}
+
+ return $temp_table;
}
/**
* Stops processing of user request and displays given message
*
* @param string $message
* @access public
*/
public function ApplicationDie($message = '')
{
while ( ob_get_level() ) {
ob_end_clean();
}
if ( $this->isDebugMode() ) {
$message .= $this->Debugger->printReport(true);
}
$this->HTML = $message;
$this->_outputPage();
}
/**
* Returns comma-separated list of groups from given user
*
* @param int $user_id
* @return string
*/
public function getUserGroups($user_id)
{
switch ($user_id) {
case USER_ROOT:
$user_groups = $this->ConfigValue('User_LoggedInGroup');
break;
case USER_GUEST:
$user_groups = $this->ConfigValue('User_LoggedInGroup') . ',' . $this->ConfigValue('User_GuestGroup');
break;
default:
$sql = 'SELECT GroupId
FROM ' . TABLE_PREFIX . 'UserGroupRelations
WHERE PortalUserId = ' . (int)$user_id;
$res = $this->Conn->GetCol($sql);
$user_groups = Array ($this->ConfigValue('User_LoggedInGroup'));
if ( $res ) {
$user_groups = array_merge($user_groups, $res);
}
$user_groups = implode(',', $user_groups);
}
return $user_groups;
}
/**
* Allows to detect if page is browsed by spider (293 scheduled_tasks supported)
*
* @return bool
* @access public
*/
/*public function IsSpider()
{
static $is_spider = null;
if ( !isset($is_spider) ) {
$user_agent = trim($_SERVER['HTTP_USER_AGENT']);
$robots = file(FULL_PATH . '/core/robots_list.txt');
foreach ($robots as $robot_info) {
$robot_info = explode("\t", $robot_info, 3);
if ( $user_agent == trim($robot_info[2]) ) {
$is_spider = true;
break;
}
}
}
return $is_spider;
}*/
/**
* Allows to detect table's presence in database
*
* @param string $table_name
* @param bool $force
* @return bool
* @access public
*/
public function TableFound($table_name, $force = false)
{
return $this->Conn->TableFound($table_name, $force);
}
/**
* Returns counter value
*
* @param string $name counter name
* @param Array $params counter parameters
* @param string $query_name specify query name directly (don't generate from parameters)
* @param bool $multiple_results
* @return mixed
* @access public
*/
public function getCounter($name, $params = Array (), $query_name = null, $multiple_results = false)
{
/** @var kCountHelper $count_helper */
$count_helper = $this->recallObject('CountHelper');
return $count_helper->getCounter($name, $params, $query_name, $multiple_results);
}
/**
* Resets counter, which are affected by one of specified tables
*
* @param string $tables comma separated tables list used in counting sqls
* @return void
* @access public
*/
public function resetCounters($tables)
{
if ( kUtil::constOn('IS_INSTALL') ) {
return;
}
/** @var kCountHelper $count_helper */
$count_helper = $this->recallObject('CountHelper');
$count_helper->resetCounters($tables);
}
/**
* Sends XML header + optionally displays xml heading
*
* @param string|bool $xml_version
* @return string
* @access public
* @author Alex
*/
public function XMLHeader($xml_version = false)
{
$this->setContentType('text/xml');
return $xml_version ? '<?xml version="' . $xml_version . '" encoding="' . CHARSET . '"?>' : '';
}
/**
* Returns category tree
*
* @param int $category_id
* @return Array
* @access public
*/
public function getTreeIndex($category_id)
{
$tree_index = $this->getCategoryCache($category_id, 'category_tree');
if ( $tree_index ) {
$ret = Array ();
list ($ret['TreeLeft'], $ret['TreeRight']) = explode(';', $tree_index);
return $ret;
}
return false;
}
/**
* Base category of all categories
* Usually replaced category, with ID = 0 in category-related operations.
*
* @return int
* @access public
*/
public function getBaseCategory()
{
// same, what $this->findModule('Name', 'Core', 'RootCat') does
// don't cache while IS_INSTALL, because of kInstallToolkit::createModuleCategory and upgrade
return $this->ModuleInfo['Core']['RootCat'];
}
/**
* Deletes all data, that was cached during unit config parsing (excluding unit config locations)
*
* @param Array $config_variables
* @access public
*/
public function DeleteUnitCache($config_variables = null)
{
$this->cacheManager->DeleteUnitCache($config_variables);
}
/**
* Deletes cached section tree, used during permission checking and admin console tree display
*
* @return void
* @access public
*/
public function DeleteSectionCache()
{
$this->cacheManager->DeleteSectionCache();
}
/**
* Sets data from cache to object
*
* @param Array $data
* @access public
*/
public function setFromCache(&$data)
{
$this->Factory->setFromCache($data);
$this->UnitConfigReader->setFromCache($data);
$this->EventManager->setFromCache($data);
$this->ReplacementTemplates = $data['Application.ReplacementTemplates'];
$this->RewriteListeners = $data['Application.RewriteListeners'];
$this->ModuleInfo = $data['Application.ModuleInfo'];
}
/**
* Gets object data for caching
* The following caches should be reset based on admin interaction (adjusting config, enabling modules etc)
*
* @access public
* @return Array
*/
public function getToCache()
{
return array_merge(
$this->Factory->getToCache(),
$this->UnitConfigReader->getToCache(),
$this->EventManager->getToCache(),
Array (
'Application.ReplacementTemplates' => $this->ReplacementTemplates,
'Application.RewriteListeners' => $this->RewriteListeners,
'Application.ModuleInfo' => $this->ModuleInfo,
)
);
}
public function delayUnitProcessing($method, $params)
{
$this->cacheManager->delayUnitProcessing($method, $params);
}
/**
* Returns current maintenance mode state
*
* @param bool $check_ips
* @return int
* @access public
*/
public function getMaintenanceMode($check_ips = true)
{
$exception_ips = defined('MAINTENANCE_MODE_IPS') ? MAINTENANCE_MODE_IPS : '';
$setting_name = $this->isAdmin ? 'MAINTENANCE_MODE_ADMIN' : 'MAINTENANCE_MODE_FRONT';
if ( defined($setting_name) && constant($setting_name) > MaintenanceMode::NONE ) {
$exception_ip = $check_ips ? kUtil::ipMatch($exception_ips) : false;
if ( !$exception_ip ) {
return constant($setting_name);
}
}
return MaintenanceMode::NONE;
}
/**
* Sets content type of the page
*
* @param string $content_type
* @param bool $include_charset
* @return void
* @access public
*/
public function setContentType($content_type = 'text/html', $include_charset = null)
{
static $already_set = false;
if ( $already_set ) {
return;
}
$header = 'Content-type: ' . $content_type;
if ( !isset($include_charset) ) {
$include_charset = $content_type = 'text/html' || $content_type == 'text/plain' || $content_type = 'text/xml';
}
if ( $include_charset ) {
$header .= '; charset=' . CHARSET;
}
$already_set = true;
header($header);
}
/**
* Posts message to event log
*
* @param string $message
* @param int $code
* @param bool $write_now Allows further customization of log record by returning kLog object
* @return bool|int|kLogger
* @access public
*/
public function log($message, $code = null, $write_now = false)
{
$log = $this->_logger->prepare($message, $code)->addSource($this->_logger->createTrace(null, 1));
if ( $write_now ) {
return $log->write();
}
return $log;
}
/**
* Deletes log with given id from database or disk, when database isn't available
*
* @param int $unique_id
* @param int $storage_medium
* @return void
* @access public
* @throws InvalidArgumentException
*/
public function deleteLog($unique_id, $storage_medium = kLogger::LS_AUTOMATIC)
{
$this->_logger->delete($unique_id, $storage_medium);
}
/**
* Returns the client IP address.
*
* @return string The client IP address
* @access public
*/
public function getClientIp()
{
return $this->HttpQuery->getClientIp();
}
}
Index: branches/5.2.x/core/kernel/utility/debugger/debugger_responce.php
===================================================================
--- branches/5.2.x/core/kernel/utility/debugger/debugger_responce.php (revision 16796)
+++ branches/5.2.x/core/kernel/utility/debugger/debugger_responce.php (revision 16797)
@@ -1,83 +1,83 @@
<?php
/**
* @version $Id$
* @package In-Portal
* @copyright Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license GNU/GPL
* In-Portal is Open Source software.
* This means that this software may have been modified pursuant
* the GNU General Public License, and as distributed it includes
* or is derivative of works licensed under the GNU General Public License
* or other free or open source software licenses.
* See http://www.in-portal.org/license for copyright notices and details.
*/
set_time_limit(0);
ini_set('memory_limit', -1);
define('FULL_PATH', realpath(dirname(__FILE__) . '/../../../..'));
$sid = $_GET['sid'];
$path = isset($_GET['path']) ? $_GET['path'] : '/system/cache';
if ( (strpos($path, '../') !== false) || (trim($path) !== $path) ) {
// when relative paths or special chars are found template names from url, then it's hacking attempt
exit;
}
- if ( !preg_match('/^@([\d]+)@$/', $sid) ) {
+ if ( !preg_match('/^@[^@]+@$/', $sid) ) {
exit;
}
$debug_file = FULL_PATH . $path . '/debug_' . $sid . '.txt';
if ( file_exists($debug_file) ) {
$ret = file_get_contents($debug_file);
$ret = str_replace('#DBG_FILESIZE#', formatSize(filesize($debug_file)), $ret);
unlink($debug_file);
}
else {
$ret = 'file not found';
}
$accept_encoding = isset($_SERVER['HTTP_ACCEPT_ENCODING']) ? $_SERVER['HTTP_ACCEPT_ENCODING'] : '';
if ( function_exists('gzencode') && strstr($accept_encoding, 'gzip') ) {
header('Content-Encoding: gzip');
echo gzencode($ret);
}
else {
echo $ret;
}
/**
* Formats file/memory size in nice way
*
* @param int $bytes
* @return string
* @access public
*/
function formatSize($bytes)
{
if ( $bytes >= 1099511627776 ) {
$return = round($bytes / 1024 / 1024 / 1024 / 1024, 2);
$suffix = "TB";
}
elseif ( $bytes >= 1073741824 ) {
$return = round($bytes / 1024 / 1024 / 1024, 2);
$suffix = "GB";
}
elseif ( $bytes >= 1048576 ) {
$return = round($bytes / 1024 / 1024, 2);
$suffix = "MB";
}
elseif ( $bytes >= 1024 ) {
$return = round($bytes / 1024, 2);
$suffix = "KB";
}
else {
$return = $bytes;
$suffix = "Byte";
}
$return .= ' ' . $suffix;
return $return;
}
Index: branches/5.2.x/core/kernel/utility/temp_handler.php
===================================================================
--- branches/5.2.x/core/kernel/utility/temp_handler.php (revision 16796)
+++ branches/5.2.x/core/kernel/utility/temp_handler.php (revision 16797)
@@ -1,1139 +1,1139 @@
<?php
/**
* @version $Id$
* @package In-Portal
* @copyright Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license GNU/GPL
* In-Portal is Open Source software.
* This means that this software may have been modified pursuant
* the GNU General Public License, and as distributed it includes
* or is derivative of works licensed under the GNU General Public License
* or other free or open source software licenses.
* See http://www.in-portal.org/license for copyright notices and details.
*/
defined('FULL_PATH') or die('restricted access!');
class kTempTablesHandler extends kBase {
var $Tables = Array();
/**
* Master table name for temp handler
*
* @var string
* @access private
*/
var $MasterTable = '';
/**
* IDs from master table
*
* @var Array
* @access private
*/
var $MasterIDs = Array();
var $AlreadyProcessed = Array();
var $DroppedTables = Array();
var $FinalRefs = Array();
var $TableIdCounter = 0;
var $CopiedTables = Array();
/**
* Foreign key cache
*
* @var Array
*/
var $FKeysCache = Array ();
/**
* IDs of newly cloned items (key - prefix.special, value - array of ids)
*
* @var Array
*/
var $savedIDs = Array();
/**
* Window ID of current window
*
* @var mixed
*/
var $WindowID = '';
/**
* Event, that was used to create this object
*
* @var kEvent
* @access protected
*/
protected $parentEvent = null;
/**
* Sets new parent event to the object
*
* @param kEvent $event
* @return void
* @access public
*/
public function setParentEvent($event)
{
$this->parentEvent = $event;
}
function SetTables($tables)
{
// set table name as key for tables array
$this->Tables = $tables;
$this->MasterTable = $tables['TableName'];
}
function saveID($prefix, $special = '', $id = null)
{
if (!isset($this->savedIDs[$prefix.($special ? '.' : '').$special])) {
$this->savedIDs[$prefix.($special ? '.' : '').$special] = array();
}
if (is_array($id)) {
foreach ($id as $tmp_id => $live_id) {
$this->savedIDs[$prefix.($special ? '.' : '').$special][$tmp_id] = $live_id;
}
}
else {
$this->savedIDs[$prefix.($special ? '.' : '').$special][] = $id;
}
}
/**
* Get temp table name
*
* @param string $table
* @return string
*/
function GetTempName($table)
{
return $this->Application->GetTempName($table, $this->WindowID);
}
function GetTempTablePrefix()
{
return $this->Application->GetTempTablePrefix($this->WindowID);
}
/**
* Return live table name based on temp table name
*
* @param string $temp_table
* @return string
*/
function GetLiveName($temp_table)
{
return $this->Application->GetLiveName($temp_table);
}
function IsTempTable($table)
{
return $this->Application->IsTempTable($table);
}
/**
* Return temporary table name for master table
*
* @return string
* @access public
*/
function GetMasterTempName()
{
return $this->GetTempName($this->MasterTable);
}
function CreateTempTable($table)
{
$sql = 'CREATE TABLE ' . $this->GetTempName($table) . ' ENGINE = ' . $this->getTableEngine($table) . '
SELECT *
FROM ' . $table . '
WHERE 0';
$this->Conn->Query($sql);
}
/**
* Returns an engine of a given table.
*
* @param string $table Table.
*
* @return string
*/
protected function getTableEngine($table)
{
static $cache;
if ( $cache === null ) {
$sql = 'SHOW TABLE STATUS WHERE `Name` LIKE ' . $this->Conn->qstr(TABLE_PREFIX . '%');
$table_statuses = $this->Conn->GetIterator($sql, 'Name');
$cache = array();
foreach ( $table_statuses as $table_status_name => $table_status_data ) {
$cache[$table_status_name] = $table_status_data['Engine'];
}
}
return isset($cache[$table]) ? $cache[$table] : null;
}
function BuildTables($prefix, $ids)
{
$this->WindowID = $this->Application->GetVar('m_wid');
$this->TableIdCounter = 0;
$tables = Array(
'TableName' => $this->Application->getUnitOption($prefix, 'TableName'),
'IdField' => $this->Application->getUnitOption($prefix, 'IDField'),
'IDs' => $ids,
'Prefix' => $prefix,
'TableId' => $this->TableIdCounter++,
);
/*$parent_prefix = $this->Application->getUnitOption($prefix, 'ParentPrefix');
if ($parent_prefix) {
$tables['ForeignKey'] = $this->Application->getUnitOption($prefix, 'ForeignKey');
$tables['ParentPrefix'] = $parent_prefix;
$tables['ParentTableKey'] = $this->Application->getUnitOption($prefix, 'ParentTableKey');
}*/
$this->FinalRefs[ $tables['TableName'] ] = $tables['TableId']; // don't forget to add main table to FinalRefs too
/** @var Array $sub_items */
$sub_items = $this->Application->getUnitOption($prefix, 'SubItems', Array ());
if ( is_array($sub_items) ) {
foreach ($sub_items as $prefix) {
$this->AddTables($prefix, $tables);
}
}
$this->SetTables($tables);
}
/**
* Searches through TempHandler tables info for required prefix
*
* @param string $prefix
* @param Array $master
* @return mixed
*/
function SearchTable($prefix, $master = null)
{
if (is_null($master)) {
$master = $this->Tables;
}
if ($master['Prefix'] == $prefix) {
return $master;
}
if (isset($master['SubTables'])) {
foreach ($master['SubTables'] as $sub_table) {
$found = $this->SearchTable($prefix, $sub_table);
if ($found !== false) {
return $found;
}
}
}
return false;
}
function AddTables($prefix, &$tables)
{
if ( !$this->Application->prefixRegistred($prefix) ) {
// allows to skip subitem processing if subitem module not enabled/installed
return ;
}
$tmp = Array(
'TableName' => $this->Application->getUnitOption($prefix,'TableName'),
'IdField' => $this->Application->getUnitOption($prefix,'IDField'),
'ForeignKey' => $this->Application->getUnitOption($prefix,'ForeignKey'),
'ParentPrefix' => $this->Application->getUnitOption($prefix, 'ParentPrefix'),
'ParentTableKey' => $this->Application->getUnitOption($prefix,'ParentTableKey'),
'Prefix' => $prefix,
'AutoClone' => $this->Application->getUnitOption($prefix,'AutoClone'),
'AutoDelete' => $this->Application->getUnitOption($prefix,'AutoDelete'),
'TableId' => $this->TableIdCounter++,
);
$this->FinalRefs[ $tmp['TableName'] ] = $tmp['TableId'];
$constrain = $this->Application->getUnitOption($prefix, 'Constrain');
if ( $constrain ) {
$tmp['Constrain'] = $constrain;
$this->FinalRefs[ $tmp['TableName'] . $tmp['Constrain'] ] = $tmp['TableId'];
}
/** @var Array $sub_items */
$sub_items = $this->Application->getUnitOption($prefix, 'SubItems', Array ());
if ( is_array($sub_items) ) {
foreach ($sub_items as $prefix) {
$this->AddTables($prefix, $tmp);
}
}
if ( !is_array(getArrayValue($tables, 'SubTables')) ) {
$tables['SubTables'] = Array ();
}
$tables['SubTables'][] = $tmp;
}
function CloneItems($prefix, $special, $ids, $master = null, $foreign_key = null, $parent_prefix = null, $skip_filenames = false)
{
if (!isset($master)) $master = $this->Tables;
// recalling by different name, because we may get kDBList, if we recall just by prefix
if (!preg_match('/(.*)-item$/', $special)) {
$special .= '-item';
}
/** @var kCatDBItem $object */
$object = $this->Application->recallObject($prefix.'.'.$special, $prefix, Array('skip_autoload' => true, 'parent_event' => $this->parentEvent));
$object->PopulateMultiLangFields();
foreach ($ids as $id) {
$mode = 'create';
$cloned_ids = getArrayValue($this->AlreadyProcessed, $master['TableName']);
if ( $cloned_ids ) {
// if we have already cloned the id, replace it with cloned id and set mode to update
// update mode is needed to update second ForeignKey for items cloned by first ForeignKey
if ( getArrayValue($cloned_ids, $id) ) {
$id = $cloned_ids[$id];
$mode = 'update';
}
}
$object->Load($id);
$original_values = $object->GetFieldValues();
if (!$skip_filenames) {
$object->NameCopy($master, $foreign_key);
}
elseif ($master['TableName'] == $this->MasterTable) {
// kCatDBItem class only has this attribute
$object->useFilenames = false;
}
if (isset($foreign_key)) {
$master_foreign_key_field = is_array($master['ForeignKey']) ? $master['ForeignKey'][$parent_prefix] : $master['ForeignKey'];
$object->SetDBField($master_foreign_key_field, $foreign_key);
}
if ($mode == 'create') {
$this->RaiseEvent('OnBeforeClone', $master['Prefix'], $special, Array($object->GetId()), $foreign_key);
}
$object->inCloning = true;
$res = $mode == 'update' ? $object->Update() : $object->Create();
$object->inCloning = false;
if ($res)
{
if ( $mode == 'create' && is_array( getArrayValue($master, 'ForeignKey')) ) {
// remember original => clone mapping for dual ForeignKey updating
$this->AlreadyProcessed[$master['TableName']][$id] = $object->GetId();
}
if ($mode == 'create') {
$this->RaiseEvent('OnAfterClone', $master['Prefix'], $special, Array($object->GetId()), $foreign_key, array('original_id' => $id) );
$this->saveID($master['Prefix'], $special, $object->GetID());
}
if ( is_array(getArrayValue($master, 'SubTables')) ) {
foreach($master['SubTables'] as $sub_table) {
if (!getArrayValue($sub_table, 'AutoClone')) continue;
$sub_TableName = $object->IsTempTable() ? $this->GetTempName($sub_table['TableName']) : $sub_table['TableName'];
$foreign_key_field = is_array($sub_table['ForeignKey']) ? $sub_table['ForeignKey'][$master['Prefix']] : $sub_table['ForeignKey'];
$parent_key_field = is_array($sub_table['ParentTableKey']) ? $sub_table['ParentTableKey'][$master['Prefix']] : $sub_table['ParentTableKey'];
if (!$foreign_key_field || !$parent_key_field) continue;
$query = 'SELECT '.$sub_table['IdField'].' FROM '.$sub_TableName.'
WHERE '.$foreign_key_field.' = '.$original_values[$parent_key_field];
if (isset($sub_table['Constrain'])) $query .= ' AND '.$sub_table['Constrain'];
$sub_ids = $this->Conn->GetCol($query);
if ( is_array(getArrayValue($sub_table, 'ForeignKey')) ) {
// $sub_ids could containt newly cloned items, we need to remove it here
// to escape double cloning
$cloned_ids = getArrayValue($this->AlreadyProcessed, $sub_table['TableName']);
if ( !$cloned_ids ) $cloned_ids = Array();
$new_ids = array_values($cloned_ids);
$sub_ids = array_diff($sub_ids, $new_ids);
}
$parent_key = $object->GetDBField($parent_key_field);
$this->CloneItems($sub_table['Prefix'], $special, $sub_ids, $sub_table, $parent_key, $master['Prefix']);
}
}
}
}
if (!$ids) {
$this->savedIDs[$prefix.($special ? '.' : '').$special] = Array();
}
return $this->savedIDs[$prefix.($special ? '.' : '').$special];
}
function DeleteItems($prefix, $special, $ids, $master=null, $foreign_key=null)
{
if ( !$ids ) {
return;
}
if ( !isset($master) ) {
$master = $this->Tables;
}
if ( strpos($prefix, '.') !== false ) {
list($prefix, $special) = explode('.', $prefix, 2);
}
$prefix_special = rtrim($prefix . '.' . $special, '.');
//recalling by different name, because we may get kDBList, if we recall just by prefix
$recall_prefix = $prefix_special . ($special ? '' : '.') . '-item';
/** @var kDBItem $object */
$object = $this->Application->recallObject($recall_prefix, $prefix, Array ('skip_autoload' => true, 'parent_event' => $this->parentEvent));
foreach ($ids as $id) {
$object->Load($id);
$original_values = $object->GetFieldValues();
if ( !$object->Delete($id) ) {
continue;
}
if ( is_array(getArrayValue($master, 'SubTables')) ) {
foreach ($master['SubTables'] as $sub_table) {
if ( !getArrayValue($sub_table, 'AutoDelete') ) {
continue;
}
$sub_TableName = $object->IsTempTable() ? $this->GetTempName($sub_table['TableName']) : $sub_table['TableName'];
$foreign_key_field = is_array($sub_table['ForeignKey']) ? getArrayValue($sub_table, 'ForeignKey', $master['Prefix']) : $sub_table['ForeignKey'];
$parent_key_field = is_array($sub_table['ParentTableKey']) ? getArrayValue($sub_table, 'ParentTableKey', $master['Prefix']) : $sub_table['ParentTableKey'];
if ( !$foreign_key_field || !$parent_key_field ) {
continue;
}
$sql = 'SELECT ' . $sub_table['IdField'] . '
FROM ' . $sub_TableName . '
WHERE ' . $foreign_key_field . ' = ' . $original_values[$parent_key_field];
$sub_ids = $this->Conn->GetCol($sql);
$parent_key = $object->GetDBField(is_array($sub_table['ParentTableKey']) ? $sub_table['ParentTableKey'][$prefix] : $sub_table['ParentTableKey']);
$this->DeleteItems($sub_table['Prefix'], $special, $sub_ids, $sub_table, $parent_key);
}
}
}
}
function DoCopyLiveToTemp($master, $ids, $parent_prefix=null)
{
// when two tables refers the same table as sub-sub-table, and ForeignKey and ParentTableKey are arrays
// the table will be first copied by first sub-table, then dropped and copied over by last ForeignKey in the array
// this should not do any problems :)
if ( !preg_match("/.*\.[0-9]+/", $master['Prefix']) ) {
if( $this->DropTempTable($master['TableName']) )
{
$this->CreateTempTable($master['TableName']);
}
}
if (is_array($ids)) {
$ids = join(',', $ids);
}
$table_sig = $master['TableName'].(isset($master['Constrain']) ? $master['Constrain'] : '');
if ($ids != '' && !in_array($table_sig, $this->CopiedTables)) {
if ( getArrayValue($master, 'ForeignKey') ) {
if ( is_array($master['ForeignKey']) ) {
$key_field = $master['ForeignKey'][$parent_prefix];
}
else {
$key_field = $master['ForeignKey'];
}
}
else {
$key_field = $master['IdField'];
}
$query = 'INSERT INTO '.$this->GetTempName($master['TableName']).'
SELECT * FROM '.$master['TableName'].'
WHERE '.$key_field.' IN ('.$ids.')';
if (isset($master['Constrain'])) $query .= ' AND '.$master['Constrain'];
$this->Conn->Query($query);
$this->CopiedTables[] = $table_sig;
$query = 'SELECT '.$master['IdField'].' FROM '.$master['TableName'].'
WHERE '.$key_field.' IN ('.$ids.')';
if (isset($master['Constrain'])) $query .= ' AND '.$master['Constrain'];
$this->RaiseEvent( 'OnAfterCopyToTemp', $master['Prefix'], '', $this->Conn->GetCol($query) );
}
if ( getArrayValue($master, 'SubTables') ) {
foreach ($master['SubTables'] as $sub_table) {
$parent_key = is_array($sub_table['ParentTableKey']) ? $sub_table['ParentTableKey'][$master['Prefix']] : $sub_table['ParentTableKey'];
if (!$parent_key) continue;
if ( $ids != '' && $parent_key != $key_field ) {
$query = 'SELECT '.$parent_key.' FROM '.$master['TableName'].'
WHERE '.$key_field.' IN ('.$ids.')';
$sub_foreign_keys = join(',', $this->Conn->GetCol($query));
}
else {
$sub_foreign_keys = $ids;
}
$this->DoCopyLiveToTemp($sub_table, $sub_foreign_keys, $master['Prefix']);
}
}
}
function GetForeignKeys($master, $sub_table, $live_id, $temp_id=null)
{
$mode = 1; //multi
if (!is_array($live_id)) {
$live_id = Array($live_id);
$mode = 2; //single
}
if (isset($temp_id) && !is_array($temp_id)) $temp_id = Array($temp_id);
if ( isset($sub_table['ParentTableKey']) ) {
if ( is_array($sub_table['ParentTableKey']) ) {
$parent_key_field = $sub_table['ParentTableKey'][$master['Prefix']];
}
else {
$parent_key_field = $sub_table['ParentTableKey'];
}
}
else {
$parent_key_field = $master['IdField'];
}
$cached = getArrayValue($this->FKeysCache, $master['TableName'].'.'.$parent_key_field);
if ( $cached ) {
if ( array_key_exists(serialize($live_id), $cached) ) {
list($live_foreign_key, $temp_foreign_key) = $cached[serialize($live_id)];
if ($mode == 1) {
return $live_foreign_key;
}
else {
return Array($live_foreign_key[0], $temp_foreign_key[0]);
}
}
}
if ($parent_key_field != $master['IdField']) {
$query = 'SELECT '.$parent_key_field.' FROM '.$master['TableName'].'
WHERE '.$master['IdField'].' IN ('.join(',', $live_id).')';
$live_foreign_key = $this->Conn->GetCol($query);
if (isset($temp_id)) {
// because DoCopyTempToOriginal resets negative IDs to 0 in temp table (one by one) before copying to live
$temp_key = $temp_id < 0 ? 0 : $temp_id;
$query = 'SELECT '.$parent_key_field.' FROM '.$this->GetTempName($master['TableName']).'
WHERE '.$master['IdField'].' IN ('.join(',', $temp_key).')';
$temp_foreign_key = $this->Conn->GetCol($query);
}
else {
$temp_foreign_key = Array();
}
}
else {
$live_foreign_key = $live_id;
$temp_foreign_key = $temp_id;
}
$this->FKeysCache[$master['TableName'].'.'.$parent_key_field][serialize($live_id)] = Array($live_foreign_key, $temp_foreign_key);
if ($mode == 1) {
return $live_foreign_key;
}
else {
return Array($live_foreign_key[0], $temp_foreign_key[0]);
}
}
/**
* Copies data from temp to live table and returns IDs of copied records
*
* @param Array $master
* @param string $parent_prefix
* @param Array $current_ids
* @return Array
* @access public
*/
public function DoCopyTempToOriginal($master, $parent_prefix = null, $current_ids = Array())
{
$current_ids = $this->getMainIDs($master, $current_ids);
$table_sig = $master['TableName'] . (isset($master['Constrain']) ? $master['Constrain'] : '');
if ($current_ids) {
// delete all ids from live table - for MasterTable ONLY!
// because items from Sub Tables get deteleted in CopySubTablesToLive !BY ForeignKey!
if ( $master['TableName'] == $this->MasterTable ) {
$this->RaiseEvent('OnBeforeDeleteFromLive', $master['Prefix'], '', $current_ids);
$query = 'DELETE FROM ' . $master['TableName'] . ' WHERE ' . $master['IdField'] . ' IN (' . join(',', $current_ids) . ')';
$this->Conn->Query($query);
}
if ( getArrayValue($master, 'SubTables') ) {
if ( in_array($table_sig, $this->CopiedTables) || $this->FinalRefs[$table_sig] != $master['TableId'] ) {
return Array ();
}
foreach ($current_ids AS $id) {
$this->RaiseEvent('OnBeforeCopyToLive', $master['Prefix'], '', Array ($id));
//reset negative ids to 0, so autoincrement in live table works fine
if ( $id < 0 ) {
$query = ' UPDATE ' . $this->GetTempName($master['TableName']) . '
SET ' . $master['IdField'] . ' = 0
WHERE ' . $master['IdField'] . ' = ' . $id;
if ( isset($master['Constrain']) ) {
$query .= ' AND ' . $master['Constrain'];
}
$this->Conn->Query($query);
$id_to_copy = 0;
}
else {
$id_to_copy = $id;
}
//copy current id_to_copy (0 for new or real id) to live table
$query = ' INSERT INTO ' . $master['TableName'] . '
SELECT * FROM ' . $this->GetTempName($master['TableName']) . '
WHERE ' . $master['IdField'] . ' = ' . $id_to_copy;
$this->Conn->Query($query);
$insert_id = $id_to_copy == 0 ? $this->Conn->getInsertID() : $id_to_copy;
$this->saveID($master['Prefix'], '', array ($id => $insert_id));
$this->RaiseEvent('OnAfterCopyToLive', $master['Prefix'], '', Array ($insert_id), null, Array ('temp_id' => $id));
$this->UpdateForeignKeys($master, $insert_id, $id);
//delete already copied record from master temp table
$query = ' DELETE FROM ' . $this->GetTempName($master['TableName']) . '
WHERE ' . $master['IdField'] . ' = ' . $id_to_copy;
if ( isset($master['Constrain']) ) {
$query .= ' AND ' . $master['Constrain'];
}
$this->Conn->Query($query);
}
$this->CopiedTables[] = $table_sig;
// when all of ids in current master has been processed, copy all sub-tables data
$this->CopySubTablesToLive($master, $current_ids);
}
elseif ( !in_array($table_sig, $this->CopiedTables) && ($this->FinalRefs[$table_sig] == $master['TableId']) ) { //If current master doesn't have sub-tables - we could use mass operations
// We don't need to delete items from live here, as it get deleted in the beginning of the method for MasterTable
// or in parent table processing for sub-tables
$live_ids = Array ();
$this->RaiseEvent('OnBeforeCopyToLive', $master['Prefix'], '', $current_ids);
foreach ($current_ids as $an_id) {
if ( $an_id > 0 ) {
$live_ids[$an_id] = $an_id;
// positive (already live) IDs will be copied in on query all togather below,
// so we just store it here
continue;
}
else { // zero or negative ids should be copied one by one to get their InsertId
// resetting to 0 so it get inserted into live table with autoincrement
$query = ' UPDATE ' . $this->GetTempName($master['TableName']) . '
SET ' . $master['IdField'] . ' = 0
WHERE ' . $master['IdField'] . ' = ' . $an_id;
// constrain is not needed here because ID is already unique
$this->Conn->Query($query);
// copying
$query = ' INSERT INTO ' . $master['TableName'] . '
SELECT * FROM ' . $this->GetTempName($master['TableName']) . '
WHERE ' . $master['IdField'] . ' = 0';
$this->Conn->Query($query);
$live_ids[$an_id] = $this->Conn->getInsertID(); //storing newly created live id
//delete already copied record from master temp table
$query = ' DELETE FROM ' . $this->GetTempName($master['TableName']) . '
WHERE ' . $master['IdField'] . ' = 0';
$this->Conn->Query($query);
$this->UpdateChangeLogForeignKeys($master, $live_ids[$an_id], $an_id);
}
}
// copy ALL records to live table
$query = ' INSERT INTO ' . $master['TableName'] . '
SELECT * FROM ' . $this->GetTempName($master['TableName']);
if ( isset($master['Constrain']) ) {
$query .= ' WHERE ' . $master['Constrain'];
}
$this->Conn->Query($query);
$this->CopiedTables[] = $table_sig;
$this->RaiseEvent('OnAfterCopyToLive', $master['Prefix'], '', $live_ids);
$this->saveID($master['Prefix'], '', $live_ids);
// no need to clear temp table - it will be dropped by next statement
}
}
if ( $this->FinalRefs[ $master['TableName'] ] != $master['TableId'] ) {
return Array ();
}
/*if ( is_array(getArrayValue($master, 'ForeignKey')) ) { //if multiple ForeignKeys
if ( $master['ForeignKey'][$parent_prefix] != end($master['ForeignKey']) ) {
return; // Do not delete temp table if not all ForeignKeys have been processed (current is not the last)
}
}*/
$this->DropTempTable($master['TableName']);
$this->Application->resetCounters($master['TableName']);
if ( !isset($this->savedIDs[ $master['Prefix'] ]) ) {
$this->savedIDs[ $master['Prefix'] ] = Array ();
}
return $this->savedIDs[ $master['Prefix'] ];
}
/**
* Returns IDs from main temp table.
*
* @param array $master Master table configuration.
* @param array $current_ids User provided IDs.
*
* @return array
*/
protected function getMainIDs(array $master, array $current_ids = array())
{
if ( $current_ids ) {
return $current_ids;
}
$sql = 'SELECT ' . $master['IdField'] . '
FROM ' . $this->GetTempName($master['TableName']);
if ( isset($master['Constrain']) ) {
$sql .= ' WHERE ' . $master['Constrain'];
}
return $this->Conn->GetCol($sql);
}
/**
* Create separate connection for locking purposes
*
* @return kDBConnection
*/
function &_getSeparateConnection()
{
static $connection = null;
if (!isset($connection)) {
/** @var kDBConnection $connection */
$connection = $this->Application->makeClass( 'kDBConnection', Array (SQL_TYPE, Array ($this->Application, 'handleSQLError')) );
$connection->debugMode = $this->Application->isDebugMode();
$connection->Connect(SQL_SERVER, SQL_USER, SQL_PASS, SQL_DB);
}
return $connection;
}
function UpdateChangeLogForeignKeys($master, $live_id, $temp_id)
{
if ($live_id == $temp_id) {
return ;
}
$prefix = $master['Prefix'];
$main_prefix = $this->Application->GetTopmostPrefix($prefix);
$ses_var_name = $main_prefix . '_changes_' . $this->Application->GetTopmostWid($this->Prefix);
$changes = $this->Application->RecallVar($ses_var_name);
$changes = $changes ? unserialize($changes) : Array ();
foreach ($changes as $key => $rec) {
if ($rec['Prefix'] == $prefix && $rec['ItemId'] == $temp_id) {
// main item change log record
$changes[$key]['ItemId'] = $live_id;
}
if ($rec['MasterPrefix'] == $prefix && $rec['MasterId'] == $temp_id) {
// sub item change log record
$changes[$key]['MasterId'] = $live_id;
}
if (in_array($prefix, $rec['ParentPrefix']) && $rec['ParentId'][$prefix] == $temp_id) {
// parent item change log record
$changes[$key]['ParentId'][$prefix] = $live_id;
if (array_key_exists('DependentFields', $rec)) {
// these are fields from table of $rec['Prefix'] table!
// when one of dependent fields goes into idfield of it's parent item, that was changed
$parent_table_key = $this->Application->getUnitOption($rec['Prefix'], 'ParentTableKey');
$parent_table_key = is_array($parent_table_key) ? $parent_table_key[$prefix] : $parent_table_key;
if ($parent_table_key == $master['IdField']) {
$foreign_key = $this->Application->getUnitOption($rec['Prefix'], 'ForeignKey');
$foreign_key = is_array($foreign_key) ? $foreign_key[$prefix] : $foreign_key;
$changes[$key]['DependentFields'][$foreign_key] = $live_id;
}
}
}
}
$this->Application->StoreVar($ses_var_name, serialize($changes));
}
function UpdateForeignKeys($master, $live_id, $temp_id)
{
$this->UpdateChangeLogForeignKeys($master, $live_id, $temp_id);
foreach ($master['SubTables'] as $sub_table) {
$foreign_key_field = is_array($sub_table['ForeignKey']) ? getArrayValue($sub_table, 'ForeignKey', $master['Prefix']) : $sub_table['ForeignKey'];
if (!$foreign_key_field) {
continue;
}
list ($live_foreign_key, $temp_foreign_key) = $this->GetForeignKeys($master, $sub_table, $live_id, $temp_id);
//Update ForeignKey in sub TEMP table
if ($live_foreign_key != $temp_foreign_key) {
$query = 'UPDATE '.$this->GetTempName($sub_table['TableName']).'
SET '.$foreign_key_field.' = '.$live_foreign_key.'
WHERE '.$foreign_key_field.' = '.$temp_foreign_key;
if (isset($sub_table['Constrain'])) $query .= ' AND '.$sub_table['Constrain'];
$this->Conn->Query($query);
}
}
}
function CopySubTablesToLive($master, $current_ids) {
foreach ($master['SubTables'] as $sub_table) {
$table_sig = $sub_table['TableName'].(isset($sub_table['Constrain']) ? $sub_table['Constrain'] : '');
// delete records from live table by foreign key, so that records deleted from temp table
// get deleted from live
if (count($current_ids) > 0 && !in_array($table_sig, $this->CopiedTables) ) {
$foreign_key_field = is_array($sub_table['ForeignKey']) ? getArrayValue($sub_table, 'ForeignKey', $master['Prefix']) : $sub_table['ForeignKey'];
if (!$foreign_key_field) continue;
$foreign_keys = $this->GetForeignKeys($master, $sub_table, $current_ids);
if (count($foreign_keys) > 0) {
$query = 'SELECT '.$sub_table['IdField'].' FROM '.$sub_table['TableName'].'
WHERE '.$foreign_key_field.' IN ('.join(',', $foreign_keys).')';
if (isset($sub_table['Constrain'])) $query .= ' AND '.$sub_table['Constrain'];
if ( $this->RaiseEvent( 'OnBeforeDeleteFromLive', $sub_table['Prefix'], '', $this->Conn->GetCol($query), $foreign_keys ) ){
$query = 'DELETE FROM '.$sub_table['TableName'].'
WHERE '.$foreign_key_field.' IN ('.join(',', $foreign_keys).')';
if (isset($sub_table['Constrain'])) $query .= ' AND '.$sub_table['Constrain'];
$this->Conn->Query($query);
}
}
}
//sub_table passed here becomes master in the method, and recursively updated and copy its sub tables
$this->DoCopyTempToOriginal($sub_table, $master['Prefix']);
}
}
/**
* Raises event using IDs, that are currently being processed in temp handler
*
* @param string $name
* @param string $prefix
* @param string $special
* @param Array $ids
* @param string $foreign_key
* @param Array $add_params
* @return bool
* @access protected
*/
protected function RaiseEvent($name, $prefix, $special, $ids, $foreign_key = null, $add_params = null)
{
if ( !is_array($ids) ) {
return true;
}
$event_key = $prefix . ($special ? '.' : '') . $special . ':' . $name;
$event = new kEvent($event_key);
$event->MasterEvent = $this->parentEvent;
if ( isset($foreign_key) ) {
$event->setEventParam('foreign_key', $foreign_key);
}
$set_temp_id = ($name == 'OnAfterCopyToLive') && (!is_array($add_params) || !array_key_exists('temp_id', $add_params));
foreach ($ids as $index => $id) {
$event->setEventParam('id', $id);
if ( $set_temp_id ) {
$event->setEventParam('temp_id', $index);
}
if ( is_array($add_params) ) {
foreach ($add_params as $name => $val) {
$event->setEventParam($name, $val);
}
}
$this->Application->HandleEvent($event);
}
return $event->status == kEvent::erSUCCESS;
}
function DropTempTable($table)
{
if ( in_array($table, $this->DroppedTables) ) {
return false;
}
$query = 'DROP TABLE IF EXISTS ' . $this->GetTempName($table);
array_push($this->DroppedTables, $table);
$this->DroppedTables = array_unique($this->DroppedTables);
$this->Conn->Query($query);
return true;
}
function PrepareEdit()
{
$this->DoCopyLiveToTemp($this->Tables, $this->Tables['IDs']);
if ($this->Application->getUnitOption($this->Tables['Prefix'],'CheckSimulatniousEdit')) {
$this->CheckSimultaniousEdit();
}
}
function SaveEdit($master_ids = Array())
{
- // SessionKey field is required for deleting records from expired sessions
+ // SessionId field is required for deleting records from expired sessions.
$conn =& $this->_getSeparateConnection();
$sleep_count = 0;
$master_ids = $this->getMainIDs($this->Tables, $master_ids);
do {
// acquire lock
$conn->ChangeQuery('LOCK TABLES '.TABLE_PREFIX.'Semaphores WRITE');
$another_coping_active = false;
$sql = 'SELECT MainIDs
FROM ' . TABLE_PREFIX . 'Semaphores
WHERE MainPrefix = ' . $conn->qstr($this->Tables['Prefix']) . ' AND MainIDs <> "0"';
$other_semaphores_main_ids = $conn->GetCol($sql);
foreach ( $other_semaphores_main_ids as $other_semaphore_main_ids ) {
$other_semaphore_main_ids = explode(',', $other_semaphore_main_ids);
if ( array_intersect($master_ids, $other_semaphore_main_ids) ) {
$another_coping_active = true;
break;
}
}
if ($another_coping_active) {
// another user is coping data from temp table to live -> release lock and try again after 1 second
$conn->ChangeQuery('UNLOCK TABLES');
$sleep_count++;
sleep(1);
}
} while ($another_coping_active && ($sleep_count <= 30));
if ($sleep_count > 30) {
// Another coping process failed to finished in 30 seconds.
$error_message = $this->Application->Phrase('la_error_TemporaryTableCopyingFailed');
$this->Application->SetVar('_temp_table_message', $error_message);
$log = $this->Application->log('Parallel item saving attempt detected');
$log->addTrace();
$log->setLogLevel(kLogger::LL_ERROR);
$log->write();
return false;
}
/*
* Mark, that we are coping from temp to live right now,
* so other similar attempt (from another script) will fail.
*/
$semaphore_id = $this->createSemaphore($conn, $master_ids);
// unlock table now to prevent permanent lock in case, when coping will end with SQL error in the middle
$conn->ChangeQuery('UNLOCK TABLES');
$ids = $this->DoCopyTempToOriginal($this->Tables, null, $master_ids);
// remove mark, that we are coping from temp to live
$conn->Query('LOCK TABLES '.TABLE_PREFIX.'Semaphores WRITE');
$sql = 'DELETE FROM ' . TABLE_PREFIX . 'Semaphores
WHERE SemaphoreId = ' . $semaphore_id;
$conn->ChangeQuery($sql);
$conn->ChangeQuery('UNLOCK TABLES');
return $ids;
}
/**
* Creates a semaphore.
*
* @param IDBConnection $conn Database connection.
* @param array $master_ids Master record IDs.
*
* @return integer
*/
protected function createSemaphore(IDBConnection $conn, array $master_ids)
{
$fields_hash = array(
- 'SessionKey' => $this->Application->GetSID(),
+ 'SessionKey' => $this->Application->GetSID(Session::PURPOSE_STORAGE),
'Timestamp' => adodb_mktime(),
'MainPrefix' => $this->Tables['Prefix'],
'MainIDs' => implode(',', $master_ids),
'UserId' => $this->Application->RecallVar('user_id'),
'IPAddress' => $this->Application->getClientIp(),
'Hostname' => $_SERVER['HTTP_HOST'],
'RequestURI' => $_SERVER['REQUEST_URI'],
'Backtrace' => serialize(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS)),
);
$conn->doInsert($fields_hash, TABLE_PREFIX . 'Semaphores');
return $conn->getInsertID();
}
function CancelEdit($master=null)
{
if (!isset($master)) $master = $this->Tables;
$this->DropTempTable($master['TableName']);
if ( getArrayValue($master, 'SubTables') ) {
foreach ($master['SubTables'] as $sub_table) {
$this->CancelEdit($sub_table);
}
}
}
/**
* Checks, that someone is editing selected records and returns true, when no one.
*
* @param Array $ids
*
* @return bool
*/
function CheckSimultaniousEdit($ids = null)
{
$tables = $this->Conn->GetCol('SHOW TABLES');
$mask_edit_table = '/' . TABLE_PREFIX . 'ses_(.*)_edit_' . $this->MasterTable . '$/';
- $my_sid = $this->Application->GetSID();
+ $my_sid = $this->Application->GetSID(Session::PURPOSE_REFERENCE);
$my_wid = $this->Application->GetVar('m_wid');
$ids = implode(',', isset($ids) ? $ids : $this->Tables['IDs']);
$sids = Array ();
if (!$ids) {
return true;
}
foreach ($tables as $table) {
if ( preg_match($mask_edit_table, $table, $rets) ) {
$sid = preg_replace('/(.*)_(.*)/', '\\1', $rets[1]); // remove popup's wid from sid
if ($sid == $my_sid) {
if ($my_wid) {
// using popups for editing
if (preg_replace('/(.*)_(.*)/', '\\2', $rets[1]) == $my_wid) {
// don't count window, that is being opened right now
continue;
}
}
else {
// not using popups for editing -> don't count my session tables
continue;
}
}
$sql = 'SELECT COUNT(' . $this->Tables['IdField'] . ')
FROM ' . $table . '
WHERE ' . $this->Tables['IdField'] . ' IN (' . $ids . ')';
$found = $this->Conn->GetOne($sql);
if (!$found || in_array($sid, $sids)) {
continue;
}
$sids[] = $sid;
}
}
if ($sids) {
// detect who is it
$sql = 'SELECT
CONCAT(IF (s.PortalUserId = ' . USER_ROOT . ', \'root\',
IF (s.PortalUserId = ' . USER_GUEST . ', \'Guest\',
CONCAT(u.FirstName, \' \', u.LastName, \' (\', u.Username, \')\')
)
), \' IP: \', s.IpAddress, \'\') FROM ' . TABLE_PREFIX . 'UserSessions AS s
LEFT JOIN ' . TABLE_PREFIX . 'Users AS u
ON u.PortalUserId = s.PortalUserId
- WHERE s.SessionKey IN (' . implode(',', $sids) . ')';
+ WHERE s.SessionId IN (' . implode(',', $sids) . ')';
$users = $this->Conn->GetCol($sql);
if ($users) {
$this->Application->SetVar('_simultaneous_edit_message',
sprintf($this->Application->Phrase('la_record_being_edited_by'), join(",\n", $users))
);
return false;
}
}
return true;
}
}
Index: branches/5.2.x/core/kernel/utility/logger.php
===================================================================
--- branches/5.2.x/core/kernel/utility/logger.php (revision 16796)
+++ branches/5.2.x/core/kernel/utility/logger.php (revision 16797)
@@ -1,1606 +1,1606 @@
<?php
/**
* @version $Id$
* @package In-Portal
* @copyright Copyright (C) 1997 - 2012 Intechnic. All rights reserved.
* @license GNU/GPL
* In-Portal is Open Source software.
* This means that this software may have been modified pursuant
* the GNU General Public License, and as distributed it includes
* or is derivative of works licensed under the GNU General Public License
* or other free or open source software licenses.
* See http://www.in-portal.org/license for copyright notices and details.
*/
defined('FULL_PATH') or die('restricted access!');
/**
* Class for logging system activity
*/
class kLogger extends kBase {
/**
* Prefix of all database related errors
*/
const DB_ERROR_PREFIX = 'SQL Error:';
/**
* Logger state: logging of errors and user-defined messages
*/
const STATE_ENABLED = 1;
/**
* Logger state: logging of user-defined messages only
*/
const STATE_USER_ONLY = 2;
/**
* Logger state: don't log anything
*/
const STATE_DISABLED = 0;
/**
* Log store: automatically determine where log should be written
*/
const LS_AUTOMATIC = 1;
/**
* Log store: always write log to database
*/
const LS_DATABASE = 2;
/**
* Log store: always write log to disk
*/
const LS_DISK = 3;
/**
* Log level: system is unusable
*/
const LL_EMERGENCY = 0;
/**
* Log level: action must be taken immediately
*/
const LL_ALERT = 1;
/**
* Log level: the system is in a critical condition
*/
const LL_CRITICAL = 2;
/**
* Log level: there is an error condition
*/
const LL_ERROR = 3;
/**
* Log level: there is a warning condition
*/
const LL_WARNING = 4;
/**
* Log level: a normal but significant condition
*/
const LL_NOTICE = 5;
/**
* Log level: a purely informational message
*/
const LL_INFO = 6;
/**
* Log level: messages generated to debug the application
*/
const LL_DEBUG = 7;
/**
* Log type: PHP related activity
*/
const LT_PHP = 1;
/**
* Log type: database related activity
*/
const LT_DATABASE = 2;
/**
* Log type: custom activity
*/
const LT_OTHER = 3;
/**
* Log interface: Front
*/
const LI_FRONT = 1;
/**
* Log interface: Admin
*/
const LI_ADMIN = 2;
/**
* Log interface: Cron (Front)
*/
const LI_CRON_FRONT = 3;
/**
* Log interface: Cron (Admin)
*/
const LI_CRON_ADMIN = 4;
/**
* Log interface: API
*/
const LI_API = 5;
/**
* Log notification status: disabled
*/
const LNS_DISABLED = 0;
/**
* Log notification status: pending
*/
const LNS_PENDING = 1;
/**
* Log notification status: sent
*/
const LNS_SENT = 2;
/**
* Database connection used for logging.
*
* @var kDBConnection
*/
protected $dbStorage;
/**
* List of error/exception handlers
*
* @var Array
* @access protected
*/
protected $_handlers = Array ();
/**
* Long messages are saved here, because "trigger_error" doesn't support error messages over 1KB in size
*
* @var Array
* @access protected
*/
protected static $_longMessages = Array ();
/**
* Log record being worked on
*
* @var Array
* @access protected
*/
protected $_logRecord = Array ();
/**
* Maximal level of a message, that can be logged
*
* @var int
* @access protected
*/
protected $_maxLogLevel = self::LL_NOTICE;
/**
* State of the logger
*
* @var int
* @access protected
*/
protected $_state = self::STATE_DISABLED;
/**
* Caches state of debug mode
*
* @var bool
* @access protected
*/
protected $_debugMode = false;
/**
* Ignores backtrace record where following classes/files are mentioned
*
* @var array
*/
protected $_ignoreInTrace = array(
'kLogger' => 'logger.php',
'kErrorHandlerStack' => 'logger.php',
'kExceptionHandlerStack' => 'logger.php',
'kDBConnection' => 'db_connection.php',
'kDBConnectionDebug' => 'db_connection.php',
'kDBLoadBalancer' => 'db_load_balancer.php',
);
/**
* Create event log
*
* @param Array $methods_to_call List of invokable kLogger class method with their parameters (if any)
* @access public
*/
public function __construct($methods_to_call = Array ())
{
parent::__construct();
$this->dbStorage = $this->getDBStorage();
$system_config = kUtil::getSystemConfig();
$this->_debugMode = $this->Application->isDebugMode();
$this->setState($system_config->get('EnableSystemLog', self::STATE_DISABLED));
$this->_maxLogLevel = $system_config->get('SystemLogMaxLevel', self::LL_NOTICE);
foreach ($methods_to_call as $method_to_call) {
call_user_func_array(Array ($this, $method_to_call[0]), $method_to_call[1]);
}
if ( !kUtil::constOn('DBG_ZEND_PRESENT') && !$this->Application->isDebugMode() ) {
// don't report error on screen if debug mode is turned off
error_reporting(0);
ini_set('display_errors', 0);
}
register_shutdown_function(Array ($this, 'catchLastError'));
}
/**
* Create separate connection for logging purposes.
*
* @return kDBConnection
*/
protected function getDBStorage()
{
$system_config = new kSystemConfig(true);
$vars = $system_config->getData();
$db_class = $this->Application->isDebugMode() ? 'kDBConnectionDebug' : 'kDBConnection';
// Can't use "kApplication::makeClass", because class factory isn't initialized at this point.
$db = new $db_class(SQL_TYPE, array($this, 'handleSQLError'), 'logger');
$db->setup($vars);
return $db;
}
/**
* Sets state of the logged (enabled/user-only/disabled)
*
* @param $new_state
* @return void
* @access public
*/
public function setState($new_state = null)
{
if ( isset($new_state) ) {
$this->_state = (int)$new_state;
}
if ( $this->_state === self::STATE_ENABLED ) {
$this->_enableErrorHandling();
}
elseif ( $this->_state === self::STATE_DISABLED ) {
$this->_disableErrorHandling();
}
}
/**
* Enable error/exception handling capabilities
*
* @return void
* @access protected
*/
protected function _enableErrorHandling()
{
$this->_disableErrorHandling();
$this->_handlers[self::LL_ERROR] = new kErrorHandlerStack($this);
$this->_handlers[self::LL_CRITICAL] = new kExceptionHandlerStack($this);
}
/**
* Disables error/exception handling capabilities
*
* @return void
* @access protected
*/
protected function _disableErrorHandling()
{
foreach ($this->_handlers as $index => $handler) {
$this->_handlers[$index]->__destruct();
unset($this->_handlers[$index]);
}
}
/**
* Initializes new log record. Use "kLogger::write" to save to db/disk
*
* @param string $message
* @param int $code
* @return kLogger
* @access public
*/
public function prepare($message = '', $code = null)
{
$this->_logRecord = Array (
'LogUniqueId' => kUtil::generateId(),
'LogMessage' => $message,
'LogLevel' => self::LL_INFO,
'LogCode' => $code,
'LogType' => self::LT_OTHER,
'LogHostname' => $_SERVER['HTTP_HOST'],
'LogRequestSource' => php_sapi_name() == 'cli' ? 2 : 1,
'LogRequestURI' => php_sapi_name() == 'cli' ? implode(' ', $GLOBALS['argv']) : $_SERVER['REQUEST_URI'],
'LogUserId' => USER_GUEST,
'IpAddress' => isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '',
- 'LogSessionKey' => 0,
+ 'LogSessionKey' => '',
'LogProcessId' => getmypid(),
'LogUserData' => '',
'LogNotificationStatus' => self::LNS_DISABLED,
);
if ( $this->Application->isAdmin ) {
$this->_logRecord['LogInterface'] = defined('CRON') && CRON ? self::LI_CRON_ADMIN : self::LI_ADMIN;
}
else {
$this->_logRecord['LogInterface'] = defined('CRON') && CRON ? self::LI_CRON_FRONT : self::LI_FRONT;
}
if ( $this->Application->InitDone ) {
$this->_logRecord['LogUserId'] = $this->Application->RecallVar('user_id');
- $this->_logRecord['LogSessionKey'] = $this->Application->GetSID();
+ $this->_logRecord['LogSessionKey'] = $this->Application->GetSID(Session::PURPOSE_STORAGE);
$this->_logRecord['IpAddress'] = $this->Application->getClientIp();
}
return $this;
}
/**
* Sets one or more fields of log record
*
* @param string|Array $field_name
* @param string|null $field_value
* @return kLogger
* @access public
* @throws UnexpectedValueException
*/
public function setLogField($field_name, $field_value = null)
{
if ( isset($field_value) ) {
$this->_logRecord[$field_name] = $field_value;
}
elseif ( is_array($field_name) ) {
$this->_logRecord = array_merge($this->_logRecord, $field_name);
}
else {
throw new UnexpectedValueException('Invalid arguments');
}
return $this;
}
/**
* Sets user data
*
* @param string $data
* @param bool $as_array
* @return kLogger
* @access public
*/
public function setUserData($data, $as_array = false)
{
if ( $as_array ) {
$data = serialize((array)$data);
}
return $this->setLogField('LogUserData', $data);
}
/**
* Add user data
*
* @param string $data
* @param bool $as_array
* @return kLogger
* @access public
*/
public function addUserData($data, $as_array = false)
{
$new_data = $this->_logRecord['LogUserData'];
if ( $as_array ) {
$new_data = $new_data ? unserialize($new_data) : Array ();
$new_data[] = $data;
$new_data = serialize($new_data);
}
else {
$new_data .= ($new_data ? PHP_EOL : '') . $data;
}
return $this->setLogField('LogUserData', $new_data);
}
/**
* Adds event to log record
*
* @param kEvent $event
* @return kLogger
* @access public
*/
public function addEvent(kEvent $event)
{
$this->_logRecord['LogEventName'] = (string)$event;
return $this;
}
/**
* Adds log source file & file to log record
*
* @param string|Array $file_or_trace file path
* @param int $line file line
* @return kLogger
* @access public
*/
public function addSource($file_or_trace = '', $line = 0)
{
if ( is_array($file_or_trace) ) {
$trace_info = $file_or_trace[0];
$this->_logRecord['LogSourceFilename'] = $trace_info['file'];
$this->_logRecord['LogSourceFileLine'] = $trace_info['line'];
}
else {
$this->_logRecord['LogSourceFilename'] = $file_or_trace;
$this->_logRecord['LogSourceFileLine'] = $line;
}
$code_fragment = $this->getCodeFragment(
$this->_logRecord['LogSourceFilename'],
$this->_logRecord['LogSourceFileLine']
);
if ( $code_fragment !== null ) {
$this->_logRecord['LogCodeFragment'] = $code_fragment;
}
return $this;
}
/**
* Adds session contents to log record
*
* @param bool $include_optional Include optional session variables
* @return kLogger
* @access public
*/
public function addSessionData($include_optional = false)
{
if ( $this->Application->InitDone ) {
$this->_logRecord['LogSessionData'] = serialize($this->Application->Session->getSessionData($include_optional));
}
return $this;
}
/**
* Adds user request information to log record
*
* @return kLogger
* @access public
*/
public function addRequestData()
{
$request_data = array(
'Headers' => $this->Application->HttpQuery->getHeaders(),
);
$request_variables = Array('_GET' => $_GET, '_POST' => $_POST, '_COOKIE' => $_COOKIE);
foreach ( $request_variables as $title => $data ) {
if ( !$data ) {
continue;
}
$request_data[$title] = $data;
}
$this->_logRecord['LogRequestData'] = serialize($request_data);
return $this;
}
/**
* Adds trace to log record
*
* @param Array $trace
* @param int $skip_levels
* @param Array $skip_files
* @return kLogger
* @access public
*/
public function addTrace($trace = null, $skip_levels = 1, $skip_files = null)
{
$trace = $this->createTrace($trace, $skip_levels, $skip_files);
foreach ($trace as $trace_index => $trace_info) {
if ( isset($trace_info['args']) ) {
$trace[$trace_index]['args'] = $this->_implodeObjects($trace_info['args']);
}
if ( isset($trace_info['file'], $trace_info['line']) ) {
$code_fragment = $this->getCodeFragment($trace_info['file'], $trace_info['line']);
if ( $code_fragment !== null ) {
$trace[$trace_index]['code_fragment'] = $code_fragment;
}
}
}
$this->_logRecord['LogBacktrace'] = serialize($this->_removeObjectsFromTrace($trace));
return $this;
}
/**
* Returns a code fragment.
*
* @param string $file Filename.
* @param integer $line Line.
*
* @return string|null
*/
protected function getCodeFragment($file, $line)
{
static $path_filter_regexp;
// Lazy detect path filter regexp, because it's not available at construction time.
if ( $path_filter_regexp === null ) {
$application =& kApplication::Instance();
$path_filter_regexp = $application->ConfigValue('SystemLogCodeFragmentPathFilterRegExp');
}
if ( strpos($file, 'eval()\'d code') !== false
|| ($path_filter_regexp && !preg_match($path_filter_regexp, $file))
) {
return null;
}
$from_line = max(1, $line - 10);
$to_line = $line + 10;
// Prefix example: ">>> 5. " or " 5. ".
$prefix_length = 4 + strlen($to_line) + 2;
$cmd_parts = array(
'sed',
'-n',
escapeshellarg($from_line . ',' . $to_line . 'p'),
escapeshellarg($file),
);
$command = implode(' ', $cmd_parts);
$ret = array();
$code_fragment = preg_replace('/(\r\n|\n|\r)$/', '', shell_exec($command), 1);
foreach ( explode("\n", $code_fragment) as $line_offset => $code_fragment_part ) {
$line_number = $from_line + $line_offset;
$line_indicator = $line_number == $line ? '>>> ' : ' ';
$ret[] = str_pad($line_indicator . $line_number . '.', $prefix_length) . $code_fragment_part;
}
return implode("\n", $ret);
}
/**
* Remove objects from trace, since before PHP 5.2.5 there wasn't possible to remove them initially
*
* @param Array $trace
* @return Array
* @access protected
*/
protected function _removeObjectsFromTrace($trace)
{
if ( version_compare(PHP_VERSION, '5.3', '>=') ) {
return $trace;
}
$trace_indexes = array_keys($trace);
foreach ($trace_indexes as $trace_index) {
unset($trace[$trace_index]['object']);
}
return $trace;
}
/**
* Implodes object to prevent memory leaks
*
* @param Array $array
* @return Array
* @access protected
*/
protected function _implodeObjects($array)
{
$ret = Array ();
foreach ($array as $key => $value) {
if ( is_array($value) ) {
$ret[$key] = $this->_implodeObjects($value);
}
elseif ( is_object($value) ) {
if ( $value instanceof kEvent ) {
$ret[$key] = 'Event: ' . (string)$value;
}
elseif ( $value instanceof kBase ) {
$ret[$key] = (string)$value;
}
else {
$ret[$key] = 'Class: ' . get_class($value);
}
}
elseif ( is_resource($value) ) {
$ret[$key] = (string)$value;
}
elseif ( strlen($value) > 200 ) {
$ret[$key] = substr($value, 0, 50) . ' ...';
}
else {
$ret[$key] = $value;
}
}
return $ret;
}
/**
* Removes first N levels from trace
*
* @param Array $trace
* @param int $levels
* @param Array $files
* @return Array
* @access public
*/
public function createTrace($trace = null, $levels = null, $files = null)
{
if ( !isset($trace) ) {
$trace = debug_backtrace(false);
}
if ( !$trace ) {
// no trace information
return $trace;
}
if ( isset($levels) && is_numeric($levels) ) {
for ($i = 0; $i < $levels; $i++) {
array_shift($trace);
}
}
if ( isset($files) && is_array($files) ) {
$classes = array_keys($files);
while ( true ) {
$trace_info = $trace[0];
$file = isset($trace_info['file']) ? basename($trace_info['file']) : '';
$class = isset($trace_info['class']) ? $trace_info['class'] : '';
if ( ($file && !in_array($file, $files)) || ($class && !in_array($class, $classes)) ) {
break;
}
array_shift($trace);
}
}
return $trace;
}
/**
* Adds PHP error to log record
*
* @param int $errno
* @param string $errstr
* @param string $errfile
* @param int $errline
* @return kLogger
* @access public
*/
public function addError($errno, $errstr, $errfile = null, $errline = null)
{
$errstr = self::expandMessage($errstr, !$this->_debugMode);
$this->_logRecord['LogLevel'] = $this->_getLogLevelByErrorNo($errno);
if ( $this->isLogType(self::LT_DATABASE, $errstr) ) {
list ($errno, $errstr, $sql) = self::parseDatabaseError($errstr);
$this->_logRecord['LogType'] = self::LT_DATABASE;
$this->_logRecord['LogUserData'] = $sql;
$trace = $this->createTrace(null, 4, $this->_ignoreInTrace);
$this->addSource($trace);
$this->addTrace($trace, 0);
}
else {
$this->_logRecord['LogType'] = self::LT_PHP;
$this->addSource((string)$errfile, $errline);
$this->addTrace(null, 4);
}
$this->_logRecord['LogCode'] = $errno;
$this->_logRecord['LogMessage'] = $errstr;
return $this;
}
/**
* Adds PHP exception to log record
*
* @param Exception $exception
* @return kLogger
* @access public
*/
public function addException($exception)
{
$errstr = self::expandMessage($exception->getMessage(), !$this->_debugMode);
$this->_logRecord['LogLevel'] = self::LL_CRITICAL;
$exception_trace = $exception->getTrace();
array_unshift($exception_trace, array(
'function' => '',
'file' => $exception->getFile() !== null ? $exception->getFile() : 'n/a',
'line' => $exception->getLine() !== null ? $exception->getLine() : 'n/a',
'args' => array(),
));
if ( $this->isLogType(self::LT_DATABASE, $errstr) ) {
list ($errno, $errstr, $sql) = self::parseDatabaseError($errstr);
$this->_logRecord['LogType'] = self::LT_DATABASE;
$this->_logRecord['LogUserData'] = $sql;
$trace = $this->createTrace($exception_trace, null, $this->_ignoreInTrace);
$this->addSource($trace);
$this->addTrace($trace, 0);
}
else {
$this->_logRecord['LogType'] = self::LT_PHP;
$errno = $exception->getCode();
$this->addSource((string)$exception->getFile(), $exception->getLine());
$this->addTrace($exception_trace, 0);
}
$this->_logRecord['LogCode'] = $errno;
$this->_logRecord['LogMessage'] = $errstr;
return $this;
}
/**
* Allows to map PHP error numbers to syslog log level
*
* @param int $errno
* @return int
* @access protected
*/
protected function _getLogLevelByErrorNo($errno)
{
$error_number_mapping = Array (
self::LL_ERROR => Array (E_RECOVERABLE_ERROR, E_USER_ERROR, E_ERROR, E_CORE_ERROR, E_COMPILE_ERROR, E_PARSE),
self::LL_WARNING => Array (E_WARNING, E_USER_WARNING, E_CORE_WARNING, E_COMPILE_WARNING),
self::LL_NOTICE => Array (E_NOTICE, E_USER_NOTICE, E_STRICT),
);
if ( version_compare(PHP_VERSION, '5.3.0', '>=') ) {
$error_number_mapping[self::LL_NOTICE][] = E_DEPRECATED;
$error_number_mapping[self::LL_NOTICE][] = E_USER_DEPRECATED;
}
foreach ($error_number_mapping as $log_level => $error_numbers) {
if ( in_array($errno, $error_numbers) ) {
return $log_level;
}
}
return self::LL_ERROR;
}
/**
* Changes log level of a log record
*
* @param int $log_level
* @return kLogger
* @access public
*/
public function setLogLevel($log_level)
{
$this->_logRecord['LogLevel'] = $log_level;
return $this;
}
/**
* Writes prepared log to database or disk, when database isn't available
*
* @param integer $storage_medium Storage medium.
* @param boolean $check_origin Check error origin.
*
* @return integer|boolean
* @throws InvalidArgumentException When unknown storage medium is given.
*/
public function write($storage_medium = self::LS_AUTOMATIC, $check_origin = false)
{
if ( $check_origin && isset($this->_logRecord['LogSourceFilename']) ) {
$origin_allowed = self::isErrorOriginAllowed($this->_logRecord['LogSourceFilename']);
}
else {
$origin_allowed = true;
}
if ( !$this->_logRecord
|| $this->_logRecord['LogLevel'] > $this->_maxLogLevel
|| !$origin_allowed
|| $this->_state == self::STATE_DISABLED
) {
// Nothing to save OR less detailed logging requested OR origin not allowed OR disabled.
$this->_logRecord = array();
return false;
}
$this->_logRecord['LogMemoryUsed'] = memory_get_usage();
$this->_logRecord['LogTimestamp'] = adodb_mktime();
$this->_logRecord['LogDate'] = adodb_date('Y-m-d H:i:s');
if ( $storage_medium == self::LS_AUTOMATIC ) {
$storage_medium = $this->dbStorage->connectionOpened() ? self::LS_DATABASE : self::LS_DISK;
}
if ( $storage_medium == self::LS_DATABASE ) {
$result = $this->dbStorage->doInsert($this->_logRecord, TABLE_PREFIX . 'SystemLog');
}
elseif ( $storage_medium == self::LS_DISK ) {
$result = $this->_saveToFile(RESTRICTED . '/system.log');
}
else {
throw new InvalidArgumentException('Unknown storage medium "' . $storage_medium . '"');
}
$unique_id = $this->_logRecord['LogUniqueId'];
if ( $this->_logRecord['LogNotificationStatus'] == self::LNS_SENT ) {
$this->_sendNotification($unique_id);
}
$this->_logRecord = Array ();
return $result ? $unique_id : false;
}
/**
* Catches last error happened before script ended
*
* @return void
* @access public
*/
public function catchLastError()
{
$this->write();
$last_error = error_get_last();
if ( !is_null($last_error) && isset($this->_handlers[self::LL_ERROR]) ) {
/** @var kErrorHandlerStack $handler */
$handler = $this->_handlers[self::LL_ERROR];
$handler->handle($last_error['type'], $last_error['message'], $last_error['file'], $last_error['line']);
}
}
/**
* Deletes log with given id from database or disk, when database isn't available
*
* @param int $unique_id
* @param int $storage_medium
* @return void
* @access public
* @throws InvalidArgumentException
*/
public function delete($unique_id, $storage_medium = self::LS_AUTOMATIC)
{
if ( $storage_medium == self::LS_AUTOMATIC ) {
$storage_medium = $this->dbStorage->connectionOpened() ? self::LS_DATABASE : self::LS_DISK;
}
if ( $storage_medium == self::LS_DATABASE ) {
$sql = 'DELETE FROM ' . TABLE_PREFIX . 'SystemLog
WHERE LogUniqueId = ' . $unique_id;
$this->dbStorage->Query($sql);
}
elseif ( $storage_medium == self::LS_DISK ) {
// TODO: no way to delete a line from a file
}
else {
throw new InvalidArgumentException('Unknown storage medium "' . $storage_medium . '"');
}
}
/**
* Send notification (delayed or instant) about log record to e-mail from configuration
*
* @param bool $instant
* @return kLogger
* @access public
*/
public function notify($instant = false)
{
$this->_logRecord['LogNotificationStatus'] = $instant ? self::LNS_SENT : self::LNS_PENDING;
return $this;
}
/**
* Sends notification e-mail about message with given $unique_id
*
* @param int $unique_id
* @return void
* @access protected
*/
protected function _sendNotification($unique_id)
{
$notification_email = $this->Application->ConfigValue('SystemLogNotificationEmail');
if ( !$notification_email ) {
trigger_error('System Log notification E-mail not specified', E_USER_NOTICE);
return;
}
$send_params = Array (
'to_name' => $notification_email,
'to_email' => $notification_email,
);
// initialize list outside of e-mail event with right settings
$this->Application->recallObject('system-log.email', 'system-log_List', Array ('unique_id' => $unique_id));
$this->Application->emailAdmin('SYSTEM.LOG.NOTIFY', null, $send_params);
$this->Application->removeObject('system-log.email');
}
/**
* Adds error/exception handler
*
* @param string|Array $handler
* @param bool $is_exception
* @return void
* @access public
*/
public function addErrorHandler($handler, $is_exception = false)
{
$this->_handlers[$is_exception ? self::LL_CRITICAL : self::LL_ERROR]->add($handler);
}
/**
* SQL Error Handler
*
* When not debug mode, then fatal database query won't break anything.
*
* @param int $code
* @param string $msg
* @param string $sql
* @return bool
* @access public
* @throws RuntimeException
*/
public function handleSQLError($code, $msg, $sql)
{
$error_msg = self::shortenMessage(self::DB_ERROR_PREFIX . ' #' . $code . ' - ' . $msg . '. SQL: ' . trim($sql));
if ( isset($this->Application->Debugger) ) {
if ( kUtil::constOn('DBG_SQL_FAILURE') && !defined('IS_INSTALL') ) {
throw new RuntimeException($error_msg);
}
else {
$this->Application->Debugger->appendTrace();
}
}
if ( PHP_SAPI === 'cli' ) {
throw new RuntimeException($error_msg);
}
// Next line also trigger attached error handlers.
trigger_error($error_msg, E_USER_WARNING);
return true;
}
/**
* Packs information about error into a single line
*
* @param string $errno
* @param bool $strip_tags
* @return string
* @access public
*/
public function toString($errno = null, $strip_tags = false)
{
if ( PHP_SAPI !== 'cli' && !$this->Application->isDebugMode() ) {
$date = date('Y-m-d H:i:s');
$reference = $this->_logRecord['LogUniqueId'] . '-' . time();
$message = <<<HTML
<h1 style="margin-top: 0;">Oops, something went wrong</h1>
This is page is currently not available.
We are working on the problem, and appreciate your patience.<br/>
<br/>
Date: {$date}<br/>
Reference: {$reference}<br/>
HTML;
return $message;
}
if ( !isset($errno) ) {
$errno = $this->_logRecord['LogCode'];
}
$errstr = $this->_logRecord['LogMessage'];
$errfile = $this->convertPathToRelative($this->_logRecord['LogSourceFilename']);
$errline = $this->_logRecord['LogSourceFileLine'];
if ( PHP_SAPI === 'cli' ) {
$result = sprintf(' [%s] ' . PHP_EOL . ' %s', $errno, $errstr);
if ( $this->_logRecord['LogBacktrace'] ) {
$result .= $this->printBacktrace(unserialize($this->_logRecord['LogBacktrace']));
}
}
else {
$result = '<strong>' . $errno . ': </strong>' . "{$errstr} in {$errfile} on line {$errline}";
}
return $strip_tags ? strip_tags($result) : $result;
}
/**
* Prints backtrace result
*
* @param array $trace Trace.
*
* @return string
*/
protected function printBacktrace(array $trace)
{
if ( !$trace ) {
return '';
}
$ret = PHP_EOL . PHP_EOL . PHP_EOL . 'Exception trace:' . PHP_EOL;
foreach ( $trace as $trace_info ) {
$class = isset($trace_info['class']) ? $trace_info['class'] : '';
$type = isset($trace_info['type']) ? $trace_info['type'] : '';
$function = $trace_info['function'];
$args = isset($trace_info['args']) && $trace_info['args'] ? '...' : '';
$file = isset($trace_info['file']) ? $this->convertPathToRelative($trace_info['file']) : 'n/a';
$line = isset($trace_info['line']) ? $trace_info['line'] : 'n/a';
$ret .= sprintf(' %s%s%s(%s) at %s:%s' . PHP_EOL, $class, $type, $function, $args, $file, $line);
}
return $ret;
}
/**
* Short description.
*
* @param string $absolute_path Absolute path.
*
* @return string
*/
protected function convertPathToRelative($absolute_path)
{
return preg_replace('/^' . preg_quote(FULL_PATH, '/') . '/', '...', $absolute_path, 1);
}
/**
* Saves log to file (e.g. when not possible to save into database)
*
* @param $filename
* @return bool
* @access protected
*/
protected function _saveToFile($filename)
{
$time = adodb_date('Y-m-d H:i:s');
$log_file = new SplFileObject($filename, 'a');
return $log_file->fwrite('[' . $time . '] #' . $this->toString(null, true) . PHP_EOL) > 0;
}
/**
* Checks if log type of current log record matches given one
*
* @param int $log_type
* @param string $log_message
* @return bool
* @access public
*/
public function isLogType($log_type, $log_message = null)
{
if ( $this->_logRecord['LogType'] == $log_type ) {
return true;
}
if ( $log_type == self::LT_DATABASE ) {
if ( !isset($log_message) ) {
$log_message = $this->_logRecord['LogMessage'];
}
return strpos($log_message, self::DB_ERROR_PREFIX) !== false;
}
return false;
}
/**
* Shortens message
*
* @param string $message
* @return string
* @access public
*/
public static function shortenMessage($message)
{
$max_len = ini_get('log_errors_max_len');
if ( strlen($message) > $max_len ) {
$long_key = kUtil::generateId();
self::$_longMessages[$long_key] = $message;
return mb_substr($message, 0, $max_len - strlen($long_key) - 2) . ' #' . $long_key;
}
return $message;
}
/**
* Expands shortened message
*
* @param string $message
* @param bool $clear_cache Allow debugger to expand message after it's been expanded by kLogger
* @return string
* @access public
*/
public static function expandMessage($message, $clear_cache = true)
{
if ( preg_match('/(.*)#([\d]+)$/', $message, $regs) ) {
$long_key = $regs[2];
if ( isset(self::$_longMessages[$long_key]) ) {
$message = self::$_longMessages[$long_key];
if ( $clear_cache ) {
unset(self::$_longMessages[$long_key]);
}
}
}
return $message;
}
/**
* Determines if error should be logged based on it's origin.
*
* @param string $file File.
*
* @return boolean
*/
public static function isErrorOriginAllowed($file)
{
static $error_origin_regexp;
// Lazy detect error origins, because they're not available at construction time.
if ( !$error_origin_regexp ) {
$error_origins = array();
$application = kApplication::Instance();
foreach ( $application->ModuleInfo as $module_info ) {
$error_origins[] = preg_quote(rtrim($module_info['Path'], '/'), '/');
}
$error_origins = array_unique($error_origins);
$error_origin_regexp = '/^' . preg_quote(FULL_PATH, '/') . '\/(' . implode('|', $error_origins) . ')\//';
}
// Allow dynamically generated code.
if ( strpos($file, 'eval()\'d code') !== false ) {
return true;
}
// Allow known modules.
if ( preg_match('/^' . preg_quote(MODULES_PATH, '/') . '\//', $file) ) {
return preg_match($error_origin_regexp, $file) == 1;
}
// Don't allow Vendors.
if ( preg_match('/^' . preg_quote(FULL_PATH, '/') . '\/vendor\//', $file) ) {
return false;
}
// Allow everything else within main folder.
return preg_match('/^' . preg_quote(FULL_PATH, '/') . '\//', $file) == 1;
}
/**
* Parses database error message into error number, error message and sql that caused that error
*
* @static
* @param string $message
* @return Array
* @access public
*/
public static function parseDatabaseError($message)
{
$regexp = '/' . preg_quote(self::DB_ERROR_PREFIX) . ' #(.*?) - (.*?)\. SQL: (.*?)$/s';
if ( preg_match($regexp, $message, $regs) ) {
// errno, errstr, sql
return Array ($regs[1], $regs[2], $regs[3]);
}
return Array (0, $message, '');
}
}
/**
* Base class for error or exception handling
*/
abstract class kHandlerStack extends kBase {
/**
* List of added handlers
*
* @var Array
* @access protected
*/
protected $_handlers = Array ();
/**
* Reference to event log, which created this object
*
* @var kLogger
* @access protected
*/
protected $_logger;
/**
* Remembers if handler is activated
*
* @var bool
* @access protected
*/
protected $_enabled = false;
public function __construct(kLogger $logger)
{
parent::__construct();
$this->_logger = $logger;
if ( !kUtil::constOn('DBG_ZEND_PRESENT') ) {
$this->attach();
$this->_enabled = true;
}
}
/**
* Detaches from error handling routines on class destruction
*
* @return void
* @access public
*/
public function __destruct()
{
if ( !$this->_enabled ) {
return;
}
$this->detach();
$this->_enabled = false;
}
/**
* Attach to error handling routines
*
* @abstract
* @return void
* @access protected
*/
abstract protected function attach();
/**
* Detach from error handling routines
*
* @abstract
* @return void
* @access protected
*/
abstract protected function detach();
/**
* Adds new handler to the stack
*
* @param callable $handler
* @return void
* @access public
*/
public function add($handler)
{
$this->_handlers[] = $handler;
}
/**
* Returns `true`, when no other error handlers should process this error.
*
* @param integer $errno Error code.
*
* @return boolean
*/
protected function _handleFatalError($errno)
{
$debug_mode = defined('DEBUG_MODE') && DEBUG_MODE;
$skip_reporting = defined('DBG_SKIP_REPORTING') && DBG_SKIP_REPORTING;
if ( !$this->_handlers || ($debug_mode && $skip_reporting) ) {
// when debugger absent OR it's present, but we actually can't see it's error report (e.g. during ajax request)
if ( $this->_isFatalError($errno) ) {
$this->_displayFatalError($errno);
}
if ( !$this->_handlers ) {
return true;
}
}
return false;
}
/**
* Determines if given error is a fatal
*
* @abstract
* @param Exception|int $errno
* @return bool
*/
abstract protected function _isFatalError($errno);
/**
* Displays div with given error message
*
* @param string $errno
* @return void
* @access protected
*/
protected function _displayFatalError($errno)
{
$errno = $this->_getFatalErrorTitle($errno);
$margin = $this->Application->isAdmin ? '8px' : 'auto';
$error_msg = $this->_logger->toString($errno, PHP_SAPI === 'cli');
if ( PHP_SAPI === 'cli' ) {
echo $error_msg;
exit(1);
}
echo '<div style="background-color: #F5F5F5; margin: ' . $margin . '; padding: 10px; border: 2px solid #0067b8; color: #0067b8;">' . $error_msg . '</div>';
exit;
}
/**
* Returns title to show for a fatal
*
* @abstract
* @param Exception|int $errno
* @return string
*/
abstract protected function _getFatalErrorTitle($errno);
}
/**
* Class, that handles errors
*/
class kErrorHandlerStack extends kHandlerStack {
/**
* Attach to error handling routines
*
* @return void
* @access protected
*/
protected function attach()
{
// set as error handler
$error_handler = set_error_handler(Array ($this, 'handle'));
if ( $error_handler ) {
// wrap around previous error handler, if any was set
$this->_handlers[] = $error_handler;
}
}
/**
* Detach from error handling routines
*
* @return void
* @access protected
*/
protected function detach()
{
restore_error_handler();
}
/**
* Determines if given error is a fatal
*
* @param int $errno
* @return bool
* @access protected
*/
protected function _isFatalError($errno)
{
$fatal_errors = Array (E_USER_ERROR, E_RECOVERABLE_ERROR, E_ERROR, E_CORE_ERROR, E_COMPILE_ERROR, E_PARSE);
return in_array($errno, $fatal_errors);
}
/**
* Returns title to show for a fatal
*
* @param int $errno
* @return string
* @access protected
*/
protected function _getFatalErrorTitle($errno)
{
return 'Fatal Error';
}
/**
* Default error handler
*
* @param int $errno
* @param string $errstr
* @param string $errfile
* @param int $errline
* @param Array $errcontext
* @return bool
* @access public
*/
public function handle($errno, $errstr, $errfile = null, $errline = null, $errcontext = Array ())
{
$log = $this->_logger->prepare()->addError($errno, $errstr, $errfile, $errline);
if ( $this->_handleFatalError($errno) ) {
$log->write(kLogger::LS_AUTOMATIC, !$this->_isFatalError($errno));
return true;
}
$log->write(kLogger::LS_AUTOMATIC, !$this->_isFatalError($errno));
$res = false;
foreach ($this->_handlers as $handler) {
$res = call_user_func($handler, $errno, $errstr, $errfile, $errline, $errcontext);
}
return $res;
}
}
/**
* Class, that handles exceptions
*/
class kExceptionHandlerStack extends kHandlerStack {
/**
* Attach to error handling routines
*
* @return void
* @access protected
*/
protected function attach()
{
// set as exception handler
$exception_handler = set_exception_handler(Array ($this, 'handle'));
if ( $exception_handler ) {
// wrap around previous exception handler, if any was set
$this->_handlers[] = $exception_handler;
}
}
/**
* Detach from error handling routines
*
* @return void
* @access protected
*/
protected function detach()
{
restore_exception_handler();
}
/**
* Determines if given error is a fatal
*
* @param Exception $errno
* @return bool
*/
protected function _isFatalError($errno)
{
return true;
}
/**
* Returns title to show for a fatal
*
* @param Exception $errno
* @return string
*/
protected function _getFatalErrorTitle($errno)
{
return get_class($errno);
}
/**
* Handles exception
*
* @param Exception $exception
* @return bool
* @access public
*/
public function handle($exception)
{
$log = $this->_logger->prepare()->addException($exception);
if ( $exception instanceof kRedirectException ) {
/** @var kRedirectException $exception */
$exception->run();
}
if ( $this->_handleFatalError($exception) ) {
$log->write();
return true;
}
$log->write();
$res = false;
foreach ($this->_handlers as $handler) {
$res = call_user_func($handler, $exception);
}
return $res;
}
}
Index: branches/5.2.x/core/kernel/utility/debugger.php
===================================================================
--- branches/5.2.x/core/kernel/utility/debugger.php (revision 16796)
+++ branches/5.2.x/core/kernel/utility/debugger.php (revision 16797)
@@ -1,2195 +1,2202 @@
<?php
/**
* @version $Id$
* @package In-Portal
* @copyright Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license GNU/GPL
* In-Portal is Open Source software.
* This means that this software may have been modified pursuant
* the GNU General Public License, and as distributed it includes
* or is derivative of works licensed under the GNU General Public License
* or other free or open source software licenses.
* See http://www.in-portal.org/license for copyright notices and details.
*/
defined('FULL_PATH') or die('restricted access!');
if( !class_exists('Debugger') ) {
/**
* Contains misc functions, used by debugger (mostly copied from kUtil class)
*/
class DebuggerUtil {
/**
* Trust information, provided by proxy
*
* @var bool
*/
public static $trustProxy = false;
/**
* Checks if constant is defined and has positive value
*
* @param string $const_name
* @return bool
*/
public static function constOn($const_name)
{
return defined($const_name) && constant($const_name);
}
/**
* Define constant if it was not already defined before
*
* @param string $const_name
* @param string $const_value
* @access public
*/
public static function safeDefine($const_name, $const_value)
{
if ( !defined($const_name) ) {
define($const_name, $const_value);
}
}
/**
* Formats file/memory size in nice way
*
* @param int $bytes
* @return string
* @access public
*/
public static function formatSize($bytes)
{
if ($bytes >= 1099511627776) {
$return = round($bytes / 1024 / 1024 / 1024 / 1024, 2);
$suffix = "TB";
} elseif ($bytes >= 1073741824) {
$return = round($bytes / 1024 / 1024 / 1024, 2);
$suffix = "GB";
} elseif ($bytes >= 1048576) {
$return = round($bytes / 1024 / 1024, 2);
$suffix = "MB";
} elseif ($bytes >= 1024) {
$return = round($bytes / 1024, 2);
$suffix = "KB";
} else {
$return = $bytes;
$suffix = "Byte";
}
$return .= ' '.$suffix;
return $return;
}
/**
* Checks, that user IP address is within allowed range
*
* @param string $ip_list semi-column (by default) separated ip address list
* @param string $separator ip address separator (default ";")
*
* @return bool
*/
public static function ipMatch($ip_list, $separator = ';')
{
if ( php_sapi_name() == 'cli' ) {
return false;
}
$ip_match = false;
$ip_addresses = $ip_list ? explode($separator, $ip_list) : Array ();
$client_ip = self::getClientIp();
foreach ($ip_addresses as $ip_address) {
if ( self::netMatch($ip_address, $client_ip) ) {
$ip_match = true;
break;
}
}
return $ip_match;
}
/**
* Returns the client IP address.
*
* @return string The client IP address
* @access public
*/
public static function getClientIp()
{
if ( self::$trustProxy ) {
if ( array_key_exists('HTTP_CLIENT_IP', $_SERVER) ) {
return $_SERVER['HTTP_CLIENT_IP'];
}
if ( array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER) ) {
$client_ip = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
foreach ($client_ip as $ip_address) {
$clean_ip_address = trim($ip_address);
if ( false !== filter_var($clean_ip_address, FILTER_VALIDATE_IP) ) {
return $clean_ip_address;
}
}
return '';
}
}
return $_SERVER['REMOTE_ADDR'];
}
/**
* Checks, that given ip belongs to given subnet
*
* @param string $network
* @param string $ip
* @return bool
* @access public
*/
public static function netMatch($network, $ip) {
$network = trim($network);
$ip = trim($ip);
if ( preg_replace('/[\d\.\/-]/', '', $network) != '' ) {
$network = gethostbyname($network);
}
if ($network == $ip) {
// comparing two ip addresses directly
return true;
}
$d = strpos($network, '-');
if ($d !== false) {
// ip address range specified
$from = ip2long(trim(substr($network, 0, $d)));
$to = ip2long(trim(substr($network, $d + 1)));
$ip = ip2long($ip);
return ($ip >= $from && $ip <= $to);
}
elseif (strpos($network, '/') !== false) {
// single subnet specified
$ip_arr = explode('/', $network);
if (!preg_match("@\d*\.\d*\.\d*\.\d*@", $ip_arr[0], $matches)) {
$ip_arr[0] .= '.0'; // Alternate form 194.1.4/24
}
$network_long = ip2long($ip_arr[0]);
$x = ip2long($ip_arr[1]);
$mask = long2ip($x) == $ip_arr[1] ? $x : (0xffffffff << (32 - $ip_arr[1]));
$ip_long = ip2long($ip);
return ($ip_long & $mask) == ($network_long & $mask);
}
return false;
}
}
/**
* Main debugger class, that can be used with any In-Portal (or not) project
*/
class Debugger {
const ROW_TYPE_ERROR = 'error';
const ROW_TYPE_WARNING = 'warning';
const ROW_TYPE_NOTICE = 'notice';
const ROW_TYPE_SQL = 'sql';
const ROW_TYPE_OTHER = 'other';
/**
* Holds reference to global KernelApplication instance
*
* @var kApplication
* @access private
*/
private $Application = null;
/**
* Stores last fatal error hash or 0, when no fatal error happened
*
* @var integer
*/
private $_fatalErrorHash = 0;
private $_filterTypes = Array ('error', 'sql', 'other');
/**
* Counts warnings on the page
*
* @var int
* @access public
*/
public $WarningCount = 0;
/**
* Allows to track compile errors, like "stack-overflow"
*
* @var bool
* @access private
*/
private $_compileError = false;
/**
* Debugger data for building report
*
* @var Array
* @access private
*/
private $Data = Array ();
/**
* Data index, that represents a header ending.
*
* @var integer
*/
private $HeaderEndingDataIndex = 0;
/**
* Holds information about each profiler record (start/end/description)
*
* @var Array
* @access private
*/
private $ProfilerData = Array ();
/**
* Holds information about total execution time per profiler key (e.g. total sql time)
*
* @var Array
* @access private
*/
private $ProfilerTotals = Array ();
/**
* Counts how much each of total types were called (e.g. total error count)
*
* @var Array
* @access private
*/
private $ProfilerTotalCount = Array ();
/**
* Holds information about all profile points registered
*
* @var Array
* @access private
*/
private $ProfilePoints = Array ();
/**
* Prevent recursion when processing debug_backtrace() function results
*
* @var Array
* @access private
*/
private $RecursionStack = Array ();
/**
* Cross browser debugger report scrollbar width detection
*
* @var int
* @access private
*/
private $scrollbarWidth = 0;
/**
* Remembers how much memory & time was spent on including files
*
* @var Array
* @access public
* @see kUtil::includeOnce
*/
public $IncludesData = Array ();
/**
* Remembers maximal include deep level
*
* @var int
* @access public
* @see kUtil::includeOnce
*/
public $IncludeLevel = 0;
/**
* Prevents report generation more then once
*
* @var bool
* @access private
*/
private $_inReportPrinting = false;
/**
* Transparent spacer image used in case of none spacer image defined via SPACER_URL constant.
* Used while drawing progress bars (memory usage, time usage, etc.)
*
* @var string
* @access private
*/
private $dummyImage = '';
/**
* Temporary files created by debugger will be stored here
*
* @var string
* @access private
*/
private $tempFolder = '';
/**
- * Debug rows will be separated using this string before writing to debug file
+ * Debug rows will be separated using this string before writing to debug file (used in debugger dump filename too).
*
* @var string
* @access private
*/
private $rowSeparator = '@@';
/**
* Base URL for debugger includes
*
* @var string
* @access private
*/
private $baseURL = '';
/**
* Sub-folder, where In-Portal is installed
*
* @var string
* @access private
*/
private $basePath = '';
/**
* Holds last recorded timestamp (for appendTimestamp)
*
* @var int
* @access private
*/
private $LastMoment;
/**
* Determines, that current request is AJAX request
*
* @var bool
* @access private
*/
private $_isAjax = false;
/**
* Data, parsed from the editor url.
*
* @var array
*/
protected $editorUrlData = array('url' => '', 'params' => array());
/**
* Creates instance of debugger
*/
public function __construct()
{
global $start, $dbg_options;
// check if user haven't defined DEBUG_MODE contant directly
if ( defined('DEBUG_MODE') && DEBUG_MODE ) {
die('error: constant DEBUG_MODE defined directly, please use <strong>$dbg_options</strong> array instead');
}
if ( class_exists('kUtil') ) {
DebuggerUtil::$trustProxy = kUtil::getSystemConfig()->get('TrustProxy');
}
// check IP before enabling debug mode
$ip_match = DebuggerUtil::ipMatch(isset($dbg_options['DBG_IP']) ? $dbg_options['DBG_IP'] : '');
if ( !$ip_match || (isset($_COOKIE['debug_off']) && $_COOKIE['debug_off']) ) {
define('DEBUG_MODE', 0);
return;
}
// debug is allowed for user, continue initialization
$this->InitDebugger();
$this->profileStart('kernel4_startup', 'Startup and Initialization of kernel4', $start);
$this->profileStart('script_runtime', 'Script runtime', $start);
$this->LastMoment = $start;
error_reporting(E_ALL & ~E_STRICT);
// show errors on screen in case if not in Zend Studio debugging
ini_set('display_errors', DebuggerUtil::constOn('DBG_ZEND_PRESENT') ? 0 : 1);
// vertical scrollbar width differs in Firefox and other browsers
$this->scrollbarWidth = $this->isGecko() ? 22 : 25;
// Mark place, where request information will be inserted.
$this->HeaderEndingDataIndex = count($this->Data);
}
/**
* Set's default values to constants debugger uses
*
*/
function InitDebugger()
{
global $dbg_options;
unset($dbg_options['DBG_IP']);
// Detect fact, that this session being debugged by Zend Studio
foreach ($_COOKIE as $cookie_name => $cookie_value) {
if (substr($cookie_name, 0, 6) == 'debug_') {
DebuggerUtil::safeDefine('DBG_ZEND_PRESENT', 1);
break;
}
}
DebuggerUtil::safeDefine('DBG_ZEND_PRESENT', 0); // set this constant value to 0 (zero) to debug debugger using Zend Studio
// set default values for debugger constants
$dbg_constMap = Array (
'DBG_USE_HIGHLIGHT' => 1, // highlight output same as php code using "highlight_string" function
'DBG_WINDOW_WIDTH' => 700, // set width of debugger window (in pixels) for better viewing large amount of debug data
'DBG_USE_SHUTDOWN_FUNC' => DBG_ZEND_PRESENT ? 0 : 1, // use shutdown function to include debugger code into output
'DBG_HANDLE_ERRORS' => DBG_ZEND_PRESENT ? 0 : 1, // handle all allowed by php (see php manual) errors instead of default handler
'DBG_DOMVIEWER' => '/temp/domviewer.html', // path to DOMViewer on website
'DOC_ROOT' => str_replace('\\', '/', realpath($_SERVER['DOCUMENT_ROOT']) ), // windows hack
'DBG_LOCAL_BASE_PATH' => 'w:', // replace DOC_ROOT in filenames (in errors) using this path
'DBG_EDITOR_URL' => 'file://%F:%L',
'DBG_SHORTCUT' => 'F12', // Defines debugger activation shortcut (any symbols or Ctrl/Alt/Shift are allowed, e.g. Ctrl+Alt+F12)
);
// debugger is initialized before kHTTPQuery, so do jQuery headers check here too
if (array_key_exists('HTTP_X_REQUESTED_WITH', $_SERVER) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
$this->_isAjax = true;
}
elseif (array_key_exists('ajax', $_GET) && $_GET['ajax'] == 'yes') {
$this->_isAjax = true;
}
// user defined options override debugger defaults
$dbg_constMap = array_merge($dbg_constMap, $dbg_options);
if ($this->_isAjax && array_key_exists('DBG_SKIP_AJAX', $dbg_constMap) && $dbg_constMap['DBG_SKIP_AJAX']) {
$dbg_constMap['DBG_SKIP_REPORTING'] = 1;
}
// allows to validate unit configs via request variable
if ( !array_key_exists('DBG_VALIDATE_CONFIGS', $dbg_constMap) ) {
$dbg_constMap['DBG_VALIDATE_CONFIGS'] = array_key_exists('validate_configs', $_GET) ? (int)$_GET['validate_configs'] : 0;
}
// when validation configs, don't show sqls for better validation error displaying
if ($dbg_constMap['DBG_VALIDATE_CONFIGS']) {
$dbg_constMap['DBG_SQL_PROFILE'] = 0;
}
// when showing explain make shure, that debugger window is large enough
if (array_key_exists('DBG_SQL_EXPLAIN', $dbg_constMap) && $dbg_constMap['DBG_SQL_EXPLAIN']) {
$dbg_constMap['DBG_WINDOW_WIDTH'] = 1000;
}
foreach ($dbg_constMap as $dbg_constName => $dbg_constValue) {
DebuggerUtil::safeDefine($dbg_constName, $dbg_constValue);
}
$this->parseEditorUrl();
}
/**
* Parses editor url.
*
* @return void
*/
protected function parseEditorUrl()
{
$components = parse_url(DBG_EDITOR_URL);
$this->editorUrlData['url'] = $components['scheme'] . '://' . $components['host'];
if ( isset($components['path']) ) {
$this->editorUrlData['url'] .= $components['path'];
}
if ( isset($components['query']) ) {
parse_str(html_entity_decode($components['query']), $this->editorUrlData['params']);
}
}
/**
* Performs debugger initialization
*
* @return void
*/
private function InitReport()
{
if ( !class_exists('kApplication') ) {
return;
}
$application =& kApplication::Instance();
- // string used to separate debugger records while in file (used in debugger dump filename too)
- $this->rowSeparator = '@' . (/*is_object($application->Factory) &&*/ $application->InitDone ? $application->GetSID() : 0) . '@';
-// $this->rowSeparator = '@' . rand(0, 100000) . '@';
+ /*
+ * Don't use "Session::PURPOSE_REFERENCE" below, because
+ * until session is saved to the db there is no reference.
+ */
+ if ( $application->InitDone ) {
+ $this->rowSeparator = '@' . $application->GetSID(Session::PURPOSE_STORAGE) . '@';
+ }
+ else {
+ $this->rowSeparator = '@0@';
+ }
// include debugger files from this url
$reg_exp = '/^' . preg_quote(FULL_PATH, '/') . '/';
$kernel_path = preg_replace($reg_exp, '', KERNEL_PATH, 1);
$this->baseURL = PROTOCOL . SERVER_NAME . (defined('PORT') ? ':' . PORT : '') . rtrim(BASE_PATH, '/') . $kernel_path . '/utility/debugger';
// store debugger cookies at this path
$this->basePath = rtrim(BASE_PATH, '/');
// save debug output in this folder
$this->tempFolder = defined('RESTRICTED') ? RESTRICTED : WRITEABLE . '/cache';
}
/**
* Appends all passed variable values (without variable names) to debug output
*
* @return void
* @access public
*/
public function dumpVars()
{
$dump_mode = 'var_dump';
$dumpVars = func_get_args();
if ( $dumpVars[count($dumpVars) - 1] === 'STRICT' ) {
$dump_mode = 'strict_var_dump';
array_pop($dumpVars);
}
foreach ($dumpVars as $varValue) {
$this->Data[] = Array ('value' => $varValue, 'debug_type' => $dump_mode);
}
}
/**
* Transforms collected data at given index into human-readable HTML to place in debugger report
*
* @param int $dataIndex
* @return string
* @access private
*/
private function prepareHTML($dataIndex)
{
static $errors_displayed = 0;
$Data =& $this->Data[$dataIndex];
if ( $Data['debug_type'] == 'html' ) {
return $Data['html'];
}
switch ($Data['debug_type']) {
case 'error':
$errors_displayed++;
$fileLink = $this->getFileLink($Data['file'], $Data['line']);
$ret = '<b class="debug_error">' . $this->getErrorNameByCode($Data['no']) . ' (#' . $errors_displayed . ')</b>: ' . $Data['str'];
$ret .= ' in <b>' . $fileLink . '</b> on line <b>' . $Data['line'] . '</b>';
return $ret;
break;
case 'exception':
$fileLink = $this->getFileLink($Data['file'], $Data['line']);
$ret = '<b class="debug_error">' . $Data['exception_class'] . '</b>: ' . $Data['str'];
$ret .= ' in <b>' . $fileLink . '</b> on line <b>' . $Data['line'] . '</b>';
return $ret;
break;
case 'var_dump':
return $this->highlightString($this->print_r($Data['value'], true));
break;
case 'strict_var_dump':
return $this->highlightString(var_export($Data['value'], true));
break;
case 'trace':
ini_set('memory_limit', '500M');
$trace =& $Data['trace'];
$i = 0;
$traceCount = count($trace);
$ret = '';
while ( $i < $traceCount ) {
$traceRec =& $trace[$i];
$argsID = 'trace_args_' . $dataIndex . '_' . $i;
$has_args = isset($traceRec['args']);
if ( isset($traceRec['file']) ) {
$func_name = isset($traceRec['class']) ? $traceRec['class'] . $traceRec['type'] . $traceRec['function'] : $traceRec['function'];
$args_link = $has_args ? '<a href="javascript:$Debugger.ToggleTraceArgs(\'' . $argsID . '\');" title="Show/Hide Function Arguments"><b>Function</b></a>' : '<strong>Function</strong>';
$ret .= $args_link . ': ' . $this->getFileLink($traceRec['file'], $traceRec['line'], $func_name);
$ret .= ' in <b>' . basename($traceRec['file']) . '</b> on line <b>' . $traceRec['line'] . '</b><br>';
}
else {
$ret .= 'no file information available';
}
if ( $has_args ) {
// if parameter value is longer then 200 symbols, then leave only first 50
$args = $this->highlightString($this->print_r($traceRec['args'], true));
$ret .= '<div id="' . $argsID . '" style="display: none;">' . $args . '</div>';
}
$i++;
}
return $ret;
break;
case 'profiler':
$profileKey = $Data['profile_key'];
$Data =& $this->ProfilerData[$profileKey];
$runtime = ($Data['ends'] - $Data['begins']); // in seconds
$totals_key = getArrayValue($Data, 'totalsKey');
if ( $totals_key ) {
$total_before = $Data['totalsBefore'];
$total = $this->ProfilerTotals[$totals_key];
$div_width = Array ();
$total_width = ($this->getWindowWidth() - 10);
$div_width['before'] = round(($total_before / $total) * $total_width);
$div_width['current'] = round(($runtime / $total) * $total_width);
$div_width['left'] = round((($total - $total_before - $runtime) / $total) * $total_width);
$subtitle = array_key_exists('subtitle', $Data) ? ' (' . $Data['subtitle'] . ')' : '';
$ret = '<b>Name' . $subtitle . '</b>: ' . $Data['description'] . '<br />';
$additional = isset($Data['additional']) ? $Data['additional'] : Array ();
if ( isset($Data['file']) ) {
array_unshift($additional, Array ('name' => 'File', 'value' => $this->getFileLink($Data['file'], $Data['line'], basename($Data['file']) . ':' . $Data['line'])));
}
array_unshift($additional, Array ('name' => 'Runtime', 'value' => $runtime . 's'));
$ret .= '<div>'; //FF 3.5 needs this!
foreach ($additional as $mixed_param) {
$ret .= '[<strong>' . $mixed_param['name'] . '</strong>: ' . $mixed_param['value'] . '] ';
}
/*if ( isset($Data['file']) ) {
$ret .= '[<b>Runtime</b>: ' . $runtime . 's] [<b>File</b>: ' . $this->getFileLink($Data['file'], $Data['line'], basename($Data['file']) . ':' . $Data['line']) . ']<br />';
}
else {
$ret .= '<b>Runtime</b>: ' . $runtime . 's<br />';
}*/
$ret .= '</div>';
$ret .= '<div class="dbg_profiler" style="width: ' . $div_width['before'] . 'px; border-right: 0px; background-color: #298DDF;"><img src="' . $this->dummyImage . '" width="1" height="1"/></div>';
$ret .= '<div class="dbg_profiler" style="width: ' . $div_width['current'] . 'px; border-left: 0px; border-right: 0px; background-color: #EF4A4A;"><img src="' . $this->dummyImage . '" width="1" height="1"/></div>';
$ret .= '<div class="dbg_profiler" style="width: ' . $div_width['left'] . 'px; border-left: 0px; background-color: #DFDFDF;"><img src="' . $this->dummyImage . '" width="1" height="1"/></div>';
return $ret;
}
else {
return '<b>Name</b>: ' . $Data['description'] . '<br><b>Runtime</b>: ' . $runtime . 's';
}
break;
default:
return 'incorrect debug data';
break;
}
}
/**
* Returns row type for debugger row.
*
* @param integer $data_index Index of the row.
*
* @return string
*/
protected function getRowType($data_index)
{
$data = $this->Data[$data_index];
switch ($data['debug_type']) {
case 'html':
if ( strpos($data['html'], 'SQL Total time') !== false ) {
return self::ROW_TYPE_SQL;
}
break;
case 'error':
$error_map = array(
'Fatal Error' => self::ROW_TYPE_ERROR,
'Warning' => self::ROW_TYPE_WARNING,
'Notice' => self::ROW_TYPE_NOTICE,
'Deprecation Notice' => self::ROW_TYPE_NOTICE,
);
return $error_map[$this->getErrorNameByCode($data['no'])];
break;
case 'exception':
return self::ROW_TYPE_ERROR;
break;
case 'profiler':
if ( preg_match('/^sql_/', $data['profile_key']) ) {
return self::ROW_TYPE_SQL;
}
break;
}
return self::ROW_TYPE_OTHER;
}
/**
* Returns debugger report window width excluding scrollbar
*
* @return int
* @access private
*/
private function getWindowWidth()
{
return DBG_WINDOW_WIDTH - $this->scrollbarWidth - 8;
}
/**
* Tells debugger to skip objects that are heavy in plan of memory usage while printing debug_backtrace results
*
* @param Object $object
* @return bool
* @access private
*/
private function IsBigObject(&$object)
{
$skip_classes = Array(
defined('APPLICATION_CLASS') ? APPLICATION_CLASS : 'kApplication',
'kFactory',
'kUnitConfigReader',
'NParser',
);
foreach ($skip_classes as $class_name) {
if ( strtolower(get_class($object)) == strtolower($class_name) ) {
return true;
}
}
return false;
}
/**
* Advanced version of print_r (for debugger only). Don't print objects recursively.
*
* @param mixed $p_array Value to be printed.
* @param boolean $return_output Return output or print it out.
* @param integer $tab_count Offset in tabs.
*
* @return string
*/
private function print_r(&$p_array, $return_output = false, $tab_count = -1)
{
static $first_line = true;
// not an array at all
if ( !is_array($p_array) ) {
switch ( gettype($p_array) ) {
case 'NULL':
return 'NULL' . "\n";
break;
case 'object':
return $this->processObject($p_array, $tab_count);
break;
case 'resource':
return (string)$p_array . "\n";
break;
default:
// number or string
if ( strlen($p_array) > 200 ) {
$p_array = substr($p_array, 0, 50) . ' ...';
}
return $p_array . "\n";
break;
}
}
$output = '';
if ( count($p_array) > 50 ) {
$array = array_slice($p_array, 0, 50);
$array[] = '...';
}
else {
$array = $p_array;
}
$tab_count++;
$output .= "Array\n" . str_repeat(' ', $tab_count) . "(\n";
$tab_count++;
$tabsign = $tab_count ? str_repeat(' ', $tab_count) : '';
$array_keys = array_keys($array);
foreach ($array_keys as $key) {
switch ( gettype($array[$key]) ) {
case 'array':
$output .= $tabsign . '[' . $key . '] = ' . $this->print_r($array[$key], true, $tab_count);
break;
case 'boolean':
$output .= $tabsign . '[' . $key . '] = ' . ($array[$key] ? 'true' : 'false') . "\n";
break;
case 'integer':
case 'double':
case 'string':
if ( strlen($array[$key]) > 200 ) {
$array[$key] = substr($array[$key], 0, 50) . ' ...';
}
$output .= $tabsign . '[' . $key . '] = ' . $array[$key] . "\n";
break;
case 'NULL':
$output .= $tabsign . '[' . $key . "] = NULL\n";
break;
case 'object':
$output .= $tabsign . '[' . $key . "] = ";
$output .= "Object (" . get_class($array[$key]) . ") = \n" . str_repeat(' ', $tab_count + 1) . "(\n";
$output .= $this->processObject($array[$key], $tab_count + 2);
$output .= str_repeat(' ', $tab_count + 1) . ")\n";
break;
default:
$output .= $tabsign . '[' . $key . '] unknown = ' . gettype($array[$key]) . "\n";
break;
}
}
$tab_count--;
$output .= str_repeat(' ', $tab_count) . ")\n";
if ( $first_line ) {
$first_line = false;
$output .= "\n";
}
$tab_count--;
if ( $return_output ) {
return $output;
}
else {
echo $output;
}
return true;
}
/**
* Returns string representation of given object (more like print_r, but with recursion prevention check)
*
* @param Object $object
* @param int $tab_count
* @return string
* @access private
*/
private function processObject(&$object, $tab_count)
{
$object_class = get_class($object);
if ( !in_array($object_class, $this->RecursionStack) ) {
if ( $this->IsBigObject($object) ) {
return 'SKIPPED (class: ' . $object_class . ")\n";
}
$attribute_names = get_class_vars($object_class);
if ( !$attribute_names ) {
return "NO_ATTRIBUTES\n";
}
else {
$output = '';
array_push($this->RecursionStack, $object_class);
$tabsign = $tab_count ? str_repeat(' ', $tab_count) : '';
foreach ($attribute_names as $attribute_name => $attribute_value) {
if ( is_object($object->$attribute_name) ) {
// it is object
$output .= $tabsign . '[' . $attribute_name . '] = ' . $this->processObject($object->$attribute_name, $tab_count + 1);
}
else {
$output .= $tabsign . '[' . $attribute_name . '] = ' . $this->print_r($object->$attribute_name, true, $tab_count);
}
}
array_pop($this->RecursionStack);
return $output;
}
}
else {
// object [in recursion stack]
return '*** RECURSION *** (class: ' . $object_class . ")\n";
}
}
/**
* Format SQL Query using predefined formatting
* and highlighting techniques
*
* @param string $sql
* @return string
* @access public
*/
public function formatSQL($sql)
{
$sql = trim(preg_replace('/(\n|\t| )+/is', ' ', $sql));
// whitespace in the beginning of the regex is to avoid splitting inside words, for example "FROM int_ConfigurationValues" into "FROM intConfiguration\n\tValues"
$formatted_sql = preg_replace('/\s(CREATE TABLE|DROP TABLE|SELECT|UPDATE|SET|REPLACE|INSERT|DELETE|VALUES|FROM|LEFT JOIN|INNER JOIN|LIMIT|WHERE|HAVING|GROUP BY|ORDER BY)\s/is', "\n\t$1 ", ' ' . $sql);
$formatted_sql = $this->highlightString($formatted_sql);
if ( defined('DBG_SQL_EXPLAIN') && DBG_SQL_EXPLAIN ) {
if ( substr($sql, 0, 6) == 'SELECT' ) {
$formatted_sql .= '<br/>' . '<strong>Explain</strong>:<br /><br />';
$explain_result = $this->Application->Conn->Query('EXPLAIN ' . $sql, null, true);
$explain_table = '';
foreach ($explain_result as $explain_row) {
if ( !$explain_table ) {
// first row -> draw header
$explain_table .= '<tr class="explain_header"><td>' . implode('</td><td>', array_keys($explain_row)) . '</td></tr>';
}
$explain_table .= '<tr><td>' . implode('</td><td>', $explain_row) . '</td></tr>';
}
$formatted_sql .= '<table class="dbg_explain_table">' . $explain_table . '</table>';
}
}
return $formatted_sql;
}
/**
* Highlights given string using "highlight_string" method
*
* @param string $string
* @return string
* @access public
*/
public function highlightString($string)
{
if ( !(defined('DBG_USE_HIGHLIGHT') && DBG_USE_HIGHLIGHT) || $this->_compileError ) {
return nl2br($string);
}
$string = str_replace(Array ('\\', '/'), Array ('_no_match_string_', '_n_m_s_'), $string);
$this->_compileError = true; // next line is possible cause of compile error
$string = highlight_string('<?php ' . $string . ' ?>', true);
$this->_compileError = false;
$string = str_replace(Array ('_no_match_string_', '_n_m_s_'), Array ('\\', '/'), $string);
if ( strlen($string) >= 65536 ) {
// preg_replace will fail, when string is longer, then 65KB
return str_replace(Array ('&lt;?php&nbsp;', '?&gt;'), '', $string);
}
return preg_replace('/&lt;\?(.*)php&nbsp;(.*)\?&gt;/Us', '\\2', $string);
}
/**
* Determine by php type of browser used to show debugger
*
* @return bool
* @access private
*/
private function isGecko()
{
// we need isset because we may run scripts from shell with no user_agent at all
return isset($_SERVER['HTTP_USER_AGENT']) && strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'firefox') !== false;
}
/**
* Returns link for editing php file (from error) in external editor
*
* @param string $file filename with path from root folder
* @param int $line_number line number in file where error is found
* @param string $title text to show on file edit link
* @return string
* @access public
*/
public function getFileLink($file, $line_number = 1, $title = '')
{
if ( !$title ) {
$title = str_replace('/', '\\', $this->getLocalFile($file));
}
$local_file = $this->getLocalFile($file);
$url_params = $this->editorUrlData['params'];
foreach ( $url_params as $param_name => $param_value ) {
$url_params[$param_name] = str_replace(
array('%F', '%L'),
array($local_file, $line_number),
$param_value
);
}
$url = $this->editorUrlData['url'] . '?' . http_build_query($url_params);
return '<a href="' . $url . '">' . $title . '</a>';
}
/**
* Converts filepath on server to filepath in mapped DocumentRoot on developer pc
*
* @param string $remoteFile
* @return string
* @access private
*/
private function getLocalFile($remoteFile)
{
return preg_replace('/^' . preg_quote(DOC_ROOT, '/') . '/', DBG_LOCAL_BASE_PATH, $remoteFile, 1);
}
/**
* Appends call trace till this method call
*
* @param int $levels_to_shift
* @return void
* @access public
*/
public function appendTrace($levels_to_shift = 1)
{
$levels_shifted = 0;
$trace = debug_backtrace();
while ( $levels_shifted < $levels_to_shift ) {
array_shift($trace);
$levels_shifted++;
}
$this->Data[] = Array ('trace' => $trace, 'debug_type' => 'trace');
}
/**
* Appends call trace till this method call
*
* @param Exception $exception
* @return void
* @access private
*/
private function appendExceptionTrace(&$exception)
{
$trace = $exception->getTrace();
$this->Data[] = Array('trace' => $trace, 'debug_type' => 'trace');
}
/**
* Adds memory usage statistics
*
* @param string $msg
* @param int $used
* @return void
* @access public
*/
public function appendMemoryUsage($msg, $used = null)
{
if ( !isset($used) ) {
$used = round(memory_get_usage() / 1024);
}
$this->appendHTML('<b>Memory usage</b> ' . $msg . ' ' . $used . 'Kb');
}
/**
* Appends HTML code without transformations
*
* @param string $html
* @return void
* @access public
*/
public function appendHTML($html)
{
$this->Data[] = Array ('html' => $html, 'debug_type' => 'html');
}
/**
* Inserts HTML code without transformations at given position
*
* @param string $html HTML.
* @param integer $position Position.
*
* @return integer
*/
public function insertHTML($html, $position)
{
array_splice(
$this->Data,
$position,
0,
array(
array('html' => $html, 'debug_type' => 'html'),
)
);
return $position + 1;
}
/**
* Returns instance of FirePHP class
*
* @return FirePHP
* @link http://www.firephp.org/HQ/Use.htm
*/
function firePHP()
{
require_once('FirePHPCore/FirePHP.class.php');
return FirePHP::getInstance(true);
}
/**
* Change debugger info that was already generated before.
* Returns true if html was set.
*
* @param int $index
* @param string $html
* @param string $type = {'append','prepend','replace'}
* @return bool
* @access public
*/
public function setHTMLByIndex($index, $html, $type = 'append')
{
if ( !isset($this->Data[$index]) || $this->Data[$index]['debug_type'] != 'html' ) {
return false;
}
switch ( $type ) {
case 'append':
$this->Data[$index]['html'] .= '<br>' . $html;
break;
case 'prepend':
$this->Data[$index]['html'] = $this->Data[$index]['html'] . '<br>' . $html;
break;
case 'replace':
$this->Data[$index]['html'] = $html;
break;
}
return true;
}
/**
* Move $debugLineCount lines of input from debug output
* end to beginning.
*
* @param int $debugLineCount
* @return void
* @access private
*/
private function moveToBegin($debugLineCount)
{
$lines = array_splice($this->Data, count($this->Data) - $debugLineCount, $debugLineCount);
$this->Data = array_merge($lines, $this->Data);
}
/**
* Moves all debugger report lines after $debugLineCount into $new_row position
*
* @param int $new_row
* @param int $debugLineCount
* @return void
* @access private
*/
private function moveAfterRow($new_row, $debugLineCount)
{
$lines = array_splice($this->Data, count($this->Data) - $debugLineCount, $debugLineCount);
$rows_before = array_splice($this->Data, 0, $new_row, $lines);
$this->Data = array_merge($rows_before, $this->Data);
}
/**
* Appends HTTP REQUEST information to debugger report
*
* @return void
* @access private
*/
private function appendRequest()
{
if ( isset($_SERVER['SCRIPT_FILENAME']) ) {
$script = $_SERVER['SCRIPT_FILENAME'];
}
else {
$script = $_SERVER['DOCUMENT_ROOT'] . $_SERVER['PHP_SELF'];
}
$insert_at_index = $this->HeaderEndingDataIndex;
$insert_at_index = $this->insertHTML(
'ScriptName: <b>' . $this->getFileLink($script, 1, basename($script)) . '</b> (<b>' . dirname($script) . '</b>)',
$insert_at_index
);
if ( $this->_isAjax ) {
$insert_at_index = $this->insertHTML(
'RequestURI: ' . $_SERVER['REQUEST_URI'] . ' (QS Length:' . strlen($_SERVER['QUERY_STRING']) . ')',
$insert_at_index
);
}
$tools_html = ' <table style="width: ' . $this->getWindowWidth() . 'px;">
<tr>
<td>' . $this->_getDomViewerHTML() . '</td>
<td>' . $this->_getToolsHTML() . '</td>
</tr>
</table>';
$insert_at_index = $this->insertHTML($tools_html, $insert_at_index);
ob_start();
?>
<table border="0" cellspacing="0" cellpadding="0" class="dbg_flat_table" style="width: <?php echo $this->getWindowWidth(); ?>px;">
<thead style="font-weight: bold;">
<td width="20">Src</td><td>Name</td><td>Value</td>
</thead>
<?php
if ( is_object($this->Application) ) {
$super_globals = array(
'GE' => $this->Application->HttpQuery->Get,
'PO' => $this->Application->HttpQuery->Post,
'CO' => $this->Application->HttpQuery->Cookie,
);
}
else {
$super_globals = array('GE' => $_GET, 'PO' => $_POST, 'CO' => $_COOKIE);
}
foreach ($super_globals as $prefix => $data) {
foreach ($data as $key => $value) {
if ( !is_array($value) && trim($value) == '' ) {
$value = '<b class="debug_error">no value</b>';
}
else {
$value = htmlspecialchars($this->print_r($value, true), ENT_QUOTES, 'UTF-8');
}
echo '<tr><td>' . $prefix . '</td><td>' . $key . '</td><td>' . $value . '</td></tr>';
}
}
?>
</table>
<?php
$this->insertHTML(ob_get_contents(), $insert_at_index);
ob_end_clean();
}
/**
* Appends php session content to debugger output
*
* @return void
* @access private
*/
private function appendSession()
{
if ( isset($_SESSION) && $_SESSION ) {
$this->appendHTML('PHP Session: [<b>' . ini_get('session.name') . '</b>]');
$this->dumpVars($_SESSION);
$this->moveToBegin(2);
}
}
/**
* Starts profiling of a given $key
*
* @param string $key
* @param string $description
* @param int $timeStamp
* @return void
* @access public
*/
public function profileStart($key, $description = null, $timeStamp = null)
{
if ( !isset($timeStamp) ) {
$timeStamp = microtime(true);
}
$this->ProfilerData[$key] = Array ('begins' => $timeStamp, 'ends' => 5000, 'debuggerRowID' => count($this->Data));
if ( isset($description) ) {
$this->ProfilerData[$key]['description'] = $description;
}
if ( substr($key, 0, 4) == 'sql_' ) {
// append place from what was called
$trace_results = debug_backtrace();
$trace_count = count($trace_results);
$i = 0;
while ( $i < $trace_count ) {
if ( !isset($trace_results[$i]['file']) ) {
$i++;
continue;
}
$trace_file = basename($trace_results[$i]['file']);
if ( $trace_file != 'db_connection.php' && $trace_file != 'db_load_balancer.php' && $trace_file != 'adodb.inc.php' ) {
break;
}
$i++;
}
$this->ProfilerData[$key]['file'] = $trace_results[$i]['file'];
$this->ProfilerData[$key]['line'] = $trace_results[$i]['line'];
if ( isset($trace_results[$i + 1]['object']) && isset($trace_results[$i + 1]['object']->Prefix) ) {
/** @var kBase $object */
$object =& $trace_results[$i + 1]['object'];
$prefix_special = rtrim($object->Prefix . '.' . $object->Special, '.');
$this->ProfilerData[$key]['prefix_special'] = $prefix_special;
}
unset($trace_results);
}
$this->Data[] = Array ('profile_key' => $key, 'debug_type' => 'profiler');
}
/**
* Ends profiling for a given $key
*
* @param string $key
* @param string $description
* @param int $timeStamp
* @return void
* @access public
*/
public function profileFinish($key, $description = null, $timeStamp = null)
{
if ( !isset($timeStamp) ) {
$timeStamp = microtime(true);
}
$this->ProfilerData[$key]['ends'] = $timeStamp;
if ( isset($description) ) {
$this->ProfilerData[$key]['description'] = $description;
}
if ( substr($key, 0, 4) == 'sql_' ) {
$func_arguments = func_get_args();
$rows_affected = $func_arguments[3];
$additional = Array ();
if ( $rows_affected > 0 ) {
$additional[] = Array ('name' => 'Affected Rows', 'value' => $rows_affected);
if ( isset($func_arguments[4]) ) {
if ( strlen($func_arguments[4]) > 200 ) {
$func_arguments[4] = substr($func_arguments[4], 0, 50) . ' ...';
}
$additional[] = Array ('name' => 'Result', 'value' => $func_arguments[4]);
}
}
$additional[] = Array ('name' => 'Query Number', 'value' => $func_arguments[5]);
if ( $func_arguments[6] ) {
$this->profilerAddTotal('cachable_queries', $key);
$this->ProfilerData[$key]['subtitle'] = 'cachable';
}
if ( (string)$func_arguments[7] !== '' ) {
$additional[] = Array ('name' => 'Server #', 'value' => $func_arguments[7]);
}
if ( array_key_exists('prefix_special', $this->ProfilerData[$key]) ) {
$additional[] = Array ('name' => 'PrefixSpecial', 'value' => $this->ProfilerData[$key]['prefix_special']);
}
$this->ProfilerData[$key]['additional'] =& $additional;
}
}
/**
* Collects total execution time from profiler record
*
* @param string $total_key
* @param string $key
* @param int $value
* @return void
* @access public
*/
public function profilerAddTotal($total_key, $key = null, $value = null)
{
if ( !isset($this->ProfilerTotals[$total_key]) ) {
$this->ProfilerTotals[$total_key] = 0;
$this->ProfilerTotalCount[$total_key] = 0;
}
if ( !isset($value) ) {
$value = $this->ProfilerData[$key]['ends'] - $this->ProfilerData[$key]['begins'];
}
if ( isset($key) ) {
$this->ProfilerData[$key]['totalsKey'] = $total_key;
$this->ProfilerData[$key]['totalsBefore'] = $this->ProfilerTotals[$total_key];
}
$this->ProfilerTotals[$total_key] += $value;
$this->ProfilerTotalCount[$total_key]++;
}
/**
* Traces relative code execution speed between this method calls
*
* @param string $message
* @return void
* @access public
*/
public function appendTimestamp($message)
{
global $start;
$time = microtime(true);
$from_last = $time - $this->LastMoment;
$from_start = $time - $start;
$this->appendHTML(sprintf("<strong>%s</strong> %.5f from last %.5f from start", $message, $from_last, $from_start));
$this->LastMoment = $time;
}
/**
* Returns unique ID for each method call
*
* @return int
* @access public
*/
public function generateID()
{
list($usec, $sec) = explode(' ', microtime());
$id_part_1 = substr($usec, 4, 4);
$id_part_2 = mt_rand(1, 9);
$id_part_3 = substr($sec, 6, 4);
$digit_one = substr($id_part_1, 0, 1);
if ( $digit_one == 0 ) {
$digit_one = mt_rand(1, 9);
$id_part_1 = preg_replace('/^0/', '', $id_part_1);
$id_part_1 = $digit_one . $id_part_1;
}
return $id_part_1 . $id_part_2 . $id_part_3;
}
/**
* Returns error name based on it's code
*
* @param int $error_code
* @return string
* @access private
*/
private function getErrorNameByCode($error_code)
{
$error_map = Array (
'Fatal Error' => Array (E_RECOVERABLE_ERROR, E_USER_ERROR, E_ERROR, E_CORE_ERROR, E_COMPILE_ERROR, E_PARSE),
'Warning' => Array (E_WARNING, E_USER_WARNING, E_CORE_WARNING, E_COMPILE_WARNING),
'Notice' => Array (E_NOTICE, E_USER_NOTICE, E_STRICT),
);
if ( defined('E_DEPRECATED') ) {
// Since PHP 5.3.
$error_map['Deprecation Notice'] = array(E_DEPRECATED, E_USER_DEPRECATED);
}
foreach ($error_map as $error_name => $error_codes) {
if ( in_array($error_code, $error_codes) ) {
return $error_name;
}
}
return '';
}
/**
* Returns profile total key (check against missing key too)
*
* @param string $key
* @return int
* @access private
*/
private function getProfilerTotal($key)
{
if ( isset($this->ProfilerTotalCount[$key]) ) {
return (int)$this->ProfilerTotalCount[$key];
}
return 0;
}
/**
* Counts how much calls were made to a place, where this method is called (basic version of profiler)
*
* @param string $title
* @param int $level
* @return void
* @access public
*/
public function ProfilePoint($title, $level = 1)
{
$trace_results = debug_backtrace();
$level = min($level, count($trace_results) - 1);
do {
$point = $trace_results[$level];
$location = $point['file'] . ':' . $point['line'];
$level++;
$has_more = isset($trace_results[$level]);
} while ( $has_more && $point['function'] == $trace_results[$level]['function'] );
if ( !isset($this->ProfilePoints[$title]) ) {
$this->ProfilePoints[$title] = Array ();
}
if ( !isset($this->ProfilePoints[$title][$location]) ) {
$this->ProfilePoints[$title][$location] = 0;
}
$this->ProfilePoints[$title][$location]++;
}
/**
* Generates report
*
* @param boolean $return_result Returns or output report contents.
* @param boolean $clean_output_buffer Clean output buffers before displaying anything.
* @param boolean $is_shutdown_func Called from shutdown function.
*
* @return string
*/
public function printReport($return_result = false, $clean_output_buffer = true, $is_shutdown_func = false)
{
if ( $this->_inReportPrinting ) {
// don't print same report twice (in case if shutdown function used + compression + fatal error)
return '';
}
$this->_inReportPrinting = true;
$last_error = error_get_last();
if ( !is_null($last_error) && $is_shutdown_func ) {
$this->saveError(
$last_error['type'],
$last_error['message'],
$last_error['file'],
$last_error['line'],
null,
$is_shutdown_func
);
}
$this->profileFinish('script_runtime');
$this->_breakOutOfBuffering(!$return_result);
$debugger_start = memory_get_usage();
if ( defined('SPACER_URL') ) {
$this->dummyImage = SPACER_URL;
}
$this->InitReport(); // set parameters required by AJAX
// defined here, because user can define this constant while script is running, not event before debugger is started
DebuggerUtil::safeDefine('DBG_RAISE_ON_WARNINGS', 0);
DebuggerUtil::safeDefine('DBG_TOOLBAR_BUTTONS', 1);
$this->appendRequest();
$this->appendSession(); // show php session if any
// ensure, that 1st line of debug output always is this one:
$top_line = '<table cellspacing="0" cellpadding="0" style="width: ' . $this->getWindowWidth() . 'px; margin: 0px;"><tr><td align="left" width="50%">[<a href="javascript:window.location.reload();">Reload Frame</a>] [<a href="javascript:$Debugger.Toggle(27);">Hide Debugger</a>] [<a href="javascript:$Debugger.Clear();">Clear Debugger</a>]</td><td align="right" width="50%">[Current Time: <b>' . date('H:i:s') . '</b>] [File Size: <b>#DBG_FILESIZE#</b>]</td></tr><tr><td align="left" colspan="2" style="padding-top: 5px;">' . $this->getFilterDropdown() . '</td></tr></table>';
$this->appendHTML($top_line);
$this->moveToBegin(1);
if ( count($this->ProfilePoints) > 0 ) {
foreach ($this->ProfilePoints as $point => $locations) {
arsort($this->ProfilePoints[$point]);
}
$this->appendHTML($this->highlightString($this->print_r($this->ProfilePoints, true)));
}
if ( DebuggerUtil::constOn('DBG_SQL_PROFILE') && isset($this->ProfilerTotals['sql']) ) {
// sql query profiling was enabled -> show totals
if ( array_key_exists('cachable_queries', $this->ProfilerTotalCount) ) {
$append = ' <strong>Cachable queries</strong>: ' . $this->ProfilerTotalCount['cachable_queries'];
}
else {
$append = '';
}
$this->appendHTML('<b>SQL Total time:</b> ' . $this->ProfilerTotals['sql'] . ' <b>Number of queries</b>: ' . $this->ProfilerTotalCount['sql'] . $append);
}
if ( DebuggerUtil::constOn('DBG_PROFILE_INCLUDES') && isset($this->ProfilerTotals['includes']) ) {
// included file profiling was enabled -> show totals
$this->appendHTML('<b>Included Files Total time:</b> ' . $this->ProfilerTotals['includes'] . ' Number of includes: ' . $this->ProfilerTotalCount['includes']);
}
if ( DebuggerUtil::constOn('DBG_PROFILE_MEMORY') ) {
// detailed memory usage reporting by objects was enabled -> show totals
$this->appendHTML('<b>Memory used by Objects:</b> ' . round($this->ProfilerTotals['objects'] / 1024, 2) . 'Kb');
}
if ( DebuggerUtil::constOn('DBG_INCLUDED_FILES') ) {
$files = get_included_files();
$this->appendHTML('<strong>Included files:</strong>');
foreach ($files as $file) {
$this->appendHTML($this->getFileLink($this->getLocalFile($file)) . ' (' . round(filesize($file) / 1024, 2) . 'Kb)');
}
}
if ( DebuggerUtil::constOn('DBG_PROFILE_INCLUDES') ) {
$totals = $totals_configs = Array ('mem' => 0, 'time' => 0);
$this->appendHTML('<b>Included files statistics:</b>' . (DebuggerUtil::constOn('DBG_SORT_INCLUDES_MEM') ? ' (sorted by memory usage)' : ''));
if ( is_array($this->IncludesData['mem']) ) {
if ( DebuggerUtil::constOn('DBG_SORT_INCLUDES_MEM') ) {
array_multisort($this->IncludesData['mem'], SORT_DESC, $this->IncludesData['file'], $this->IncludesData['time'], $this->IncludesData['level']);
}
foreach ($this->IncludesData['file'] as $key => $file_name) {
$this->appendHTML(str_repeat('&nbsp;->&nbsp;', ($this->IncludesData['level'][$key] >= 0 ? $this->IncludesData['level'][$key] : 0)) . $file_name . ' Mem: ' . sprintf("%.4f Kb", $this->IncludesData['mem'][$key] / 1024) . ' Time: ' . sprintf("%.4f", $this->IncludesData['time'][$key]));
if ( $this->IncludesData['level'][$key] == 0 ) {
$totals['mem'] += $this->IncludesData['mem'][$key];
$totals['time'] += $this->IncludesData['time'][$key];
}
elseif ( $this->IncludesData['level'][$key] == -1 ) {
$totals_configs['mem'] += $this->IncludesData['mem'][$key];
$totals_configs['time'] += $this->IncludesData['time'][$key];
}
}
$this->appendHTML('<b>Sub-Total classes:</b> ' . ' Mem: ' . sprintf("%.4f Kb", $totals['mem'] / 1024) . ' Time: ' . sprintf("%.4f", $totals['time']));
$this->appendHTML('<b>Sub-Total configs:</b> ' . ' Mem: ' . sprintf("%.4f Kb", $totals_configs['mem'] / 1024) . ' Time: ' . sprintf("%.4f", $totals_configs['time']));
$this->appendHTML('<span class="error"><b>Grand Total:</b></span> ' . ' Mem: ' . sprintf("%.4f Kb", ($totals['mem'] + $totals_configs['mem']) / 1024) . ' Time: ' . sprintf("%.4f", $totals['time'] + $totals_configs['time']));
}
}
$skip_reporting = DebuggerUtil::constOn('DBG_SKIP_REPORTING') || DebuggerUtil::constOn('DBG_ZEND_PRESENT');
if ( ($this->_isAjax && !DebuggerUtil::constOn('DBG_SKIP_AJAX')) || !$skip_reporting ) {
$debug_file = $this->tempFolder . '/debug_' . $this->rowSeparator . '.txt';
if ( file_exists($debug_file) ) {
unlink($debug_file);
}
$i = 0;
$fp = fopen($debug_file, 'a');
$lineCount = count($this->Data);
while ( $i < $lineCount ) {
$html = $this->prepareHTML($i);
$row_type = $this->getRowType($i);
fwrite($fp, json_encode(Array ('html' => $html, 'row_type' => $row_type)) . $this->rowSeparator);
$i++;
}
fclose($fp);
}
if ( $skip_reporting ) {
// let debugger write report and then don't output anything
return '';
}
$application =& kApplication::Instance();
$dbg_path = str_replace(FULL_PATH, '', $this->tempFolder);
$debugger_params = Array (
'FilterTypes' => $this->_filterTypes,
'RowSeparator' => $this->rowSeparator,
'ErrorsCount' => (int)$this->getProfilerTotal('error_handling'),
'IsFatalError' => $this->_fatalErrorHappened(),
'SQLCount' => (int)$this->getProfilerTotal('sql'),
'SQLTime' => isset($this->ProfilerTotals['sql']) ? sprintf('%.5f', $this->ProfilerTotals['sql']) : 0,
'ScriptTime' => sprintf('%.5f', $this->ProfilerData['script_runtime']['ends'] - $this->ProfilerData['script_runtime']['begins']),
'ScriptMemory' => DebuggerUtil::formatSize($this->getMemoryUsed($debugger_start)),
'Shortcut' => DBG_SHORTCUT,
);
ob_start();
// the <script .. /script> and hidden div helps browser to break out of script tag or attribute esacped
// with " or ' in case fatal error (or user-error) occurs inside it in compiled template,
// otherwise it has no effect
?>
<div style="display: none" x='nothing'><script></script></div><html><body></body></html>
<link rel="stylesheet" rev="stylesheet" href="<?php echo $this->baseURL; ?>/debugger.css?v2" type="text/css" media="screen" />
<script type="text/javascript" src="<?php echo $this->baseURL; ?>/debugger.js?v4"></script>
<script type="text/javascript">
var $Debugger = new Debugger(<?php echo json_encode($debugger_params); ?>);
$Debugger.createEnvironment(<?php echo DBG_WINDOW_WIDTH; ?>, <?php echo $this->getWindowWidth(); ?>);
$Debugger.DOMViewerURL = '<?php echo constant('DBG_DOMVIEWER'); ?>';
$Debugger.DebugURL = '<?php echo $this->baseURL.'/debugger_responce.php?sid='.$this->rowSeparator.'&path='.urlencode($dbg_path); ?>';
$Debugger.EventURL = '<?php echo /*is_object($application->Factory) &&*/ $application->InitDone ? $application->HREF('dummy', '', Array ('pass' => 'm', '__NO_REWRITE__' => 1)) : ''; ?>';
$Debugger.BasePath = '<?php echo $this->basePath; ?>';
<?php
$is_install = defined('IS_INSTALL') && IS_INSTALL;
if ( $this->_fatalErrorHappened()
|| (!$is_install && DBG_RAISE_ON_WARNINGS && $this->WarningCount)
) {
echo '$Debugger.Toggle();';
}
if ( DBG_TOOLBAR_BUTTONS ) {
echo '$Debugger.AddToolbar("$Debugger");';
}
?>
window.focus();
</script>
<?php
if ( $return_result ) {
$ret = ob_get_contents();
if ( $clean_output_buffer ) {
ob_end_clean();
}
$ret .= $this->getShortReport($this->getMemoryUsed($debugger_start));
return $ret;
}
else {
if ( !DebuggerUtil::constOn('DBG_HIDE_FULL_REPORT') ) {
$this->_breakOutOfBuffering();
}
elseif ( $clean_output_buffer ) {
ob_clean();
}
echo $this->getShortReport($this->getMemoryUsed($debugger_start));
}
return '';
}
function getFilterDropdown()
{
$filter_options = '';
foreach ( $this->_filterTypes as $filter_type ) {
$filter_options .= '<option value="' . $filter_type . '">' . $filter_type . '</option>';
}
return 'Show: <select id="dbg_filter" onchange="$Debugger.Filter()"><option value="">All</option>' . $filter_options .'</select>';
}
function getMemoryUsed($debugger_start)
{
if ( !isset($this->ProfilerTotals['error_handling']) ) {
$memory_used = $debugger_start;
$this->ProfilerTotalCount['error_handling'] = 0;
}
else {
$memory_used = $debugger_start - $this->ProfilerTotals['error_handling'];
}
return $memory_used;
}
/**
* Format's memory usage report by debugger
*
* @param int $memory_used
* @return string
* @access private
*/
private function getShortReport($memory_used)
{
if ( DebuggerUtil::constOn('DBG_TOOLBAR_BUTTONS') ) {
// evenrything is in toolbar - don't duplicate
return '';
}
else {
// toolbar not visible, then show sql & error count too
$info = Array (
'Script Runtime' => 'PROFILE:script_runtime',
'SQL\'s Runtime' => 'PROFILE_T:sql',
'-' => 'SEP:-',
'Notice / Warning' => 'PROFILE_TC:error_handling',
'SQLs Count' => 'PROFILE_TC:sql',
);
}
$ret = ''; // '<tr><td>Application:</td><td><b>' . DebuggerUtil::formatSize($memory_used) . '</b> (' . $memory_used . ')</td></tr>';
foreach ($info as $title => $value_key) {
list ($record_type, $record_data) = explode(':', $value_key, 2);
switch ( $record_type ) {
case 'PROFILE': // profiler totals value
$Data =& $this->ProfilerData[$record_data];
$profile_time = ($Data['ends'] - $Data['begins']); // in seconds
$ret .= '<tr><td>' . $title . ':</td><td><b>' . sprintf('%.5f', $profile_time) . ' s</b></td></tr>';
break;
case 'PROFILE_TC': // profile totals record count
$record_cell = '<td>';
if ( $record_data == 'error_handling' && $this->ProfilerTotalCount[$record_data] > 0 ) {
$record_cell = '<td class="debug_error">';
}
$ret .= '<tr>' . $record_cell . $title . ':</td>' . $record_cell . '<b>' . $this->ProfilerTotalCount[$record_data] . '</b></td></tr>';
break;
case 'PROFILE_T': // profile total
$record_cell = '<td>';
$total = array_key_exists($record_data, $this->ProfilerTotals) ? $this->ProfilerTotals[$record_data] : 0;
$ret .= '<tr>' . $record_cell . $title . ':</td>' . $record_cell . '<b>' . sprintf('%.5f', $total) . ' s</b></td></tr>';
break;
case 'SEP':
$ret .= '<tr><td colspan="2" style="height: 1px; background-color: #000000; padding: 0px;"><img src="' . $this->dummyImage . '" height="1" alt=""/></td></tr>';
break;
}
}
return '<br /><table class="dbg_stats_table"><tr><td style="border-color: #FFFFFF;"><table class="dbg_stats_table" align="left">' . $ret . '</table></td></tr></table>';
}
/**
* Detects if there was a fatal error at some point
*
* @return boolean
*/
private function _fatalErrorHappened()
{
return $this->_fatalErrorHash !== 0;
}
/**
* Creates error hash
*
* @param string $errfile File, where error happened.
* @param integer $errline Line in file, where error happened.
*
* @return integer
*/
private function _getErrorHash($errfile, $errline)
{
return crc32($errfile . ':' . $errline);
}
/**
* User-defined error handler
*
* @param integer $errno Error code.
* @param string $errstr Error message.
* @param string $errfile Error file.
* @param integer $errline Error line.
* @param array $errcontext Error context.
* @param boolean $is_shutdown_func Called from shutdown function.
*
* @return boolean
* @throws Exception When unknown error code given.
*/
public function saveError(
$errno,
$errstr,
$errfile = null,
$errline = null,
array $errcontext = null,
$is_shutdown_func = false
) {
$this->ProfilerData['error_handling']['begins'] = memory_get_usage();
$errorType = $this->getErrorNameByCode($errno);
if (!$errorType) {
throw new Exception('Unknown error type [' . $errno . ']');
return false;
}
elseif ( substr($errorType, 0, 5) == 'Fatal' ) {
$this->_fatalErrorHash = $this->_getErrorHash($errfile, $errline);
$this->appendTrace(4);
}
elseif ( !kLogger::isErrorOriginAllowed($errfile) ) {
return;
}
$this->expandError($errstr, $errfile, $errline);
$this->Data[] = Array (
'no' => $errno, 'str' => $errstr, 'file' => $errfile, 'line' => $errline,
'context' => $errcontext, 'debug_type' => 'error'
);
$this->ProfilerData['error_handling']['ends'] = memory_get_usage();
$this->profilerAddTotal('error_handling', 'error_handling');
if ($errorType == 'Warning') {
$this->WarningCount++;
}
if ( $this->_fatalErrorHappened()
&& $this->_getErrorHash($errfile, $errline) === $this->_fatalErrorHash
) {
// Append debugger report to data in buffer & clean buffer afterwards.
echo $this->_breakOutOfBuffering(false) . $this->printReport(true);
if ( !$is_shutdown_func ) {
exit;
}
}
return true;
}
/**
* Adds exception details into debugger but don't cause fatal error
*
* @param Exception $exception
* @return void
* @access public
*/
public function appendException($exception)
{
$this->ProfilerData['error_handling']['begins'] = memory_get_usage();
$this->appendExceptionTrace($exception);
$errno = $exception->getCode();
$errstr = $exception->getMessage();
$errfile = $exception->getFile();
$errline = $exception->getLine();
$this->expandError($errstr, $errfile, $errline);
$this->Data[] = Array (
'no' => $errno, 'str' => $errstr, 'file' => $errfile, 'line' => $errline,
'exception_class' => get_class($exception), 'debug_type' => 'exception'
);
$this->ProfilerData['error_handling']['ends'] = memory_get_usage();
$this->profilerAddTotal('error_handling', 'error_handling');
}
/**
* User-defined exception handler
*
* @param Exception $exception
* @return void
* @access public
*/
public function saveException($exception)
{
$this->appendException($exception);
$this->_fatalErrorHash = $this->_getErrorHash($exception->getFile(), $exception->getLine());
// Append debugger report to data in buffer & clean buffer afterwards.
echo $this->_breakOutOfBuffering(false) . $this->printReport(true);
}
/**
* Transforms short error messages into long ones
*
* @param string $errstr
* @param string $errfile
* @param int $errline
* @return void
* @access private
*/
private function expandError(&$errstr, &$errfile, &$errline)
{
$errstr = kLogger::expandMessage($errstr);
list ($errno, $errstr, $sql) = kLogger::parseDatabaseError($errstr);
if ( $errno != 0 ) {
$errstr = '<span class="debug_error">' . $errstr . ' (' . $errno . ')</span><br/><strong>SQL</strong>: ' . $this->formatSQL($sql);
}
if ( strpos($errfile, 'eval()\'d code') !== false ) {
$errstr = '[<b>EVAL</b>, line <b>' . $errline . '</b>]: ' . $errstr;
$tmpStr = $errfile;
$pos = strpos($tmpStr, '(');
$errfile = substr($tmpStr, 0, $pos);
$pos++;
$errline = substr($tmpStr, $pos, strpos($tmpStr, ')', $pos) - $pos);
}
}
/**
* Break buffering in case if fatal error is happened in the middle
*
* @param bool $flush
* @return string
* @access private
*/
private function _breakOutOfBuffering($flush = true)
{
$buffer_content = Array ();
while ( ob_get_level() ) {
$buffer_content[] = ob_get_clean();
}
$ret = implode('', array_reverse($buffer_content));
if ( $flush ) {
echo $ret;
flush();
}
return $ret;
}
/**
* Saves given message to "vb_debug.txt" file in DocumentRoot
*
* @param string $msg
* @return void
* @access public
*/
public function saveToFile($msg)
{
$fp = fopen($_SERVER['DOCUMENT_ROOT'] . '/vb_debug.txt', 'a');
fwrite($fp, $msg . "\n");
fclose($fp);
}
/**
* Prints given constant values in a table
*
* @param mixed $constants
* @return void
* @access public
*/
public function printConstants($constants)
{
if ( !is_array($constants) ) {
$constants = explode(',', $constants);
}
$constant_tpl = '<tr><td>%s</td><td><b>%s</b></td></tr>';
$ret = '<table class="dbg_flat_table" style="width: ' . $this->getWindowWidth() . 'px;">';
foreach ($constants as $constant_name) {
$ret .= sprintf($constant_tpl, $constant_name, constant($constant_name));
}
$ret .= '</table>';
$this->appendHTML($ret);
}
/**
* Attaches debugger to Application
*
* @return void
* @access public
*/
public function AttachToApplication()
{
if ( !DebuggerUtil::constOn('DBG_HANDLE_ERRORS') ) {
return;
}
if ( class_exists('kApplication') ) {
$this->Application =& kApplication::Instance();
$this->Application->Debugger = $this;
}
// kLogger will auto-detect these automatically
// error/exception handlers registered before debugger will be removed!
set_error_handler( Array ($this, 'saveError') );
set_exception_handler( Array ($this, 'saveException') );
}
/**
* Returns HTML for tools section
*
* @return string
* @access private
*/
private function _getToolsHTML()
{
$html = '<table>
<tr>
<td>System Tools:</td>
<td>
<select id="reset_cache" style="border: 1px solid #000000;">
<option value=""></option>
<option value="events[adm][OnResetModRwCache]">Reset mod_rewrite Cache</option>
<option value="events[adm][OnResetCMSMenuCache]">Reset SMS Menu Cache</option>
<option value="events[adm][OnResetSections]">Reset Sections Cache</option>
<option value="events[adm][OnResetConfigsCache]">Reset Configs Cache</option>
<option value="events[adm][OnRebuildThemes]">Re-build Themes Files</option>
<option value="events[lang][OnReflectMultiLingualFields]">Re-build Multilanguage Fields</option>
<option value="events[adm][OnDeleteCompiledTemplates]">Delete Compiled Templates</option>
</select>
</td>
<td>
<input type="button" class="button" onclick="$Debugger.resetCache(\'reset_cache\');" value="Go"/>
</td>
</tr>
</table>';
return $html;
}
/**
* Returns HTML for dom viewer section
*
* @return string
* @access private
*/
private function _getDomViewerHTML()
{
$html = '<table>
<tr>
<td>
<a href="http://www.brainjar.com/dhtml/domviewer/" target="_blank">DomViewer</a>:
</td>
<td>
<input id="dbg_domviewer" type="text" value="window" style="border: 1px solid #000000;"/>
</td>
<td>
<button class="button" onclick="return $Debugger.OpenDOMViewer();">Show</button>
</td>
</tr>
</table>';
return $html;
}
}
if ( !function_exists('memory_get_usage') ) {
// PHP 4.x and compiled without --enable-memory-limit option
function memory_get_usage()
{
return -1;
}
}
if ( !DebuggerUtil::constOn('DBG_ZEND_PRESENT') ) {
$debugger = new Debugger();
}
if ( DebuggerUtil::constOn('DBG_USE_SHUTDOWN_FUNC') ) {
register_shutdown_function(array(&$debugger, 'printReport'), false, true, true);
}
}
Index: branches/5.2.x/core/units/users/users_event_handler.php
===================================================================
--- branches/5.2.x/core/units/users/users_event_handler.php (revision 16796)
+++ branches/5.2.x/core/units/users/users_event_handler.php (revision 16797)
@@ -1,1952 +1,1952 @@
<?php
/**
* @version $Id$
* @package In-Portal
* @copyright Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license GNU/GPL
* In-Portal is Open Source software.
* This means that this software may have been modified pursuant
* the GNU General Public License, and as distributed it includes
* or is derivative of works licensed under the GNU General Public License
* or other free or open source software licenses.
* See http://www.in-portal.org/license for copyright notices and details.
*/
defined('FULL_PATH') or die('restricted access!');
class UsersEventHandler extends kDBEventHandler
{
/**
* Allows to override standard permission mapping
*
* @return void
* @access protected
* @see kEventHandler::$permMapping
*/
protected function mapPermissions()
{
parent::mapPermissions();
$permissions = Array (
// admin
'OnSetPersistantVariable' => Array('self' => 'view'), // because setting to logged in user only
'OnUpdatePassword' => Array('self' => true),
'OnSaveSelected' => Array ('self' => 'view'),
'OnGeneratePassword' => Array ('self' => 'view'),
// front
'OnRefreshForm' => Array('self' => true),
'OnForgotPassword' => 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);
}
/**
* Builds item (loads if needed)
*
* Pattern: Prototype Manager
*
* @param kEvent $event
* @access protected
*/
protected function OnItemBuild(kEvent $event)
{
parent::OnItemBuild($event);
/** @var kDBItem $object */
$object = $event->getObject();
if ( $event->Special == 'forgot' || $object->getFormName() == 'registration' ) {
$this->_makePasswordRequired($event);
}
}
/**
* Shows only admins when required
*
* @param kEvent $event
* @return void
* @access protected
* @see kDBEventHandler::OnListBuild()
*/
protected function SetCustomQuery(kEvent $event)
{
parent::SetCustomQuery($event);
/** @var kDBList $object */
$object = $event->getObject();
if ( $event->Special == 'regular' ) {
$object->addFilter('primary_filter', '%1$s.UserType = ' . UserType::USER);
}
if ( $event->Special == 'admins' ) {
$object->addFilter('primary_filter', '%1$s.UserType = ' . UserType::ADMIN);
}
if ( !$this->Application->isAdminUser ) {
$object->addFilter('status_filter', '%1$s.Status = ' . STATUS_ACTIVE);
}
if ( $event->Special == 'online' ) {
$object->addFilter('online_users_filter', 's.PortalUserId IS NOT NULL');
}
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
$sql = 'SELECT PortalUserId
FROM ' . $this->Application->GetTempName(TABLE_PREFIX . 'UserGroupRelations', 'prefix:g') . '
WHERE GroupId = ' . (int)$group_id;
$user_ids = $this->Conn->GetCol($sql);
if ( $user_ids ) {
$object->addFilter('already_member_filter', '%1$s.PortalUserId NOT IN (' . implode(',', $user_ids) . ')');
}
}
}
}
/**
* Checks user permission to execute given $event
*
* @param kEvent $event
* @return bool
* @access public
*/
public function CheckPermission(kEvent $event)
{
if ( $event->Name == 'OnLogin' || $event->Name == 'OnLoginAjax' || $event->Name == 'OnLogout' ) {
// permission is checked in OnLogin event directly
return true;
}
if ( $event->Name == 'OnResetRootPassword' ) {
return defined('DBG_RESET_ROOT') && DBG_RESET_ROOT;
}
if ( $event->Name == 'OnLoginAs' ) {
/** @var Session $admin_session */
$admin_session = $this->Application->recallObject('Session.admin');
return $admin_session->LoggedIn();
}
if ( !$this->Application->isAdminUser ) {
$user_id = $this->Application->RecallVar('user_id');
$items_info = $this->Application->GetVar($event->getPrefixSpecial(true));
if ( ($event->Name == 'OnCreate' || $event->Name == 'OnRegisterAjax') && $user_id == USER_GUEST ) {
// "Guest" can create new users
return true;
}
if ( substr($event->Name, 0, 8) == 'OnUpdate' && $user_id > 0 ) {
/** @var UsersItem $user_dummy */
$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 = $user_dummy->getStatusField();
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 == 'OnResetLostPassword' && $event->Special == 'forgot' && $user_id == USER_GUEST ) {
// non-logged in users can reset their password, when reset code is valid
return is_numeric($this->getPassedID($event));
}
if ( substr($event->Name, 0, 8) == 'OnUpdate' && $user_id <= 0 ) {
// guests are not allowed to update their record, because they don't have it :)
return false;
}
}
return parent::CheckPermission($event);
}
/**
* Handles session expiration (redirects to valid template)
*
* @param kEvent $event
*/
function OnSessionExpire($event)
{
$this->Application->resetCounters('UserSessions');
// place 2 of 2 (also in kHTTPQuery::getRedirectParams)
$admin_url_params = Array (
'm_cat_id' => 0, // category means nothing on admin login screen
'm_wid' => '', // remove wid, otherwise parent window may add wid to its name breaking all the frameset (for <a> targets)
'pass' => 'm', // don't pass any other (except "m") prefixes to admin session expiration template
'expired' => 1, // expiration mark to show special error on login screen
'no_pass_through' => 1, // this way kApplication::HREF won't add them again
);
if ($this->Application->isAdmin) {
$this->Application->Redirect('index', $admin_url_params, '', 'index.php');
}
if ($this->Application->GetVar('admin') == 1) {
// Front-End showed in admin's right frame
/** @var Session $session_admin */
$session_admin = $this->Application->recallObject('Session.admin');
if (!$session_admin->LoggedIn()) {
// front-end session created from admin session & both expired
$this->Application->DeleteVar('admin');
$this->Application->Redirect('index', $admin_url_params, '', 'admin/index.php');
}
}
// Front-End session expiration
$get = $this->Application->HttpQuery->getRedirectParams();
$t = $this->Application->GetVar('t');
$get['js_redirect'] = $this->Application->ConfigValue('UseJSRedirect');
$this->Application->Redirect($t ? $t : 'index', $get);
}
/**
* [SCHEDULED TASK] Deletes expired sessions
*
* @param kEvent $event
*/
function OnDeleteExpiredSessions($event)
{
if (defined('IS_INSTALL') && IS_INSTALL) {
return ;
}
/** @var SessionStorage $session_storage */
$session_storage = $this->Application->recallObject('SessionStorage');
$session_storage->DeleteExpired();
}
/**
* Checks user data and logs it in if allowed
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnLogin($event)
{
/** @var kDBItem $object */
$object = $event->getObject( Array ('form_name' => 'login') );
$object->SetFieldsFromHash($this->getSubmittedFields($event));
$username = $object->GetDBField('UserLogin');
$password = $object->GetDBField('UserPassword');
$remember_login = $object->GetDBField('UserRememberLogin') == 1;
/** @var UserHelper $user_helper */
$user_helper = $this->Application->recallObject('UserHelper');
$user_helper->event =& $event;
$result = $user_helper->loginUser($username, $password, false, $remember_login);
if ($result != LoginResult::OK) {
$event->status = kEvent::erFAIL;
$object->SetError('UserLogin', $result == LoginResult::NO_PERMISSION ? 'no_permission' : 'invalid_password');
}
if ( is_object($event->MasterEvent) && ($event->MasterEvent->Name == 'OnLoginAjax') ) {
// used to insert just logged-in user e-mail on "One Step Checkout" form in "Modern Store" theme
$user =& $user_helper->getUserObject();
$event->SetRedirectParam('user_email', $user->GetDBField('Email'));
}
}
/**
* Performs user login from ajax request
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnLoginAjax($event)
{
/** @var AjaxFormHelper $ajax_form_helper */
$ajax_form_helper = $this->Application->recallObject('AjaxFormHelper');
$ajax_form_helper->transitEvent($event, 'OnLogin');
}
/**
* [HOOK] Auto-Logins Front-End user when "Remember Login" cookie is found
*
* @param kEvent $event
*/
function OnAutoLoginUser($event)
{
$remember_login_cookie = $this->Application->GetVar('remember_login');
if (!$remember_login_cookie || $this->Application->isAdmin || $this->Application->LoggedIn()) {
return ;
}
/** @var UserHelper $user_helper */
$user_helper = $this->Application->recallObject('UserHelper');
$user_helper->loginUser('', '', false, false, $remember_login_cookie);
}
/**
* Called when user logs in using old in-portal
*
* @param kEvent $event
*/
function OnInpLogin($event)
{
/** @var UsersSyncronizeManager $sync_manager */
$sync_manager = $this->Application->recallObject('UsersSyncronizeManager', null, Array(), 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->getRedirectParams());
}
}
/**
* Called when user logs in using old in-portal
*
* @param kEvent $event
*/
function OnInpLogout($event)
{
/** @var UsersSyncronizeManager $sync_manager */
$sync_manager = $this->Application->recallObject('UsersSyncronizeManager', null, Array(), Array ('InPortalSyncronize'));
$sync_manager->performAction('LogoutUser');
}
/**
* Performs user logout
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnLogout($event)
{
/** @var UserHelper $user_helper */
$user_helper = $this->Application->recallObject('UserHelper');
$user_helper->event =& $event;
$user_helper->logoutUser();
}
/**
* Redirects user after successful registration to confirmation template (on Front only)
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnAfterItemCreate(kEvent $event)
{
parent::OnAfterItemCreate($event);
$this->afterItemChanged($event);
$this->assignToPrimaryGroup($event);
}
/**
* Performs user registration
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnCreate(kEvent $event)
{
if ( $this->Application->isAdmin ) {
parent::OnCreate($event);
return ;
}
/** @var UsersItem $object */
$object = $event->getObject( Array('form_name' => 'registration') );
$field_values = $this->getSubmittedFields($event);
$user_email = getArrayValue($field_values, 'Email');
$subscriber_id = $user_email ? $this->getSubscriberByEmail($user_email) : false;
if ( $subscriber_id ) {
// update existing subscriber
$object->Load($subscriber_id);
$object->SetDBField('PrimaryGroupId', $this->Application->ConfigValue('User_NewGroup'));
$this->Application->SetVar($event->getPrefixSpecial(true), Array ($object->GetID() => $field_values));
}
$object->SetFieldsFromHash($field_values);
$event->setEventParam('form_data', $field_values);
$status = $object->isLoaded() ? $object->Update() : $object->Create();
if ( !$status ) {
$event->status = kEvent::erFAIL;
$event->redirect = false;
$object->setID( (int)$object->GetID() );
}
$this->setNextTemplate($event, true);
if ( ($event->status == kEvent::erSUCCESS) && $event->redirect ) {
$this->assignToPrimaryGroup($event);
$object->sendEmails();
$this->autoLoginUser($event);
}
}
/**
* Processes user registration from ajax request
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnRegisterAjax(kEvent $event)
{
/** @var AjaxFormHelper $ajax_form_helper */
$ajax_form_helper = $this->Application->recallObject('AjaxFormHelper');
$ajax_form_helper->transitEvent($event, 'OnCreate', Array ('do_refresh' => 1));
}
/**
* Returns subscribed user ID by given e-mail address
*
* @param string $email
* @return int|bool
* @access protected
*/
protected function getSubscriberByEmail($email)
{
/** @var UsersItem $verify_user */
$verify_user = $this->Application->recallObject('u.verify', null, Array ('skip_autoload' => true));
$verify_user->Load($email, 'Email');
return $verify_user->isLoaded() && $verify_user->isSubscriberOnly() ? $verify_user->GetID() : false;
}
/**
* Login user if possible, if not then redirect to corresponding template
*
* @param kEvent $event
*/
function autoLoginUser($event)
{
/** @var UsersItem $object */
$object = $event->getObject();
if ( $object->GetDBField('Status') == STATUS_ACTIVE ) {
/** @var UserHelper $user_helper */
$user_helper = $this->Application->recallObject('UserHelper');
$user =& $user_helper->getUserObject();
$user->Load($object->GetID());
if ( $user_helper->checkLoginPermission() ) {
$user_helper->loginUserById( $user->GetID() );
}
}
}
/**
* Set's new unique resource id to user
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnBeforeItemCreate(kEvent $event)
{
parent::OnBeforeItemCreate($event);
$this->beforeItemChanged($event);
/** @var kCountryStatesHelper $cs_helper */
$cs_helper = $this->Application->recallObject('CountryStatesHelper');
/** @var UsersItem $object */
$object = $event->getObject();
if ( !$object->isSubscriberOnly() ) {
// don't check state-to-country relations for subscribers
$cs_helper->CheckStateField($event, 'State', 'Country');
}
if ( $object->getFormName() != 'login' ) {
$this->_makePasswordRequired($event);
}
$cs_helper->PopulateStates($event, 'State', 'Country');
$this->setUserGroup($object);
/** @var UserHelper $user_helper */
$user_helper = $this->Application->recallObject('UserHelper');
if ( !$user_helper->checkBanRules($object) ) {
$object->SetError('Username', 'banned');
}
$object->SetDBField('IPAddress', $this->Application->getClientIp());
if ( !$this->Application->isAdmin ) {
$object->SetDBField('FrontLanguage', $this->Application->GetVar('m_lang'));
}
}
/**
* Sets primary group of the user
*
* @param kDBItem $object
*/
protected function setUserGroup(&$object)
{
if ($object->Special == 'subscriber') {
$object->SetDBField('PrimaryGroupId', $this->Application->ConfigValue('User_SubscriberGroup'));
return ;
}
// set primary group to user
if ( !$this->Application->isAdminUser ) {
$group_id = $object->GetDBField('PrimaryGroupId');
if ($group_id) {
// check, that group is allowed for Front-End
$sql = 'SELECT GroupId
FROM ' . TABLE_PREFIX . 'UserGroups
WHERE GroupId = ' . (int)$group_id . ' AND FrontRegistration = 1';
$group_id = $this->Conn->GetOne($sql);
}
if (!$group_id) {
// when group not selected OR not allowed -> use default group
$object->SetDBField('PrimaryGroupId', $this->Application->ConfigValue('User_NewGroup'));
}
}
}
/**
* Assigns a user to it's primary group
*
* @param kEvent $event
*/
protected function assignToPrimaryGroup($event)
{
/** @var kDBItem $object */
$object = $event->getObject();
$primary_group_id = $object->GetDBField('PrimaryGroupId');
if ($primary_group_id) {
$ug_table = TABLE_PREFIX . 'UserGroupRelations';
if ( $object->IsTempTable() ) {
$ug_table = $this->Application->GetTempName($ug_table, 'prefix:' . $event->Prefix);
}
$fields_hash = Array (
'PortalUserId' => $object->GetID(),
'GroupId' => $primary_group_id,
);
$this->Conn->doInsert($fields_hash, $ug_table, 'REPLACE');
}
}
/**
* Set's new unique resource id to user
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnAfterItemValidate(kEvent $event)
{
/** @var kDBItem $object */
$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)
{
/** @var kDBItem $object */
$object = $event->getObject( Array ('form_name' => 'recommend') );
$object->SetFieldsFromHash($this->getSubmittedFields($event));
if ( !$object->ValidateField('RecommendEmail') ) {
$event->status = kEvent::erFAIL;
return ;
}
$send_params = Array (
'to_email' => $object->GetDBField('RecommendEmail'),
'to_name' => $object->GetDBField('RecommendEmail'),
);
$user_id = $this->Application->RecallVar('user_id');
$email_sent = $this->Application->emailUser('USER.SUGGEST', $user_id, $send_params);
$this->Application->emailAdmin('USER.SUGGEST');
if ( $email_sent ) {
$event->SetRedirectParam('pass', 'all');
$event->redirect = $this->Application->GetVar('template_success');
}
else {
$event->status = kEvent::erFAIL;
$object->SetError('RecommendEmail', 'send_error');
}
}
/**
* Saves address changes and mades no redirect
*
* @param kEvent $event
*/
function OnUpdateAddress($event)
{
/** @var kDBItem $object */
$object = $event->getObject(Array ('skip_autoload' => true));
$items_info = $this->Application->GetVar($event->getPrefixSpecial(true));
if ( $items_info ) {
$id = key($items_info);
$field_values = $items_info[$id];
if ( $id > 0 ) {
$object->Load($id);
}
$object->setID($id);
$object->SetFieldsFromHash($field_values);
$event->setEventParam('form_data', $field_values);
$object->Validate();
}
/** @var kCountryStatesHelper $cs_helper */
$cs_helper = $this->Application->recallObject('CountryStatesHelper');
$cs_helper->PopulateStates($event, 'State', 'Country');
$event->redirect = false;
}
/**
* Validate subscriber's email & store it to session -> redirect to confirmation template
*
* @param kEvent $event
*/
function OnSubscribeQuery($event)
{
/** @var UsersItem $object */
$object = $event->getObject( Array ('form_name' => 'subscription') );
$object->SetFieldsFromHash($this->getSubmittedFields($event));
if ( !$object->ValidateField('SubscriberEmail') ) {
$event->status = kEvent::erFAIL;
return ;
}
$user_email = $object->GetDBField('SubscriberEmail');
$object->Load($user_email, 'Email');
$event->SetRedirectParam('subscriber_email', $user_email);
if ( $object->isLoaded() && $object->isSubscribed() ) {
$event->redirect = $this->Application->GetVar('unsubscribe_template');
}
else {
$event->redirect = $this->Application->GetVar('subscribe_template');
}
$event->SetRedirectParam('pass', 'm');
}
/**
* Subscribe/Unsubscribe user based on email stored in previous step
*
* @param kEvent $event
*/
function OnSubscribeUser($event)
{
/** @var UsersItem $object */
$object = $event->getObject( Array ('form_name' => 'subscription') );
$user_email = $this->Application->GetVar('subscriber_email');
$object->SetDBField('SubscriberEmail', $user_email);
if ( !$object->ValidateField('SubscriberEmail') ) {
$event->status = kEvent::erFAIL;
return ;
}
$username_required = $object->isRequired('Username');
$this->RemoveRequiredFields($object);
$object->Load($user_email, 'Email');
if ( $object->isLoaded() ) {
if ( $object->isSubscribed() ) {
if ( $event->getEventParam('no_unsubscribe') ) {
// for customization code from FormsEventHandler
return ;
}
if ( $object->isSubscriberOnly() ) {
/** @var kTempTablesHandler $temp_handler */
$temp_handler = $this->Application->recallObject($event->Prefix . '_TempHandler', 'kTempTablesHandler');
$temp_handler->DeleteItems($event->Prefix, '', Array($object->GetID()));
}
else {
$this->RemoveSubscriberGroup( $object->GetID() );
}
$event->redirect = $this->Application->GetVar('unsubscribe_ok_template');
}
else {
$this->AddSubscriberGroup($object);
$event->redirect = $this->Application->GetVar('subscribe_ok_template');
}
}
else {
$object->generatePassword();
$object->SetDBField('Email', $user_email);
if ( $username_required ) {
$object->SetDBField('Username', str_replace('@', '_at_', $user_email));
}
$object->SetDBField('Status', STATUS_ACTIVE); // make user subscriber Active by default
if ( $object->Create() ) {
$this->AddSubscriberGroup($object);
$event->redirect = $this->Application->GetVar('subscribe_ok_template');
}
}
}
/**
* Adding user to subscribers group
*
* @param UsersItem $object
*/
function AddSubscriberGroup(&$object)
{
if ( !$object->isSubscriberOnly() ) {
$fields_hash = Array (
'PortalUserId' => $object->GetID(),
'GroupId' => $this->Application->ConfigValue('User_SubscriberGroup'),
);
$this->Conn->doInsert($fields_hash, TABLE_PREFIX . 'UserGroupRelations');
}
$this->Application->emailAdmin('USER.SUBSCRIBE');
$this->Application->emailUser('USER.SUBSCRIBE', $object->GetID());
}
/**
* Removing user from subscribers group
*
* @param int $user_id
*/
function RemoveSubscriberGroup($user_id)
{
$group_id = $this->Application->ConfigValue('User_SubscriberGroup');
$sql = 'DELETE FROM ' . TABLE_PREFIX . 'UserGroupRelations
WHERE PortalUserId = ' . $user_id . ' AND GroupId = ' . $group_id;
$this->Conn->Query($sql);
$this->Application->emailAdmin('USER.UNSUBSCRIBE');
$this->Application->emailUser('USER.UNSUBSCRIBE', $user_id);
}
/**
* Validates forgot password form and sends password reset confirmation e-mail
*
* @param kEvent $event
* @return void
*/
function OnForgotPassword($event)
{
/** @var kDBItem $object */
$object = $event->getObject( Array ('form_name' => 'forgot_password') );
$object->SetFieldsFromHash($this->getSubmittedFields($event));
/** @var UsersItem $user */
$user = $this->Application->recallObject('u.tmp', null, Array ('skip_autoload' => true));
$found = $allow_reset = false;
$email_or_username = $object->GetDBField('ForgotLogin');
$is_email = strpos($email_or_username, '@') !== false;
if ( strlen($email_or_username) ) {
$user->Load($email_or_username, $is_email ? 'Email' : 'Username');
}
if ( $user->isLoaded() ) {
$min_pwd_reset_delay = $this->Application->ConfigValue('Users_AllowReset');
$found = ($user->GetDBField('Status') == STATUS_ACTIVE) && strlen($user->GetDBField('Password'));
if ( !$user->GetDBField('PwResetConfirm') ) {
// no reset made -> allow
$allow_reset = true;
}
else {
// reset made -> wait N minutes, then allow
$allow_reset = TIMENOW > $user->GetDBField('PwRequestTime') + $min_pwd_reset_delay;
}
}
if ( $found && $allow_reset ) {
$this->Application->emailUser('USER.PSWDC', $user->GetID());
$event->redirect = $this->Application->GetVar('template_success');
return;
}
if ( strlen($email_or_username) ) {
$object->SetError('ForgotLogin', $found ? 'reset_denied' : ($is_email ? 'unknown_email' : 'unknown_username'));
}
if ( !$object->ValidateField('ForgotLogin') ) {
$event->status = kEvent::erFAIL;
}
}
/**
* Updates kDBItem
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnUpdate(kEvent $event)
{
parent::OnUpdate($event);
if ( !$this->Application->isAdmin ) {
$this->setNextTemplate($event);
}
}
/**
* Updates kDBItem via AJAX.
*
* @param kEvent $event Event.
*
* @return void
*/
protected function OnUpdateAjax(kEvent $event)
{
/** @var AjaxFormHelper $ajax_form_helper */
$ajax_form_helper = $this->Application->recallObject('AjaxFormHelper');
$ajax_form_helper->transitEvent($event, 'OnUpdate');
}
/**
* Checks state against country
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnBeforeItemUpdate(kEvent $event)
{
parent::OnBeforeItemUpdate($event);
$this->beforeItemChanged($event);
/** @var kCountryStatesHelper $cs_helper */
$cs_helper = $this->Application->recallObject('CountryStatesHelper');
$cs_helper->CheckStateField($event, 'State', 'Country');
$cs_helper->PopulateStates($event, 'State', 'Country');
/** @var kDBItem $object */
$object = $event->getObject();
if ( $event->Special == 'forgot' ) {
$object->SetDBField('PwResetConfirm', '');
$object->SetDBField('PwRequestTime_date', NULL);
$object->SetDBField('PwRequestTime_time', NULL);
}
$changed_fields = array_keys($object->GetChangedFields());
if ( $changed_fields && !in_array('Modified', $changed_fields) ) {
$object->SetDBField('Modified_date', adodb_mktime());
$object->SetDBField('Modified_time', adodb_mktime());
}
if ( !$this->Application->isAdmin && in_array('Email', $changed_fields) && ($event->Special != 'email-restore') ) {
$object->SetDBField('EmailVerified', 0);
}
}
/**
* Occurs before item is changed
*
* @param kEvent $event
*/
function beforeItemChanged($event)
{
/** @var UsersItem $object */
$object = $event->getObject();
if ( !$this->Application->isAdmin && $object->getFormName() == 'registration' ) {
// sets new user's status based on config options
$status_map = Array (1 => STATUS_ACTIVE, 2 => STATUS_DISABLED, 3 => STATUS_PENDING, 4 => STATUS_PENDING);
$object->SetDBField('Status', $status_map[ $this->Application->ConfigValue('User_Allow_New') ]);
if ( $this->Application->ConfigValue('User_Password_Auto') ) {
$object->generatePassword( rand(5, 8) );
}
if ( $this->Application->ConfigValue('RegistrationCaptcha') ) {
/** @var kCaptchaHelper $captcha_helper */
$captcha_helper = $this->Application->recallObject('CaptchaHelper');
$captcha_helper->validateCode($event, false);
}
if ( $event->Name == 'OnBeforeItemUpdate' ) {
// when a subscriber-only users performs normal registration, then assign him to Member group
$this->setUserGroup($object);
}
}
}
/**
* Sets redirect template based on user status & user request contents
*
* @param kEvent $event
* @param bool $for_registration
*/
function setNextTemplate($event, $for_registration = false)
{
$event->SetRedirectParam('opener', 's');
/** @var UsersItem $object */
$object = $event->getObject();
$next_template = false;
if ( $object->GetDBField('Status') == STATUS_ACTIVE && $this->Application->GetVar('next_template') ) {
$next_template = $this->Application->GetVar('next_template');
}
elseif ( $for_registration ) {
switch ( $this->Application->ConfigValue('User_Allow_New') ) {
case 1: // Immediate
$next_template = $this->Application->GetVar('registration_confirm_template');
break;
case 3: // Upon Approval
case 4: // Email Activation
$next_template = $this->Application->GetVar('registration_confirm_pending_template');
break;
}
}
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.'UserGroupRelations
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) {
$this->Application->emailUser('USER.MEMBERSHIP.EXPIRATION.NOTICE', $record['PortalUserId']);
$this->Application->emailAdmin('USER.MEMBERSHIP.EXPIRATION.NOTICE');
$conditions[] = '(PortalUserId = '.$record['PortalUserId'].' AND GroupId = '.$record['GroupId'].')';
}
$sql = 'UPDATE '.TABLE_PREFIX.'UserGroupRelations
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.'UserGroupRelations
WHERE (MembershipExpires IS NOT NULL) AND (MembershipExpires < '.adodb_mktime().')';
$user_ids = $this->Conn->GetCol($sql);
if ($user_ids) {
foreach ($user_ids as $id) {
$this->Application->emailUser('USER.MEMBERSHIP.EXPIRED', $id);
$this->Application->emailAdmin('USER.MEMBERSHIP.EXPIRED');
}
}
$sql = 'DELETE FROM '.TABLE_PREFIX.'UserGroupRelations
WHERE (MembershipExpires IS NOT NULL) AND (MembershipExpires < '.adodb_mktime().')';
$this->Conn->Query($sql);
// remove users from groups with expired membership: end
}
/**
* Used to keep user registration form data, while showing affiliate registration form fields
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnRefreshForm($event)
{
$event->redirect = false;
$item_info = $this->Application->GetVar( $event->getPrefixSpecial(true) );
$id = key($item_info);
$field_values = $item_info[$id];
/** @var kDBItem $object */
$object = $event->getObject( Array ('skip_autoload' => true) );
$object->IgnoreValidation = true;
$object->setID($id);
$object->SetFieldsFromHash($field_values);
$event->setEventParam('form_data', $field_values);
}
/**
* Sets persistant variable
*
* @param kEvent $event
*/
function OnSetPersistantVariable($event)
{
$field = $this->Application->GetVar('field');
$value = $this->Application->GetVar('value');
$this->Application->StorePersistentVar($field, $value);
$force_tab = $this->Application->GetVar('SetTab');
if ($force_tab) {
$this->Application->StoreVar('force_tab', $force_tab);
}
}
/**
* Return user from order by special .ord
*
* @param kEvent $event
* @return int
* @access public
*/
public function getPassedID(kEvent $event)
{
switch ($event->Special) {
case 'ord':
/** @var OrdersItem $order */
$order = $this->Application->recallObject('ord');
return $order->GetDBField('PortalUserId');
break;
case 'profile':
$id = $this->Application->GetVar('user_id');
if ( $id ) {
$event->setEventParam(kEvent::FLAG_ID_FROM_REQUEST, true);
return $id;
}
// If none user_id given use current user id.
return $this->Application->RecallVar('user_id');
break;
case 'forgot':
/** @var UserHelper $user_helper */
$user_helper = $this->Application->recallObject('UserHelper');
$id = $user_helper->validateUserCode($this->Application->GetVar('user_key'), 'forgot_password');
if ( is_numeric($id) ) {
return $id;
}
break;
}
if ( preg_match('/^(login|register|recommend|subscribe|forgot)/', $event->Special) ) {
// this way we can have 2+ objects stating with same special, e.g. "u.login-sidebox" and "u.login-main"
return USER_GUEST;
}
elseif ( preg_match('/^(update|delete)/', $event->Special) ) {
// This way we can have 2+ objects stating with same special, e.g. "u.update-sidebox" and "u.update-profile".
return $this->Application->RecallVar('user_id');
}
return parent::getPassedID($event);
}
/**
* Allows to change root password
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnUpdatePassword($event)
{
$items_info = $this->Application->GetVar($event->getPrefixSpecial(true));
if ( !$items_info ) {
return;
}
$id = key($items_info);
$field_values = $items_info[$id];
$user_id = $this->Application->RecallVar('user_id');
if ( $id == $user_id && ($user_id > 0 || $user_id == USER_ROOT) ) {
/** @var kDBItem $user_dummy */
$user_dummy = $this->Application->recallObject($event->Prefix . '.-item', null, Array ('skip_autoload' => true));
$user_dummy->Load($id);
$status_field = $user_dummy->getStatusField();
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 ;
}
}
if ( $user_id == USER_ROOT ) {
/** @var UsersItem $object */
$object = $event->getObject(Array ('skip_autoload' => true));
// this is internal hack to allow root/root passwords for dev
if ( $this->Application->isDebugMode() && $field_values['RootPassword'] == 'root' ) {
$object->SetFieldOption('RootPassword', 'min_length', 4);
}
$this->RemoveRequiredFields($object);
$object->SetDBField('RootPassword', $this->Application->ConfigValue('RootPass'));
$object->setID(-1);
$object->SetFieldsFromHash($field_values);
$event->setEventParam('form_data', $field_values);
if ( $object->Validate() ) {
// 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 = kEvent::erFAIL;
$event->redirect = false;
return ;
}
}
else {
/** @var kDBItem $object */
$object = $event->getObject();
$object->SetFieldsFromHash($field_values);
$event->setEventParam('form_data', $field_values);
if ( !$object->Update() ) {
$event->status = kEvent::erFAIL;
$event->redirect = false;
}
}
$event->SetRedirectParam('opener', 'u');
}
/**
* Resets grid settings, remembered in each user record
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnMassResetSettings($event)
{
if ( $this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1) ) {
$event->status = kEvent::erFAIL;
return;
}
$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 . 'UserPersistentSessionData 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
* @access protected
*/
protected function checkItemStatus(kEvent $event)
{
/** @var kDBItem $object */
$object = $event->getObject();
if ( !$object->isLoaded() ) {
return true;
}
$virtual_users = Array (USER_ROOT, USER_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
* @return void
* @access protected
*/
protected function OnAfterItemUpdate(kEvent $event)
{
parent::OnAfterItemUpdate($event);
$this->afterItemChanged($event);
/** @var UsersItem $object */
$object = $event->getObject();
if ( !$this->Application->isAdmin && ($event->Special != 'email-restore') ) {
$this->sendEmailChangeEvent($event);
}
if ( !$this->Application->isAdmin || $object->IsTempTable() ) {
return;
}
$this->sendStatusChangeEvent($object->GetID(), $object->GetOriginalField('Status'), $object->GetDBField('Status'));
}
/**
* Occurs, after item is changed
*
* @param kEvent $event
*/
protected function afterItemChanged($event)
{
$this->saveUserImages($event);
/** @var UsersItem $object */
$object = $event->getObject();
if ( $object->GetDBField('EmailPassword') && $object->GetDBField('Password_plain') ) {
$email_passwords = $this->Application->RecallVar('email_passwords');
$email_passwords = $email_passwords ? unserialize($email_passwords) : Array ();
$email_passwords[ $object->GetID() ] = $object->GetDBField('Password_plain');
$this->Application->StoreVar('email_passwords', serialize($email_passwords));
}
// update user subscription status (via my profile or new user registration)
if ( !$this->Application->isAdmin && !$object->isSubscriberOnly() ) {
if ( $object->GetDBField('SubscribeToMailing') && !$object->isSubscribed() ) {
$this->AddSubscriberGroup($object);
}
elseif ( !$object->GetDBField('SubscribeToMailing') && $object->isSubscribed() ) {
$this->RemoveSubscriberGroup( $object->GetID() );
}
}
}
/**
* Stores user's original Status before overwriting with data from temp table
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnBeforeDeleteFromLive(kEvent $event)
{
parent::OnBeforeDeleteFromLive($event);
$user_id = $event->getEventParam('id');
$user_status = $this->Application->GetVar('user_status', Array ());
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
* @return void
* @access protected
*/
protected function OnAfterCopyToLive(kEvent $event)
{
parent::OnAfterCopyToLive($event);
$temp_id = $event->getEventParam('temp_id');
$email_passwords = $this->Application->RecallVar('email_passwords');
if ( $email_passwords ) {
$email_passwords = unserialize($email_passwords);
if ( isset($email_passwords[$temp_id]) ) {
/** @var kDBItem $object */
$object = $event->getObject();
$object->SwitchToLive();
$object->Load( $event->getEventParam('id') );
$object->SetField('Password', $email_passwords[$temp_id]);
$object->SetField('VerifyPassword', $email_passwords[$temp_id]);
$this->Application->emailUser($temp_id > 0 ? 'USER.NEW.PASSWORD': 'USER.ADD.BYADMIN', $object->GetID());
unset($email_passwords[$temp_id]);
$this->Application->StoreVar('email_passwords', serialize($email_passwords));
}
}
if ( $temp_id > 0 ) {
// only send status change e-mail on user update
$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->emailUser($email_event, $user_id);
$this->Application->emailAdmin($email_event);
}
// deletes sessions from users, that are no longer active
if (($prev_status != $new_status) && ($new_status != STATUS_ACTIVE)) {
- $sql = 'SELECT SessionKey
+ $sql = 'SELECT SessionId
FROM ' . TABLE_PREFIX . 'UserSessions
WHERE PortalUserId = ' . $user_id;
$session_ids = $this->Conn->GetCol($sql);
$this->Application->Session->DeleteSessions($session_ids);
}
}
/**
* Sends restore/validation email event on user email change
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function sendEmailChangeEvent(kEvent $event)
{
/** @var UsersItem $object */
$object = $event->getObject();
$new_email = $object->GetDBField('Email');
$prev_email = $object->GetOriginalField('Email');
if ( !$new_email || ($prev_email == $new_email) ) {
return;
}
$prev_emails = $object->GetDBField('PrevEmails');
$prev_emails = $prev_emails ? unserialize($prev_emails) : Array ();
$fields_hash = Array (
'PrevEmails' => serialize($prev_emails),
'EmailVerified' => 0,
);
$user_id = $object->GetID();
if ( $prev_email ) {
$hash = md5(TIMENOW + $user_id);
$prev_emails[$hash] = $prev_email;
$fields_hash['PrevEmails'] = serialize($prev_emails);
$send_params = Array (
'hash' => $hash,
'to_email' => $prev_email,
'to_name' => trim($object->GetDBField('FirstName') . ' ' . $object->GetDBField('LastName')),
);
$this->Application->emailUser('USER.EMAIL.CHANGE.UNDO', null, $send_params);
}
if ( $new_email ) {
$this->Application->emailUser('USER.EMAIL.CHANGE.VERIFY', $user_id);
}
// direct DB update, since USER.EMAIL.CHANGE.VERIFY puts verification code in user record, that we don't want to loose
$this->Conn->doUpdate($fields_hash, $object->TableName, 'PortalUserId = ' . $user_id);
}
/**
* OnAfterConfigRead for users
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnAfterConfigRead(kEvent $event)
{
parent::OnAfterConfigRead($event);
$forms = $this->Application->getUnitOption($event->Prefix, 'Forms');
$form_fields =& $forms['default']['Fields'];
// 1. arrange user registration countries
/** @var SiteHelper $site_helper */
$site_helper = $this->Application->recallObject('SiteHelper');
$first_country = $site_helper->getDefaultCountry('', false);
if ($first_country === false) {
$first_country = $this->Application->ConfigValue('User_Default_Registration_Country');
}
if ($first_country) {
// update user country dropdown sql
$form_fields['Country']['options_sql'] = preg_replace('/ORDER BY (.*)/', 'ORDER BY IF (CountryStateId = '.$first_country.', 1, 0) DESC, \\1', $form_fields['Country']['options_sql']);
}
// 2. set default user registration group
$form_fields['PrimaryGroupId']['default'] = $this->Application->ConfigValue('User_NewGroup');
// 3. allow avatar upload on Front-End
/** @var FileHelper $file_helper */
$file_helper = $this->Application->recallObject('FileHelper');
$file_helper->createItemFiles($event->Prefix, true); // create image fields
if ($this->Application->isAdminUser) {
// 4. when in administrative console, then create all users with Active status
$form_fields['Status']['default'] = STATUS_ACTIVE;
// 5. remove groups tab on editing forms when AdvancedUserManagement config variable not set
if (!$this->Application->ConfigValue('AdvancedUserManagement')) {
$edit_tab_presets = $this->Application->getUnitOption($event->Prefix, 'EditTabPresets');
foreach ($edit_tab_presets as $preset_name => $preset_tabs) {
if (array_key_exists('groups', $preset_tabs)) {
unset($edit_tab_presets[$preset_name]['groups']);
if (count($edit_tab_presets[$preset_name]) == 1) {
// only 1 tab left -> remove it too
$edit_tab_presets[$preset_name] = Array ();
}
}
}
$this->Application->setUnitOption($event->Prefix, 'EditTabPresets', $edit_tab_presets);
}
}
if ( $this->Application->ConfigValue('RegistrationUsernameRequired') ) {
// Username becomes required only, when it's used in registration process
$max_username = $this->Application->ConfigValue('MaxUserName');
$form_fields['Username']['required'] = 1;
$form_fields['Username']['min_len'] = $this->Application->ConfigValue('Min_UserName');
$form_fields['Username']['max_len'] = $max_username ? $max_username : 255;
}
$this->Application->setUnitOption($event->Prefix, 'Forms', $forms);
}
/**
* OnMassCloneUsers
*
* @param kEvent $event
*/
function OnMassCloneUsers($event)
{
if ($this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1)) {
$event->status = kEvent::erFAIL;
return;
}
/** @var kTempTablesHandler $temp_handler */
$temp_handler = $this->Application->recallObject($event->Prefix.'_TempHandler', 'kTempTablesHandler');
$ids = $this->StoreSelectedIDs($event);
$temp_handler->CloneItems($event->Prefix, '', $ids);
$this->clearSelectedIDs($event);
}
/**
* When cloning users, reset password (set random)
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnBeforeClone(kEvent $event)
{
parent::OnBeforeClone($event);
/** @var UsersItem $object */
$object = $event->getObject();
$object->generatePassword();
$object->SetDBField('ResourceId', 0); // this will reset it
// change email because it should be unique
$object->NameCopy(Array (), $object->GetID(), 'Email', 'copy%1$s.%2$s');
}
/**
* Saves selected ids to session
*
* @param kEvent $event
*/
function OnSaveSelected($event)
{
$this->StoreSelectedIDs($event);
// remove current ID, otherwise group selector will use it in filters
$this->Application->DeleteVar($event->getPrefixSpecial(true) . '_id');
}
/**
* Sets primary group of selected users
*
* @param kEvent $event
*/
function OnProcessSelected($event)
{
$event->SetRedirectParam('opener', 'u');
$user_ids = $this->getSelectedIDs($event, true);
$this->clearSelectedIDs($event);
$dst_field = $this->Application->RecallVar('dst_field');
if ( $dst_field != 'PrimaryGroupId' ) {
return;
}
$group_ids = array_keys($this->Application->GetVar('g'));
$primary_group_id = $group_ids ? array_shift($group_ids) : false;
if ( !$user_ids || !$primary_group_id ) {
return;
}
$table_name = $this->Application->getUnitOption('ug', 'TableName');
// 1. mark group as primary
$sql = 'UPDATE ' . TABLE_PREFIX . 'Users
SET PrimaryGroupId = ' . $primary_group_id . '
WHERE PortalUserId IN (' . implode(',', $user_ids) . ')';
$this->Conn->Query($sql);
foreach ( $user_ids as $user_id ) {
$this->Application->incrementCacheSerial('u', $user_id);
}
$this->Application->incrementCacheSerial('u');
$sql = 'SELECT PortalUserId
FROM ' . $table_name . '
WHERE (GroupId = ' . $primary_group_id . ') AND (PortalUserId IN (' . implode(',', $user_ids) . '))';
$existing_members = $this->Conn->GetCol($sql);
// 2. add new members to a group
$new_members = array_diff($user_ids, $existing_members);
foreach ($new_members as $user_id) {
$fields_hash = Array (
'GroupId' => $primary_group_id,
'PortalUserId' => $user_id,
);
$this->Conn->doInsert($fields_hash, $table_name);
}
}
/**
* Loads user images
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnAfterItemLoad(kEvent $event)
{
parent::OnAfterItemLoad($event);
// linking existing images for item with virtual fields
/** @var ImageHelper $image_helper */
$image_helper = $this->Application->recallObject('ImageHelper');
/** @var UsersItem $object */
$object = $event->getObject();
$image_helper->LoadItemImages($object);
/** @var kCountryStatesHelper $cs_helper */
$cs_helper = $this->Application->recallObject('CountryStatesHelper');
$cs_helper->PopulateStates($event, 'State', 'Country');
// get user subscription status
$object->SetDBField('SubscribeToMailing', $object->isSubscribed() ? 1 : 0);
if ( !$this->Application->isAdmin ) {
$object->SetFieldOption('FrontLanguage', 'options', $this->getEnabledLanguages());
}
}
/**
* Returns list of enabled languages with their names
*
* @return Array
* @access protected
*/
protected function getEnabledLanguages()
{
$cache_key = 'user_languages[%LangSerial%]';
$ret = $this->Application->getCache($cache_key);
if ( $ret === false ) {
/** @var kDBList $languages */
$languages = $this->Application->recallObject('lang.enabled', 'lang_List');
$ret = Array ();
foreach ($languages as $language_info) {
$ret[$languages->GetID()] = $language_info['LocalName'];
}
$this->Application->setCache($cache_key, $ret);
}
return $ret;
}
/**
* Save user images
*
* @param kEvent $event
*/
function saveUserImages($event)
{
if (!$this->Application->isAdmin) {
/** @var ImageHelper $image_helper */
$image_helper = $this->Application->recallObject('ImageHelper');
/** @var kDBItem $object */
$object = $event->getObject();
// process image upload in virtual fields
$image_helper->SaveItemImages($object);
}
}
/**
* Makes password required for new users
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnPreCreate(kEvent $event)
{
parent::OnPreCreate($event);
if ( $event->status != kEvent::erSUCCESS ) {
return;
}
/** @var kDBItem $object */
$object = $event->getObject();
$user_type = $this->Application->GetVar('user_type');
if ( $user_type ) {
$object->SetDBField('UserType', $user_type);
if ( $user_type == UserType::ADMIN ) {
$object->SetDBField('PrimaryGroupId', $this->Application->ConfigValue('User_AdminGroup'));
}
}
if ( $this->Application->ConfigValue('User_Password_Auto') ) {
$object->SetDBField('EmailPassword', 1);
}
$this->_makePasswordRequired($event);
}
/**
* Makes password required for new users
*
* @param kEvent $event
*/
function _makePasswordRequired($event)
{
/** @var kDBItem $object */
$object = $event->getObject();
$required_fields = Array ('Password', 'Password_plain', 'VerifyPassword', 'VerifyPassword_plain');
$object->setRequired($required_fields);
}
/**
* Load item if id is available
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function LoadItem(kEvent $event)
{
$id = $this->getPassedID($event);
if ( $id < 0 ) {
// when root, guest and so on
/** @var kDBItem $object */
$object = $event->getObject();
$object->Clear($id);
return;
}
parent::LoadItem($event);
}
/**
* Occurs just after login (for hooking)
*
* @param kEvent $event
*/
function OnAfterLogin($event)
{
if ( is_object($event->MasterEvent) && !$this->Application->isAdmin ) {
$event->MasterEvent->SetRedirectParam('login', 1);
}
}
/**
* Occurs just before logout (for hooking)
*
* @param kEvent $event
*/
function OnBeforeLogout($event)
{
if ( is_object($event->MasterEvent) && !$this->Application->isAdmin ) {
$event->MasterEvent->SetRedirectParam('logout', 1);
}
}
/**
* Generates password
*
* @param kEvent $event
*/
function OnGeneratePassword($event)
{
$event->status = kEvent::erSTOP;
if ( $this->Application->isAdminUser ) {
echo kUtil::generatePassword();
}
}
/**
* Changes user's password and logges him in
*
* @param kEvent $event
*/
function OnResetLostPassword($event)
{
/** @var kDBItem $object */
$object = $event->getObject();
$event->CallSubEvent('OnUpdate');
if ( $event->status == kEvent::erSUCCESS ) {
/** @var UserHelper $user_helper */
$user_helper = $this->Application->recallObject('UserHelper');
$user =& $user_helper->getUserObject();
$user->Load( $object->GetID() );
if ( $user_helper->checkLoginPermission() ) {
$user_helper->loginUserById( $user->GetID() );
}
}
}
/**
* Generates new Root password and email it
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnResetRootPassword($event)
{
/** @var kPasswordFormatter $password_formatter */
$password_formatter = $this->Application->recallObject('kPasswordFormatter');
$new_root_password = kUtil::generatePassword();
$this->Application->SetConfigValue('RootPass', $password_formatter->hashPassword($new_root_password));
$this->Application->emailAdmin('ROOT.RESET.PASSWORD', null, Array ('password' => $new_root_password));
$event->SetRedirectParam('reset', 1);
$event->SetRedirectParam('pass', 'm');
}
/**
* Perform login of user, selected in Admin Console, on Front-End in a separate window
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnLoginAs(kEvent $event)
{
/** @var UserHelper $user_helper */
$user_helper = $this->Application->recallObject('UserHelper');
$user =& $user_helper->getUserObject();
$user->Load( $this->Application->GetVar('user_id') );
if ( !$user->isLoaded() ) {
return ;
}
if ( $user_helper->checkLoginPermission() ) {
$user_helper->loginUserById( $user->GetID() );
}
}
}
Index: branches/5.2.x/core/units/helpers/curl_helper.php
===================================================================
--- branches/5.2.x/core/units/helpers/curl_helper.php (revision 16796)
+++ branches/5.2.x/core/units/helpers/curl_helper.php (revision 16797)
@@ -1,634 +1,634 @@
<?php
/**
* @version $Id$
* @package In-Portal
* @copyright Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license GNU/GPL
* In-Portal is Open Source software.
* This means that this software may have been modified pursuant
* the GNU General Public License, and as distributed it includes
* or is derivative of works licensed under the GNU General Public License
* or other free or open source software licenses.
* See http://www.in-portal.org/license for copyright notices and details.
*/
use Composer\CaBundle\CaBundle;
defined('FULL_PATH') or die('restricted access!');
class kCurlHelper extends kHelper {
const REQUEST_METHOD_GET = 1;
const REQUEST_METHOD_POST = 2;
/**
* ID of database record of currently active curl request
*
* @var int
* @access protected
*/
protected $logId = 0;
/**
* Connection to host
*
* @var resource
* @access protected
*/
protected $connectionID = NULL;
/**
* Response waiting timeout in seconds
*
* @var integer
*/
public $timeout;
/**
* Follow to url, if redirect received instead of document (only works when open_basedir and safe mode is off)
*
* @var boolean
*/
public $followLocation;
/**
* Last response received by Curl
*
* @var string
* @access public
*/
public $lastResponse = '';
/**
* Last error code
*
* @var int
* @access public
*/
public $lastErrorCode = 0;
/**
* Last error message
*
* @var string
* @access public
*/
public $lastErrorMsg = '';
/**
* Most recent HTTP response code received
*
* @var int
* @access public
*/
public $lastHTTPCode = 0;
/**
* Count of intermediate redirects performed to get actual content
*
* @var int
* @access protected
*/
protected $lastRedirectCount = 0;
/**
* Default request method
*
* @var integer
*/
protected $requestMethod;
/**
* Data to be sent using curl
*
* @var string
*/
protected $requestData;
/**
* Request headers (associative array)
*
* @var Array
*/
protected $requestHeaders;
/**
* Response headers
*
* @var Array
*/
protected $responseHeaders;
/**
* CURL options
*
* @var Array
*/
protected $options;
/**
* Indicates debug mode status
*
* @var boolean
*/
public $debugMode;
/**
* SSL Certificates file.
*
* @var string
*/
protected $sslCertificatesFile;
/**
* Verify SSL certificates.
*
* @var boolean
*/
protected $verifySslCertificate;
/**
* Creates an instance of kCurlHelper class
*/
public function __construct()
{
parent::__construct();
$this->debugMode = kUtil::constOn('DBG_CURL');
$this->_resetSettings();
}
/**
* Reset connection settings (not results) after connection was closed
*
* @access protected
*/
protected function _resetSettings()
{
$this->timeout = 90;
$this->followLocation = false;
$this->requestMethod = self::REQUEST_METHOD_GET;
$this->requestData = '';
$this->requestHeaders = Array ();
$this->responseHeaders = Array ();
$this->options = Array ();
$this->sslCertificatesFile = CaBundle::getSystemCaRootBundlePath();
$this->verifySslCertificate = true;
}
/**
* Resets information in last* properties.
*
* @return void
*/
protected function resetLastInfo()
{
$this->lastErrorCode = 0;
$this->lastErrorMsg = '';
$this->lastHTTPCode = 0;
$this->lastRedirectCount = 0;
}
/**
* Sets CURL options (adds to options set before)
*
* @param Array $options_hash
* @access public
*/
public function setOptions($options_hash)
{
$this->options = kUtil::array_merge_recursive($this->options, $options_hash);
}
/**
* Combines user-defined and default options before setting them to CURL
*
* @access protected
*/
protected function prepareOptions()
{
$default_options = Array (
// customizable options
CURLOPT_TIMEOUT => $this->timeout,
// hardcoded options
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_REFERER => PROTOCOL.SERVER_NAME,
CURLOPT_MAXREDIRS => 5,
// Prevents CURL from adding "Expect: 100-continue" header for POST requests.
CURLOPT_HTTPHEADER => Array ('Expect:'),
);
if ( $this->verifySslCertificate ) {
$default_options[CURLOPT_SSL_VERIFYHOST] = 2;
$default_options[CURLOPT_SSL_VERIFYPEER] = true;
$default_options[CURLOPT_CAINFO] = $this->sslCertificatesFile;
}
else {
$default_options[CURLOPT_SSL_VERIFYHOST] = false;
$default_options[CURLOPT_SSL_VERIFYPEER] = false;
}
if ( isset($_SERVER['HTTP_USER_AGENT']) ) {
$default_options[CURLOPT_USERAGENT] = $_SERVER['HTTP_USER_AGENT'];
}
if ($this->requestHeaders) {
$default_options[CURLOPT_HTTPHEADER] = $this->prepareHeaders();
}
// if we have post data, then POST else use GET method instead
if ($this->requestMethod == self::REQUEST_METHOD_POST) {
$default_options[CURLOPT_POST] = 1;
$default_options[CURLOPT_POSTFIELDS] = $this->requestData;
}
$default_options[CURLOPT_HEADERFUNCTION] = array(&$this, 'ParseHeader');
$user_options = $this->options; // backup options, that user set directly
$this->setOptions($default_options);
$this->setOptions($user_options);
$this->applyOptions();
}
/**
* Sets prepared options to CURL
*
* @access protected
*/
protected function applyOptions()
{
foreach ($this->options as $option_name => $option_value) {
curl_setopt($this->connectionID, $option_name, $option_value);
}
}
/**
* Parses headers from CURL request
*
* @param resource $ch
* @param string $header
* @return int
* @access protected
*/
protected function ParseHeader(&$ch, $header)
{
$trimmed_header = rtrim($header);
if ( $trimmed_header ) {
$this->responseHeaders[] = $trimmed_header;
}
return strlen($header);
}
/**
* Sets request data for next query
*
* @param mixed $data Array or string
*/
public function SetRequestData($data)
{
if ( is_array($data) ) {
$data = http_build_query($data);
}
$this->requestData = $data;
}
/**
* Sets request data for next query and switches request method to POST
*
* @param mixed $data Array or string
* @access public
*/
public function SetPostData($data)
{
$this->requestMethod = self::REQUEST_METHOD_POST;
$this->SetRequestData($data);
}
/**
* Sets request method to be used in next request
*
* @param int $request_method
*
* @throws InvalidArgumentException When invalid request method given.
*/
public function SetRequestMethod($request_method)
{
if ($request_method != self::REQUEST_METHOD_GET && $request_method != self::REQUEST_METHOD_POST) {
throw new InvalidArgumentException('Method "' . __METHOD__ . '": Invalid $request_method parameter value');
return ;
}
$this->requestMethod = $request_method;
}
/**
* Sets headers to be sent along with next query
*
* @param Array $headers
* @access public
*/
public function SetHeaders($headers)
{
$this->requestHeaders = array_merge($this->requestHeaders, $headers);
}
/**
* Returns compiled header to be used by curl
*
* @return Array
* @access protected
*/
protected function prepareHeaders()
{
$ret = Array ();
foreach ($this->requestHeaders as $header_name => $header_value) {
$ret[] = is_numeric($header_name) ? $header_value : $header_name . ': ' . $header_value;
}
return $ret;
}
/**
* Disables SSL certificate validation.
*
* @return void
*/
public function disableSslCertificateVerification()
{
$this->verifySslCertificate = false;
}
/**
* Enable SSL certificate validation.
*
* @param string|null $certificates_file Certificates file.
*
* @return void
* @throws RuntimeException When given certificates file doesn't exist on disk.
*/
public function enableSslCertificateVerification($certificates_file = null)
{
$this->verifySslCertificate = true;
if ( $certificates_file !== null ) {
if ( !file_exists($certificates_file) ) {
throw new RuntimeException('The "' . $certificates_file . '" file does not exist.');
}
$this->sslCertificatesFile = $certificates_file;
}
}
/**
* Performs CURL request and returns it's result
*
* @param string $url
* @param bool $close_connection
* @param bool $log_status
* @param string $log_message
* @return string
* @access public
*/
public function Send($url, $close_connection = true, $log_status = NULL, $log_message = '')
{
if ( isset($log_status) ) {
// override debug mode setting
$this->debugMode = $log_status;
}
$request_url = $url;
if ( $this->requestMethod == self::REQUEST_METHOD_GET && $this->requestData ) {
$request_url .= (strpos($request_url, '?') !== false ? '&' : '?') . $this->requestData;
}
$this->connectionID = curl_init($request_url);
if ( $this->debugMode ) {
// collect page data
$page_data = Array ();
if ( $_GET ) {
$page_data[] = '_GET:' . "\n" . print_r($_GET, true);
}
if ( $_POST ) {
$page_data[] = '_POST:' . "\n" . print_r($_POST, true);
}
if ( $_COOKIE ) {
$page_data[] = '_COOKIE:' . "\n" . print_r($_COOKIE, true);
}
// create log record
$fields_hash = Array (
'Message' => $log_message,
'PageUrl' => $_SERVER['REQUEST_URI'],
'RequestUrl' => $url,
'PortalUserId' => $this->Application->RecallVar('user_id'),
- 'SessionKey' => $this->Application->GetSID(),
+ 'SessionKey' => $this->Application->GetSID(Session::PURPOSE_STORAGE),
'IsAdmin' => $this->Application->isAdminUser ? 1 : 0,
'PageData' => implode("\n", $page_data),
'RequestData' => $this->requestData,
'RequestDate' => adodb_mktime(),
);
$this->Conn->doInsert($fields_hash, TABLE_PREFIX . 'CurlLog');
$this->logId = $this->Conn->getInsertID();
}
$this->prepareOptions();
$this->lastResponse = $this->_sendRequest();
$this->Finalize($close_connection);
return $this->lastResponse;
}
/**
* Reads data from remote url
*
* @return string
* @access protected
*/
protected function _sendRequest()
{
$this->resetLastInfo();
curl_setopt($this->connectionID, CURLOPT_RETURNTRANSFER, true);
if ( $this->followLocation ) {
if ( $this->followLocationLimited() ) {
return $this->_followLocationManually();
}
else {
// no restrictions - let curl do automatic redirects
curl_setopt($this->connectionID, CURLOPT_FOLLOWLOCATION, true);
}
}
return curl_exec($this->connectionID);
}
/**
* Fixes curl inability to automatically follow location when safe_mode/open_basedir restriction in effect
*
* @return string
* @access protected
*/
protected function _followLocationManually()
{
curl_setopt($this->connectionID, CURLOPT_HEADER, true);
$data = curl_exec($this->connectionID);
$http_code = $this->getInfo(CURLINFO_HTTP_CODE);
if ( $http_code == 301 || $http_code == 302 ) {
// safe more or open_basedir restriction - do redirects manually
list ($header) = explode("\r\n\r\n", $data, 2);
preg_match('/(Location:|URI:)(.*?)\n/', $header, $regs);
$url = trim(array_pop($regs));
$url_parsed = parse_url($url);
if ( $this->lastRedirectCount == $this->options[CURLOPT_MAXREDIRS] ) {
return $this->setError(CURLE_TOO_MANY_REDIRECTS, 'Maximum (' . $this->options[CURLOPT_MAXREDIRS] . ') redirects followed');
}
if ( isset($url_parsed) ) {
curl_setopt($this->connectionID, CURLOPT_URL, $url);
$this->lastRedirectCount++;
return $this->_followLocationManually();
}
}
list(, $body) = explode("\r\n\r\n", $data, 2);
return $body;
}
/**
* Sets error manually.
*
* @param integer $code Code.
* @param string $message Message.
*
* @return boolean
*/
protected function setError($code, $message)
{
$this->lastErrorCode = $code;
$this->lastErrorMsg = $message;
return false;
}
/**
* Returns various info about request made
*
* @param int $info_type
* @return mixed
*
* @see http://www.php.net/manual/ru/function.curl-getinfo.php
* @access public
*/
public function getInfo($info_type)
{
if ( $info_type == CURLINFO_REDIRECT_COUNT && $this->followLocationLimited() ) {
return $this->lastRedirectCount;
}
return curl_getinfo($this->connectionID, $info_type);
}
/**
* Returns response headers.
*
* @return array
*/
public function getResponseHeaders()
{
return $this->responseHeaders;
}
/**
* Detects, that follow location can't be done automatically by curl due safe_mode/open_basedir restrictions
*
* @return bool
* @access protected
*/
protected function followLocationLimited()
{
return (defined('SAFE_MODE') && SAFE_MODE) || ini_get('open_basedir');
}
/**
* Finalizes curl request and saves some data from curl before closing connection
*
* @param bool $close_connection
* @return void
* @access public
*/
public function Finalize($close_connection = true)
{
if ( $this->lastErrorCode == 0 ) {
// error not set manually -> get it from curl
$this->lastErrorCode = curl_errno($this->connectionID);
$this->lastErrorMsg = curl_error($this->connectionID);
}
$this->lastHTTPCode = $this->getInfo(CURLINFO_HTTP_CODE);
if ( $close_connection ) {
$this->CloseConnection();
}
}
/**
* Closes connection to server
*
* @access public
*/
public function CloseConnection()
{
curl_close($this->connectionID);
if ( $this->debugMode ) {
$fields_hash = Array (
'ResponseData' => $this->lastResponse,
'ResponseDate' => adodb_mktime(),
'ResponseHttpCode' => $this->lastHTTPCode,
'CurlError' => $this->lastErrorCode != 0 ? '#' . $this->lastErrorCode . ' (' . $this->lastErrorMsg . ')' : '',
);
$this->Conn->doUpdate($fields_hash, TABLE_PREFIX . 'CurlLog', 'LogId = ' . $this->logId);
}
// restore debug mode setting
$this->debugMode = kUtil::constOn('DBG_CURL');
$this->_resetSettings();
}
/**
* Checks, that last curl request was successful
*
* @return bool
* @access public
*/
public function isGoodResponseCode()
{
if ( $this->lastErrorCode != 0 ) {
return false;
}
return ($this->lastHTTPCode == 200) || ($this->lastHTTPCode >= 300 && $this->lastHTTPCode < 310);
}
}
Index: branches/5.2.x/core/units/helpers/search_helper.php
===================================================================
--- branches/5.2.x/core/units/helpers/search_helper.php (revision 16796)
+++ branches/5.2.x/core/units/helpers/search_helper.php (revision 16797)
@@ -1,861 +1,881 @@
<?php
/**
* @version $Id$
* @package In-Portal
* @copyright Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license GNU/GPL
* In-Portal is Open Source software.
* This means that this software may have been modified pursuant
* the GNU General Public License, and as distributed it includes
* or is derivative of works licensed under the GNU General Public License
* or other free or open source software licenses.
* See http://www.in-portal.org/license for copyright notices and details.
*/
defined('FULL_PATH') or die('restricted access!');
class kSearchHelper extends kHelper {
/**
* Perform Exact Search flag
*
* @var bool
* @access protected
*/
protected $_performExactSearch = true;
public function __construct()
{
parent::__construct();
$this->_performExactSearch = $this->Application->ConfigValue('PerformExactSearch');
}
/**
* Splits search phrase into keyword using quotes,plus and minus sings and spaces as split criteria
*
* @param string $keyword
* @return Array
* @access public
*/
public function splitKeyword($keyword)
{
if ( $this->Application->ConfigValue('CheckStopWords') ) {
$keyword_after_remove = $this->_removeStopWords($keyword);
if ( $keyword_after_remove ) {
// allow to search through stop word grid
$keyword = $keyword_after_remove;
}
}
$final = Array ();
$quotes_re = '/([+\-]?)"(.*?)"/';
$no_quotes_re = '/([+\-]?)([^ ]+)/';
preg_match_all($quotes_re, $keyword, $res);
foreach ($res[2] as $index => $kw) {
$final[$kw] = $res[1][$index];
}
$keyword = preg_replace($quotes_re, '', $keyword);
preg_match_all($no_quotes_re, $keyword, $res);
foreach ($res[2] as $index => $kw) {
$final[$kw] = $res[1][$index];
}
if ( $this->_performExactSearch ) {
foreach ($final AS $kw => $plus_minus) {
if ( !$plus_minus ) {
$final[$kw] = '+';
}
}
}
return $final;
}
function getPositiveKeywords($keyword)
{
$keywords = $this->splitKeyword($keyword);
$ret = Array();
foreach ($keywords as $keyword => $sign) {
if ($sign == '+' || $sign == '') {
$ret[] = $keyword;
}
}
return $ret;
}
/**
* Replace wildcards to match MySQL
*
* @param string $keyword
* @return string
*/
function transformWildcards($keyword)
{
return str_replace(Array ('%', '_', '*', '?') , Array ('\%', '\_', '%', '_'), $keyword);
}
function buildWhereClause($keyword, $fields)
{
$keywords = $this->splitKeyword( $this->transformWildcards($keyword) );
$normal_conditions = $plus_conditions = $minus_conditions = Array();
foreach ($keywords as $keyword => $sign) {
$keyword = $this->Conn->escape($keyword);
switch ($sign) {
case '+':
$plus_conditions[] = implode(" LIKE '%" . $keyword . "%' OR ", $fields) . " LIKE '%" . $keyword . "%'";
break;
case '-':
$condition = Array ();
foreach ($fields as $field) {
$condition[] = $field . " NOT LIKE '%" . $keyword . "%' OR " . $field . ' IS NULL';
}
$minus_conditions[] = '(' . implode(') AND (', $condition) . ')';
break;
case '':
$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 = $object->isVirtualField($field_name) ? 'having' : 'where';
$field_options = $object->GetFieldOptions($field_name);
$table_name = '';
$field_type = isset($field_options['type']) ? $field_options['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
+ // Replace wid inside table name to WID_MARK constant value.
+ $is_temp_table = preg_match(
+ '/(.*)' . TABLE_PREFIX . 'ses_[\d]+(_[\d]+){0,1}_edit_(.*)/',
+ $table_name,
+ $regs
+ );
+
+ // The EDIT_MARK will be replaced with sid[_main_wid] in AddFilters.
+ if ( $is_temp_table ) {
+ $table_name = $regs[1] . TABLE_PREFIX . 'ses_' . EDIT_MARK . '_edit_' . $regs[3];
}
return Array ($field_name, $field_type, $table_name, $sql_filter_type);
}
/**
* Removes stop words from keyword
*
* @param string $keyword
* @return string
*/
function _removeStopWords($keyword)
{
static $stop_words = Array ();
if (!$stop_words) {
$sql = 'SELECT StopWord
FROM ' . $this->Application->getUnitOption('stop-word', 'TableName') . '
ORDER BY LENGTH(StopWord) DESC, StopWord ASC';
$stop_words = $this->Conn->GetCol($sql);
foreach ($stop_words as $index => $stop_word) {
$stop_words[$index] = '/(^| )' . preg_quote($stop_word, '/') . '( |$)/';
}
}
$keyword = preg_replace($stop_words, ' ', $keyword);
return trim( preg_replace('/[ ]+/', ' ', $keyword) );
}
/**
* Performs new search on a given grid
*
* @param kEvent $event
* @return void
* @access public
*/
public function performSearch($event)
{
/** @var kDBItem $object */
$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);
$custom_filter = $this->processCustomFilters($event);
if ( !$search_keyword && $custom_filter === false ) {
$this->resetSearch($event);
return ;
}
if ( $search_keyword ) {
$this->processAutomaticFilters($event, $search_keyword, $custom_filter);
}
}
/**
* Creates filtering sql clauses based on given search restrictions
*
* @param kEvent $event
* @param string $search_keyword
* @param Array $custom_filter
* @return void
*/
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();
/** @var kDBList $object */
$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 $field_name
* @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)
{
if ($object->isVirtualField($field_name) && !$object->isCalculatedField($field_name)) {
// Virtual field, that is shown in grid, but it doesn't have corresponding calculated field.
// Happens, when field value is calculated on the fly (during grid display) and it is not searchable.
return '';
}
$search_keywords = $this->splitKeyword($search_keyword);
list ($field_name, $field_type, $table_name, $sql_filter_type) = $this->_getFieldInformation($object, $field_name);
$filter_value = '';
// get field clause by formatter name and/or parameters
$field_options = $object->GetFieldOptions($field_name);
$formatter = getArrayValue($field_options, '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($field_options, 'use_phrases');
$multiple = array_key_exists('multiple', $field_options) && $field_options['multiple'];
foreach ($field_options['options'] as $key => $val) {
$match_to = mb_strtolower($use_phrases ? $this->Application->Phrase($val) : $val);
foreach ($search_keywords as $keyword => $sign) {
// doesn't support wildcards
if (strpos($match_to, mb_strtolower($keyword)) === false) {
if ($sign == '+') {
$filter_value = $table_name.'`'.$field_name.'` = NULL';
break;
}
else {
continue;
}
}
if ($sign == '+' || $sign == '') {
// don't add single quotes to found option ids when multiselect (but escape string anyway)
$search_keys[$key] = $multiple ? $this->Conn->escape($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) {
if ($multiple) {
$filter_value = $table_name.'`'.$field_name.'` LIKE "%|' . implode('|%" OR ' . $table_name.'`'.$field_name.'` LIKE "%|', $search_keys) . '|%"';
}
else {
$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 Array|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) {
$filter_type = key($field_options);
$field_value = $field_options[$filter_type];
$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) {
$filter_type = key($field_options);
$field_options = $field_options[$filter_type];
$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;
}
/**
* Checks, that range filters "To" part is defined for given grid
*
* @param string $prefix_special
* @param string $grid_name
* @return bool
*/
function rangeFiltersUsed($prefix_special, $grid_name)
{
static $cache = Array ();
$cache_key = $prefix_special . $grid_name;
if (array_key_exists($cache_key, $cache)) {
return $cache[$cache_key];
}
$view_name = $this->Application->RecallVar($prefix_special . '_current_view');
$custom_filters = $this->Application->RecallPersistentVar($prefix_special . '_custom_filter.' . $view_name/*, ALLOW_DEFAULT_SETTINGS*/);
if (!$custom_filters) {
// filters not defined for given prefix
$cache[$cache_key] = false;
return false;
}
$custom_filters = unserialize($custom_filters);
if (!is_array($custom_filters) || !array_key_exists($grid_name, $custom_filters)) {
// filters not defined for given grid
$cache[$cache_key] = false;
return false;
}
$range_filter_defined = false;
$custom_filter = $custom_filters[$grid_name];
foreach ($custom_filter as $field_name => $field_options) {
$filter_type = key($field_options);
$field_options = $field_options[$filter_type];
if (strpos($filter_type, 'range') === false) {
continue;
}
$to_value = (string)$field_options['submit_value']['to'];
if ($to_value !== '') {
$range_filter_defined = true;
break;
}
}
$cache[$cache_key] = $range_filter_defined;
return $range_filter_defined;
}
/**
* Return numeric range filter value + checking that it's number
*
* @param Array $value array containing range filter value
* @return unknown
*/
function getRangeValue($value)
{
// fix user typing error, since MySQL only sees "." as decimal separator
$value = str_replace(',', '.', $value);
return strlen($value) && is_numeric($value) ? $this->Conn->qstr($value) : false;
}
/**
* Returns filter clause
*
* @param kDBItem $object
* @param string $field_name
* @param string $filter_type
* @param Array $field_options
* @return Array
*/
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'];
}
list ($field_name, $field_type, $table_name, $sql_filter_type) = $this->_getFieldInformation($object, $field_name);
$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 ( $field_type == 'int' || $field_type == 'integer' ) {
if ( $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;
}
}
else {
// MySQL can't compare values in "float" type columns using "=" operator
if ( $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 ( is_numeric($from) && $to === null && date('H:i:s', $from) == '00:00:00' ) {
$to = $from + $day_seconds;
}
elseif ( $from === null && is_numeric($to) && date('H:i:s', $to) == '00:00:00' ) {
$from = $to;
$to += $day_seconds;
}
if ( is_numeric($from) && $to === null || $from === null && is_numeric($to) ) {
$from = $from === null ? $to : $from;
$to = $from;
}
if ( is_numeric($from) && is_numeric($to) ) {
$from = strtotime(date('Y-m-d H:i', $from) . ':00', $from);
$to = strtotime(date('Y-m-d H:i', $to) . ':59', $to);
$filter_value = $table_name.'`'.$field_name.'` >= '.$from.' AND '.$table_name.'`'.$field_name.'` <= '.$to;
}
else {
$filter_value = 'FALSE';
}
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']) ? $this->Conn->escape($field_options['submit_value']) : false;
if ($field_value) {
$filter_value = $table_name.'`'.$field_name.'` LIKE "%|'.$field_value.'|%"';
}
break;
case 'multioptions':
$field_value = $field_options['submit_value'];
if ( $field_value ) {
$field_value = explode('|', substr($field_value, 1, -1));
$multiple = $object->GetFieldOption($field_name, 'multiple');
$field_value = $this->Conn->qstrArray($field_value, $multiple ? 'escape' : 'qstr');
if ( $multiple ) {
$filter_value = $table_name . '`' . $field_name . '` LIKE "%|' . implode('|%" OR ' . $table_name . '`' . $field_name . '` LIKE "%|', $field_value) . '|%"';
}
else {
$filter_value = $table_name . '`' . $field_name . '` IN (' . implode(',', $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
* @param string $format_option_prefix Format option prefix.
*/
function processRangeField(&$object, $search_field, $value, $type, $format_option_prefix = '')
{
$value_by_type = $value[$type];
if ( !strlen($value_by_type) ) {
return null;
}
$options = $object->GetFieldOptions($search_field);
$dt_separator = array_key_exists('date_time_separator', $options) ? $options['date_time_separator'] : ' ';
$value_by_type = trim($value_by_type, $dt_separator); // trim any
$tmp_value = explode($dt_separator, $value_by_type, 2);
if ( count($tmp_value) == 1 ) {
$time_format = $this->_getInputTimeFormat($options, $format_option_prefix . 'time_format');
if ( $time_format ) {
// time is missing, but time format available -> guess time and add to date
$time = adodb_mktime(0, 0, 0);
$time = adodb_date($time_format, $time);
$value_by_type .= $dt_separator . $time;
}
}
/** @var kFormatter $formatter */
$formatter = $this->Application->recallObject($options['formatter']);
$format = $options[$format_option_prefix . 'format'];
$value_ts = $formatter->Parse($value_by_type, $search_field, $object, $format);
if ( $object->GetErrorPseudo($search_field) ) {
// invalid format -> ignore this date in search
$object->RemoveError($search_field);
if ( $format_option_prefix == 'input_' ) {
return false;
}
return $this->processRangeField($object, $search_field, $value, $type, 'input_');
}
return $value_ts;
}
/**
* Returns InputTimeFormat using given field options
*
* @param Array $field_options
* @param string $format_option_name Format option name.
* @return string
*/
function _getInputTimeFormat($field_options, $format_option_name = 'input_time_format')
{
if ( array_key_exists($format_option_name, $field_options) ) {
return $field_options[$format_option_name];
}
/** @var LanguagesItem $lang_current */
$lang_current = $this->Application->recallObject('lang.current');
$field_name = str_replace(' ', '', ucwords(str_replace('_', ' ', $format_option_name)));
return $lang_current->GetDBField($field_name);
}
/**
* 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)
{
/** @var kMultipleFilter $includes_or_filter */
$includes_or_filter = $this->Application->makeClass('kMultipleFilter', Array (kDBList::FLT_TYPE_OR));
/** @var kMultipleFilter $excepts_and_filter */
$excepts_and_filter = $this->Application->makeClass('kMultipleFilter', Array (kDBList::FLT_TYPE_AND));
/** @var kMultipleFilter $includes_or_filter_h */
$includes_or_filter_h = $this->Application->makeClass('kMultipleFilter', Array (kDBList::FLT_TYPE_OR));
/** @var kMultipleFilter $excepts_and_filter_h */
$excepts_and_filter_h = $this->Application->makeClass('kMultipleFilter', Array (kDBList::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']);
}
}
}
}
/** @var kDBList $object */
$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, kDBList::HAVING_FILTER);
$object->addFilter('excepts_filter_h', $excepts_and_filter_h, kDBList::HAVING_FILTER);
}
/**
* Ensures empty search table
*
* @return void
*/
public function ensureEmptySearchTable()
{
$search_table = $this->getSearchTable();
$sql = 'CREATE TABLE IF NOT EXISTS ' . $search_table . ' (
`Relevance` decimal(8,5) DEFAULT NULL,
`ItemId` int(11) NOT NULL DEFAULT 0,
`ResourceId` int(11) DEFAULT NULL,
`ItemType` int(1) NOT NULL DEFAULT 0,
`EdPick` tinyint(4) NOT NULL DEFAULT 0,
KEY `ResourceId` (`ResourceId`),
KEY `Relevance` (`Relevance`)
) ENGINE = MEMORY';
$this->Conn->Query($sql);
$sql = 'TRUNCATE TABLE ' . $search_table;
$this->Conn->Query($sql);
}
/**
* Search table name
*
* @return string
*/
public function getSearchTable()
{
- return TABLE_PREFIX . 'ses_' . $this->Application->GetSID() . '_' . TABLE_PREFIX . 'Search';
+ try {
+ $sid = $this->Application->GetSID(Session::PURPOSE_REFERENCE);
+ }
+ catch ( RuntimeException $e ) {
+ // 1. Put some real variable into session, or otherwise it won't even save to the database.
+ $this->Application->StoreVar('search_made', 'yes');
+
+ // 2. Create session on they fly to store search results.
+ $this->Application->Session->SaveData();
+
+ // 3. Get ID of the created session.
+ $sid = $this->Application->GetSID(Session::PURPOSE_REFERENCE);
+ }
+
+ return TABLE_PREFIX . 'ses_' . $sid . '_' . TABLE_PREFIX . 'Search';
}
}
Index: branches/5.2.x/core/units/logs/session_logs/session_logs_config.php
===================================================================
--- branches/5.2.x/core/units/logs/session_logs/session_logs_config.php (revision 16796)
+++ branches/5.2.x/core/units/logs/session_logs/session_logs_config.php (revision 16797)
@@ -1,153 +1,155 @@
<?php
/**
* @version $Id$
* @package In-Portal
* @copyright Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license GNU/GPL
* In-Portal is Open Source software.
* This means that this software may have been modified pursuant
* the GNU General Public License, and as distributed it includes
* or is derivative of works licensed under the GNU General Public License
* or other free or open source software licenses.
* See http://www.in-portal.org/license for copyright notices and details.
*/
defined('FULL_PATH') or die('restricted access!');
$config = Array (
'Prefix' => 'session-log',
'ItemClass' => Array ('class' => 'kDBItem', 'file' => '', 'build_event' => 'OnItemBuild'),
'ListClass' => Array ('class' => 'kDBList', 'file' => '', 'build_event' => 'OnListBuild'),
'EventHandlerClass' => Array ('class' => 'SessionLogEventHandler', 'file' => 'session_log_eh.php', 'build_event' => 'OnBuild'),
'TagProcessorClass' => Array ('class' => 'kDBTagProcessor', 'file' => '', 'build_event' => 'OnBuild'),
'AutoLoad' => true,
'Hooks' => Array (
Array (
'Mode' => hAFTER,
'Conditional' => false,
'HookToPrefix' => 'u',
'HookToSpecial' => '*',
'HookToEvent' => Array ('OnAfterLogin'),
'DoPrefix' => '',
'DoSpecial' => '*',
'DoEvent' => 'OnStartSession',
),
Array (
'Mode' => hAFTER,
'Conditional' => false,
'HookToPrefix' => 'u',
'HookToSpecial' => '*',
'HookToEvent' => Array ('OnBeforeLogout'),
'DoPrefix' => '',
'DoSpecial' => '*',
'DoEvent' => 'OnEndSession',
),
),
'QueryString' => Array (
1 => 'id',
2 => 'Page',
3 => 'PerPage',
4 => 'event',
5 => 'mode',
),
'IDField' => 'SessionLogId',
'StatusField' => Array ('Status'),
'TableName' => TABLE_PREFIX.'UserSessionLogs',
'TitlePresets' => Array (
'session_log_list' => Array ('prefixes' => Array ('session-log_List'), 'format' => '!la_tab_SessionLogs!',
'toolbar_buttons' => Array ('delete', 'view'),
),
),
'PermSection' => Array ('main' => 'in-portal:session_logs'),
'Sections' => Array (
'in-portal:session_logs' => Array (
'parent' => 'in-portal:reports',
'icon' => 'sessions_log',
'label' => 'la_tab_SessionLog', // 'la_tab_SessionLogs',
'url' => Array ('t' => 'logs/session_logs/session_log_list', 'pass' => 'm'),
'permissions' => Array ('view', 'delete'),
'priority' => 2,
// 'show_mode' => smSUPER_ADMIN,
'type' => stTREE,
),
),
'TitleField' => 'SessionLogId',
'ListSQLs' => Array (
'' => ' SELECT %1$s.* %2$s
FROM %1$s
LEFT JOIN '.TABLE_PREFIX.'Users AS u ON u.PortalUserId = %1$s.PortalUserId',
),
'ListSortings' => Array (
'' => Array (
'Sorting' => Array ('SessionLogId' => 'desc'),
)
),
'CalculatedFields' => Array (
'' => Array (
'UserLogin' => 'IF(%1$s.PortalUserId = ' . USER_ROOT . ', \'root\', u.Username)',
'UserFirstName' => 'u.FirstName',
'UserLastName' => 'u.LastName',
'UserEmail' => 'u.Email',
'Duration' => 'IFNULL(SessionEnd, UNIX_TIMESTAMP())-SessionStart',
),
),
'ForceDontLogChanges' => true,
'Fields' => Array (
'SessionLogId' => Array ('type' => 'int', 'not_null' => 1, 'default' => 0),
'PortalUserId' => Array ('type' => 'int', 'not_null' => 1, 'default' => 0),
'SessionId' => Array ('type' => 'int', 'not_null' => 1, 'default' => 0),
+ 'SessionKey' => Array ('type' => 'string', 'max_len' => 64, 'not_null' => 1, 'default' => ''),
'Status' => Array (
'type' => 'int', 'formatter' => 'kOptionsFormatter',
'options'=> Array (0 => 'la_opt_Active', 1 => 'la_opt_LoggedOut', 2 => 'la_opt_Expired'),
'use_phrases' => 1,
'not_null' => 1, 'default' => 1
),
'SessionStart' => Array ('type' => 'int', 'formatter' => 'kDateFormatter', 'time_format' => 'H:i:s', 'default' => NULL),
'SessionEnd' => Array ('type' => 'int', 'formatter' => 'kDateFormatter', 'time_format' => 'H:i:s', 'default' => NULL),
'IP' => Array ('type' => 'string', 'max_len' => 15, 'not_null' => 1, 'default' => ''),
'AffectedItems' => Array ('type' => 'int', 'not_null' => 1, 'default' => 0),
),
'VirtualFields' => Array (
'Duration' => Array ('type' => 'int', 'formatter' => 'kDateFormatter', 'date_format' => '', 'time_format' => 'H:i:s', 'use_timezone' => false, 'default' => NULL),
'UserLogin' => Array ('type' => 'string', 'default' => ''),
'UserFirstName' => Array ('type' => 'string', 'default' => ''),
'UserLastName' => Array ('type' => 'string', 'default' => ''),
'UserEmail' => Array ('type' => 'string', 'default' => ''),
),
'Grids' => Array (
'Default' => Array (
'Icons' => Array ('default' => 'icon16_item.png'),
'Fields' => Array (
'SessionLogId' => Array ('title' => 'column:la_fld_Id', 'data_block' => 'grid_checkbox_td', 'filter_block' => 'grid_range_filter', 'width' => 70, ),
+ 'SessionKey' => Array ('title' => 'column:la_fld_LogSessionKey', 'filter_block' => 'grid_like_filter', 'width' => 120, ),
'PortalUserId' => Array ('title' => 'la_col_PortalUserId', 'filter_block' => 'grid_range_filter', 'width' => 70, ),
'UserLogin' => Array ('title' => 'column:la_fld_Username', 'filter_block' => 'grid_like_filter', 'width' => 100, ),
'UserFirstName' => Array ('title' => 'column:la_fld_FirstName', 'filter_block' => 'grid_like_filter', 'width' => 120, ),
'UserLastName' => Array ('title' => 'column:la_fld_LastName', 'filter_block' => 'grid_like_filter', 'width' => 120, ),
'UserEmail' => Array ('title' => 'column:la_fld_Email', 'filter_block' => 'grid_like_filter', 'width' => 120, ),
'SessionStart' => Array ('title' => 'la_col_SessionStart', 'filter_block' => 'grid_date_range_filter', 'width' => 120, ),
'SessionEnd' => Array ('title' => 'la_col_SessionEnd', 'filter_block' => 'grid_date_range_filter', 'width' => 145, ),
'Duration' => Array ('filter_block' => 'grid_range_filter', 'width' => 100, ),
'Status' => Array ('filter_block' => 'grid_options_filter', 'width' => 100, ),
'IP' => Array ('title' => 'la_col_IP', 'filter_block' => 'grid_like_filter', 'width' => 150, ),
'AffectedItems' => Array ('title' => 'la_col_AffectedItems', 'data_block' => 'affected_td', 'filter_block' => 'grid_range_filter', 'width' => 120, ),
),
),
),
-);
\ No newline at end of file
+);
Index: branches/5.2.x/core/units/logs/session_logs/session_log_eh.php
===================================================================
--- branches/5.2.x/core/units/logs/session_logs/session_log_eh.php (revision 16796)
+++ branches/5.2.x/core/units/logs/session_logs/session_log_eh.php (revision 16797)
@@ -1,130 +1,133 @@
<?php
/**
* @version $Id$
* @package In-Portal
* @copyright Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license GNU/GPL
* In-Portal is Open Source software.
* This means that this software may have been modified pursuant
* the GNU General Public License, and as distributed it includes
* or is derivative of works licensed under the GNU General Public License
* or other free or open source software licenses.
* See http://www.in-portal.org/license for copyright notices and details.
*/
defined('FULL_PATH') or die('restricted access!');
class SessionLogEventHandler extends kDBEventHandler {
/**
* Opens log for new session
*
* @param kEvent $event
*/
function OnStartSession($event)
{
- if (!$this->Application->ConfigValue('UseChangeLog')) {
- // don't use session log when change log is disabled
- return ;
+ if ( (defined('IS_INSTALL') && IS_INSTALL)
+ || !$this->Application->ConfigValue('UseChangeLog')
+ ) {
+ // Don't use session log when installing OR change log is disabled.
+ return;
}
/** @var kDBItem $object */
$object = $this->Application->recallObject($event->Prefix, null, Array ('skip_autoload' => 1));
$fields_hash = Array (
'SessionStart' => adodb_mktime(),
'IP' => $this->Application->getClientIp(),
'PortalUserId' => $this->Application->RecallVar('user_id'),
- 'SessionId' => $this->Application->GetSID(),
+ 'SessionId' => $this->Application->GetSID(Session::PURPOSE_REFERENCE),
+ 'SessionKey' => $this->Application->GetSID(Session::PURPOSE_STORAGE),
'Status' => SESSION_LOG_ACTIVE,
);
$object->SetDBFieldsFromHash($fields_hash);
$object->UpdateFormattersSubFields();
if ($object->Create()) {
$this->Application->StoreVar('_SessionLogId_', $object->GetID());
}
}
/**
* Closes log for current session
*
* @param kEvent $event
*/
function OnEndSession($event)
{
/** @var kDBItem $object */
$object = $this->Application->recallObject($event->Prefix, null, Array ('skip_autoload' => 1));
$object->Load($this->Application->RecallVar('_SessionLogId_'));
if (!$object->isLoaded()) {
return ;
}
$fields_hash = Array (
'SessionEnd' => adodb_mktime(),
'Status' => SESSION_LOG_LOGGED_OUT,
);
$object->SetDBFieldsFromHash($fields_hash);
$object->UpdateFormattersSubFields();
$object->Update();
}
/**
* Apply custom processing to item
*
* @param kEvent $event
* @param string $type
* @return void
* @access protected
*/
protected function customProcessing(kEvent $event, $type)
{
if ( $event->Name == 'OnMassDelete' && $type == 'before' ) {
$ids = $event->getEventParam('ids');
if ( $ids ) {
$id_field = $this->Application->getUnitOption($event->Prefix, 'IDField');
$table_name = $this->Application->getUnitOption($event->Prefix, 'TableName');
$sql = 'SELECT ' . $id_field . '
FROM ' . $table_name . '
WHERE ' . $id_field . ' IN (' . implode(',', $ids) . ') AND Status <> ' . SESSION_LOG_ACTIVE;
$allowed_ids = $this->Conn->GetCol($sql);
$event->setEventParam('ids', $allowed_ids);
}
}
}
/**
* Delete changes, related to deleted session
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnAfterItemDelete(kEvent $event)
{
parent::OnAfterItemDelete($event);
/** @var kDBItem $object */
$object = $event->getObject();
$sql = 'SELECT ' . $this->Application->getUnitOption('change-log', 'IDField') . '
FROM ' . $this->Application->getUnitOption('change-log', 'TableName') . '
WHERE SessionLogId = ' . $object->GetID();
$related_ids = $this->Conn->GetCol($sql);
if ( $related_ids ) {
/** @var kTempTablesHandler $temp_handler */
$temp_handler = $this->Application->recallObject('change-log_TempHandler', 'kTempTablesHandler');
$temp_handler->DeleteItems('change-log', '', $related_ids);
}
}
- }
\ No newline at end of file
+ }
Index: branches/5.2.x/core/units/logs/system_logs/system_logs_config.php
===================================================================
--- branches/5.2.x/core/units/logs/system_logs/system_logs_config.php (revision 16796)
+++ branches/5.2.x/core/units/logs/system_logs/system_logs_config.php (revision 16797)
@@ -1,214 +1,214 @@
<?php
/**
* @version $Id$
* @package In-Portal
* @copyright Copyright (C) 1997 - 2012 Intechnic. All rights reserved.
* @license GNU/GPL
* In-Portal is Open Source software.
* This means that this software may have been modified pursuant
* the GNU General Public License, and as distributed it includes
* or is derivative of works licensed under the GNU General Public License
* or other free or open source software licenses.
* See http://www.in-portal.org/license for copyright notices and details.
*/
defined('FULL_PATH') or die('restricted access!');
$config = Array (
'Prefix' => 'system-log',
'ItemClass' => Array ('class' => 'kDBItem', 'file' => '', 'build_event' => 'OnItemBuild'),
'ListClass' => Array ('class' => 'kDBList', 'file' => '', 'build_event' => 'OnListBuild'),
'EventHandlerClass' => Array ('class' => 'SystemLogEventHandler', 'file' => 'system_log_eh.php', 'build_event' => 'OnBuild'),
'TagProcessorClass' => Array ('class' => 'SystemLogTagProcessor', 'file' => 'system_log_tp.php', 'build_event' => 'OnBuild'),
'AutoLoad' => true,
'QueryString' => Array (
1 => 'id',
2 => 'Page',
3 => 'PerPage',
4 => 'event',
5 => 'mode',
),
'ScheduledTasks' => Array (
'system_log_notifications' => Array ('EventName' => 'OnSendNotifications', 'RunSchedule' => '0 * * * *'),
'rotate_system_logs' => Array ('EventName' => 'OnRotate', 'RunSchedule' => '0 0 * * *'),
'rotate_system_log_code_fragments' => Array ('EventName' => 'OnRotateCodeFragmentsScheduledTask', 'RunSchedule' => '0 0 * * 0'),
),
'IDField' => 'LogId',
// 'StatusField' => Array ('Status'),
'TableName' => TABLE_PREFIX . 'SystemLog',
'TitlePresets' => Array (
'default' => Array (
'edit_status_labels' => Array ('system-log' => '!la_title_ViewingSystemLog!'),
),
'system_log_list' => Array (
'prefixes' => Array ('system-log_List'), 'format' => '!la_tab_SystemLog!',
'toolbar_buttons' => Array ('edit', 'delete', 'reset', 'view', 'dbl-click'),
),
'system_log_edit' => Array (
'prefixes' => Array ('system-log'), 'format' => '#system-log_status# "#system-log_titlefield#"',
'toolbar_buttons' => Array ('select', 'cancel', 'reset_edit', 'prev', 'next'),
),
),
'PermSection' => Array ('main' => 'in-portal:system_logs'),
'Sections' => Array (
'in-portal:system_logs' => Array (
'parent' => 'in-portal:reports',
'icon' => 'system_log',
'label' => 'la_tab_SystemLog',
'url' => Array ('t' => 'logs/system_logs/system_log_list', 'pass' => 'm'),
'permissions' => Array ('view', 'edit', 'delete'),
'priority' => 6.1,
'type' => stTREE,
),
),
'TitleField' => 'LogMessage',
'ListSQLs' => Array (
'' => ' SELECT %1$s.* %2$s
FROM %1$s
LEFT JOIN '.TABLE_PREFIX.'Users AS u ON u.PortalUserId = %1$s.LogUserId',
),
'ListSortings' => Array (
'' => Array (
'Sorting' => Array ('LogId' => 'desc'),
)
),
'CalculatedFields' => Array (
'' => Array (
'Username' => 'CASE %1$s.LogUserId WHEN ' . USER_ROOT . ' THEN "root" WHEN ' . USER_GUEST . ' THEN "Guest" ELSE IF(CONCAT(u.FirstName, u.LastName) <> "", CONCAT(u.FirstName, " ", u.LastName), IF(u.Username = "", u.Email, u.Username)) END',
),
),
'ForceDontLogChanges' => true,
'Fields' => Array (
'LogId' => Array ('type' => 'int', 'not_null' => 1, 'default' => 0),
'LogUniqueId' => Array ('type' => 'int', 'default' => NULL),
'LogLevel' => Array (
'type' => 'int',
'formatter' => 'kOptionsFormatter', 'options' => Array (
kLogger::LL_EMERGENCY => 'emergency',
kLogger::LL_ALERT => 'alert',
kLogger::LL_CRITICAL => 'critical',
kLogger::LL_ERROR => 'error',
kLogger::LL_WARNING => 'warning',
kLogger::LL_NOTICE => 'notice',
kLogger::LL_INFO => 'info',
kLogger::LL_DEBUG => 'debug'
),
'not_null' => 1, 'default' => kLogger::LL_INFO
),
'LogType' => Array (
'type' => 'int',
'formatter' => 'kOptionsFormatter', 'options' => Array (
kLogger::LT_PHP => 'la_opt_LogTypePhp',
kLogger::LT_DATABASE => 'la_opt_LogTypeDatabase',
kLogger::LT_OTHER => 'la_opt_LogTypeOther',
), 'use_phrases' => 1,
'not_null', 'default' => kLogger::LT_OTHER
),
'LogCode' => Array ('type' => 'int', 'default' => NULL),
'LogMessage' => Array ('type' => 'string', 'default' => NULL),
'LogTimestamp' => Array (
'type' => 'int',
'formatter' => 'kDateFormatter',
'default' => NULL
),
'LogDate' => Array ('type' => 'string', 'default' => NULL),
'LogEventName' => Array ('type' => 'string', 'max_len' => 100, 'not_null' => 1, 'default' => ''),
'LogHostname' => Array ('type' => 'string', 'max_len' => 255, 'not_null' => 1, 'default' => ''),
'LogRequestSource' => Array (
'type' => 'int',
'formatter' => 'kOptionsFormatter', 'options' => Array (1 => 'Web', 2 => 'CLI'),
'default' => NULL
),
'LogRequestURI' => Array ('type' => 'string', 'max_len' => 255, 'not_null' => 1, 'default' => ''),
'LogRequestData' => Array ('type' => 'string', 'default' => NULL),
'LogUserId' => Array (
'type' => 'int',
'default' => NULL
),
'LogInterface' => Array (
'type' => 'int',
'formatter' => 'kOptionsFormatter', 'options' => Array (
kLogger::LI_FRONT => 'Front',
kLogger::LI_ADMIN => 'Admin',
kLogger::LI_CRON_FRONT => 'Cron (Front)',
kLogger::LI_CRON_ADMIN => 'Cron (Admin)',
kLogger::LI_API => 'API',
),
'not_null' => 1, 'default' => 0
),
'IpAddress' => Array ('type' => 'string', 'max_len' => 15, 'not_null' => 1, 'default' => ''),
- 'LogSessionKey' => Array ('type' => 'int', 'default' => NULL),
+ 'LogSessionKey' => Array ('type' => 'string', 'max_len' => 64, 'not_null' => 1, 'default' => ''),
'LogSessionData' => Array ('type' => 'string', 'default' => NULL),
'LogBacktrace' => Array ('type' => 'string', 'default' => NULL),
'LogSourceFilename' => Array ('type' => 'string', 'max_len' => 255, 'not_null' => 1, 'default' => ''),
'LogSourceFileLine' => Array ('type' => 'int', 'default' => NULL),
'LogCodeFragment' => Array ('type' => 'string', 'default' => NULL),
'LogCodeFragmentsRotated' => Array (
'type' => 'int',
'formatter' => 'kOptionsFormatter',
'options' => Array (1 => 'la_Yes', 0 => 'la_No'), 'use_phrases' => 1,
'not_null' => 1, 'default' => 0,
),
'LogProcessId' => Array ('type' => 'int', 'default' => NULL),
'LogMemoryUsed' => Array ('type' => 'int', 'not_null' => 1, 'default' => 0),
'LogUserData' => Array ('type' => 'string', 'not_null' => 1, 'default' => ''),
'LogNotificationStatus' => Array (
'type' => 'int',
'formatter' => 'kOptionsFormatter', 'options' => Array (
kLogger::LNS_DISABLED => 'la_opt_LogNotificationDisabled',
kLogger::LNS_PENDING => 'la_opt_LogNotificationPending',
kLogger::LNS_SENT => 'la_opt_LogNotificationSent'
), 'use_phrases' => 1,
'not_null' => 1, 'default' => kLogger::LNS_DISABLED
)
),
'VirtualFields' => Array (
'Username' => Array ('type' => 'string', 'default' => ''),
),
'Grids' => Array (
'Default' => Array (
// 'Icons' => Array ('default' => 'icon16_item.png'),
'Fields' => Array (
'LogId' => Array ('title' => 'column:la_fld_Id', 'filter_block' => 'grid_range_filter', 'width' => 80),
'LogUniqueId' => Array ('filter_block' => 'grid_range_filter', 'width' => 100),
'LogLevel' => Array ('filter_block' => 'grid_options_filter', 'width' => 100),
'LogType' => Array ('filter_block' => 'grid_options_filter', 'width' => 80),
'LogCode' => Array ('filter_block' => 'grid_range_filter', 'width' => 80),
'LogMessage' => Array ('filter_block' => 'grid_like_filter', 'width' => 250),
'LogTimestamp' => Array ('filter_block' => 'grid_date_range_filter', 'width' => 170),
'LogEventName' => Array ('filter_block' => 'grid_like_filter'),
'LogHostname' => Array ('filter_block' => 'grid_like_filter'),
'LogRequestSource' => Array ('filter_block' => 'grid_options_filter'),
'LogRequestURI' => Array ('data_block' => 'grid_uri_td', 'filter_block' => 'grid_like_filter'),
'Username' => Array ('filter_block' => 'grid_range_filter', 'width' => 80),
'LogInterface' => Array ('filter_block' => 'grid_options_filter'),
'IpAddress' => Array ('filter_block' => 'grid_like_filter'),
'LogSessionKey' => Array ('filter_block' => 'grid_range_filter', 'width' => 80),
'LogSourceFilename' => Array ('data_block' => 'grid_filename_td', 'filter_block' => 'grid_like_filter', 'width' => 200),
'LogSourceFileLine' => Array ('filter_block' => 'grid_range_filter', 'width' => 80),
'LogProcessId' => Array ('filter_block' => 'grid_range_filter', 'width' => 80),
'LogMemoryUsed' => Array ('data_block' => 'grid_memory_td', 'filter_block' => 'grid_range_filter'),
'LogUserData' => Array ('filter_block' => 'grid_like_filter', 'nl2br' => 1),
'LogNotificationStatus' => Array ('filter_block' => 'grid_options_filter'),
'LogBacktrace' => Array ('data_block' => 'grid_backtrace_td', 'filter_block' => 'grid_empty_filter', 'width' => 500, 'hidden' => 1),
),
),
),
);
Index: branches/5.2.x/core/units/admin/admin_events_handler.php
===================================================================
--- branches/5.2.x/core/units/admin/admin_events_handler.php (revision 16796)
+++ branches/5.2.x/core/units/admin/admin_events_handler.php (revision 16797)
@@ -1,1387 +1,1386 @@
<?php
/**
* @version $Id$
* @package In-Portal
* @copyright Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license GNU/GPL
* In-Portal is Open Source software.
* This means that this software may have been modified pursuant
* the GNU General Public License, and as distributed it includes
* or is derivative of works licensed under the GNU General Public License
* or other free or open source software licenses.
* See http://www.in-portal.org/license for copyright notices and details.
*/
defined('FULL_PATH') or die('restricted access!');
class AdminEventsHandler extends kDBEventHandler {
/**
* Allows to override standard permission mapping
*
* @return void
* @access protected
* @see kEventHandler::$permMapping
*/
protected function mapPermissions()
{
parent::mapPermissions();
$permissions = Array (
'OnSaveColumns' => Array ('self' => true),
'OnGetPopupSize' => Array ('self' => true),
'OnClosePopup' => Array ('self' => true),
'OnSaveSetting' => Array ('self' => true),
- 'OnDropTempTablesByWID' => Array ('self' => true),
'OnProcessSelected' => Array ('self' => true), // allow CSV import file upload
);
$this->permMapping = array_merge($this->permMapping, $permissions);
}
/**
* Checks user permission to execute given $event
*
* @param kEvent $event
* @return bool
* @access public
*/
public function CheckPermission(kEvent $event)
{
$perm_value = null;
$system_events = array(
'OnResetModRwCache', 'OnResetSections', 'OnResetConfigsCache', 'OnResetParsedData', 'OnResetMemcache',
'OnDeleteCompiledTemplates', 'OnCompileTemplates', 'OnGenerateTableStructure', 'OnSynchronizeDBRevisions',
'OnDeploy', 'OnRebuildThemes', 'OnDumpAssets', 'OnCheckPrefixConfig', 'OnMemoryCacheGet',
'OnMemoryCacheSet',
);
if ( in_array($event->Name, $system_events) ) {
// events from "Tools -> System Tools" section are controlled via that section "edit" permission
$perm_value = /*$this->Application->isDebugMode() ||*/ $this->Application->CheckPermission($event->getSection() . '.edit');
}
$tools_events = Array (
'OnBackup' => 'in-portal:backup.view',
'OnBackupProgress' => 'in-portal:backup.view',
'OnDeleteBackup' => 'in-portal:backup.view',
'OnBackupCancel' => 'in-portal:backup.view',
'OnRestore' => 'in-portal:restore.view',
'OnRestoreProgress' => 'in-portal:restore.view',
'OnRestoreCancel' => 'in-portal:backup.view',
'OnSqlQuery' => 'in-portal:sql_query.view',
);
if ( array_key_exists($event->Name, $tools_events) ) {
$perm_value = $this->Application->CheckPermission($tools_events[$event->Name]);
}
- if ( $event->Name == 'OnSaveMenuFrameWidth' ) {
+ if ( $event->Name == 'OnSaveMenuFrameWidth' || $event->Name == 'OnDropTempTablesByWID' ) {
$perm_value = $this->Application->isAdminUser;
}
/** @var kPermissionsHelper $perm_helper */
$perm_helper = $this->Application->recallObject('PermissionsHelper');
$csv_events = Array ('OnCSVImportBegin', 'OnCSVImportStep', 'OnExportCSV', 'OnGetCSV');
if ( in_array($event->Name, $csv_events) ) {
/** @var kCSVHelper $csv_helper */
$csv_helper = $this->Application->recallObject('CSVHelper');
$prefix = $csv_helper->getPrefix(stripos($event->Name, 'import') !== false);
$perm_mapping = Array (
'OnCSVImportBegin' => 'OnProcessSelected',
'OnCSVImportStep' => 'OnProcessSelected',
'OnExportCSV' => 'OnLoad',
'OnGetCSV' => 'OnLoad',
);
$tmp_event = new kEvent($prefix . ':' . $perm_mapping[$event->Name] );
$perm_value = $perm_helper->CheckEventPermission($tmp_event, $this->permMapping);
}
if ( isset($perm_value) ) {
return $perm_helper->finalizePermissionCheck($event, $perm_value);
}
return parent::CheckPermission($event);
}
/**
* Reset mod-rewrite url cache
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnResetModRwCache(kEvent $event)
{
if ( $this->Application->GetVar('ajax') == 'yes' ) {
$event->status = kEvent::erSTOP;
}
$this->Conn->Query('DELETE FROM ' . TABLE_PREFIX . 'CachedUrls');
$event->SetRedirectParam('action_completed', 1);
}
/**
* Resets tree section cache and refreshes admin section tree
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnResetSections(kEvent $event)
{
if ($this->Application->GetVar('ajax') == 'yes') {
$event->status = kEvent::erSTOP;
}
if ($this->Application->isCachingType(CACHING_TYPE_MEMORY)) {
$this->Application->rebuildCache('master:sections_parsed', kCache::REBUILD_LATER, CacheSettings::$sectionsParsedRebuildTime);
}
else {
$this->Application->rebuildDBCache('sections_parsed', kCache::REBUILD_LATER, CacheSettings::$sectionsParsedRebuildTime);
}
$event->SetRedirectParam('refresh_tree', 1);
$event->SetRedirectParam('action_completed', 1);
}
/**
* Resets unit config cache
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnResetConfigsCache(kEvent $event)
{
if ( $this->Application->GetVar('ajax') == 'yes' ) {
$event->status = kEvent::erSTOP;
}
if ( $this->Application->isCachingType(CACHING_TYPE_MEMORY) ) {
$this->Application->rebuildCache('master:config_files', kCache::REBUILD_LATER, CacheSettings::$unitCacheRebuildTime);
}
else {
$this->Application->rebuildDBCache('config_files', kCache::REBUILD_LATER, CacheSettings::$unitCacheRebuildTime);
}
$this->OnResetParsedData($event);
/** @var SkinHelper $skin_helper */
$skin_helper = $this->Application->recallObject('SkinHelper');
$skin_helper->deleteCompiled();
}
/**
* Resets parsed data from unit configs
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnResetParsedData(kEvent $event)
{
if ( $this->Application->GetVar('ajax') == 'yes' ) {
$event->status = kEvent::erSTOP;
}
$this->Application->DeleteUnitCache();
if ( $this->Application->GetVar('validate_configs') ) {
$event->SetRedirectParam('validate_configs', 1);
}
$event->SetRedirectParam('action_completed', 1);
}
/**
* Resets memory cache
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnResetMemcache(kEvent $event)
{
if ($this->Application->GetVar('ajax') == 'yes') {
$event->status = kEvent::erSTOP;
}
$this->Application->resetCache();
$event->SetRedirectParam('action_completed', 1);
}
/**
* Compiles all templates (with a progress bar)
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnCompileTemplates(kEvent $event)
{
/** @var NParserCompiler $compiler */
$compiler = $this->Application->recallObject('NParserCompiler');
$compiler->CompileTemplatesStep();
$event->status = kEvent::erSTOP;
}
/**
* Deletes all compiled templates
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnDeleteCompiledTemplates(kEvent $event)
{
if ( $this->Application->GetVar('ajax') == 'yes' ) {
$event->status = kEvent::erSTOP;
}
$base_path = WRITEABLE . DIRECTORY_SEPARATOR . 'cache';
// delete debugger reports
$debugger_reports = glob(RESTRICTED . '/debug_@*@.txt');
if ( $debugger_reports ) {
foreach ($debugger_reports as $debugger_report) {
unlink($debugger_report);
}
}
$this->_deleteCompiledTemplates($base_path);
$event->SetRedirectParam('action_completed', 1);
}
/**
* Deletes compiled templates in a given folder
*
* @param string $folder
* @param bool $unlink_folder
* @return void
* @access protected
*/
protected function _deleteCompiledTemplates($folder, $unlink_folder = false)
{
$sub_folders = glob($folder . '/*', GLOB_ONLYDIR);
if ( is_array($sub_folders) ) {
foreach ($sub_folders as $sub_folder) {
$this->_deleteCompiledTemplates($sub_folder, true);
}
}
$files = glob($folder . '/*.php');
if ( is_array($files) ) {
foreach ($files as $file) {
unlink($file);
}
}
if ( $unlink_folder ) {
rmdir($folder);
}
}
/**
* Generates structure for specified table
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnGenerateTableStructure(kEvent $event)
{
$types_hash = Array (
'string' => 'varchar|text|mediumtext|longtext|date|datetime|time|timestamp|char|year|enum|set',
'int' => 'smallint|mediumint|int|bigint|tinyint',
'float' => 'float|double|decimal',
);
$table_name = $this->Application->GetVar('table_name');
if ( !$table_name ) {
echo 'error: no table name specified';
return;
}
if ( TABLE_PREFIX && !preg_match('/^' . preg_quote(TABLE_PREFIX, '/') . '(.*)/', $table_name) && (strtolower($table_name) != $table_name) ) {
// table name without prefix, then add it (don't affect K3 tables named in lowercase)
$table_name = TABLE_PREFIX . $table_name;
}
if ( !$this->Conn->TableFound($table_name) ) {
// table with prefix doesn't exist, assume that just config prefix passed -> resolve table name from it
$prefix = preg_replace('/^' . preg_quote(TABLE_PREFIX, '/') . '/', '', $table_name);
if ( $this->Application->prefixRegistred($prefix) ) {
// when prefix is found -> use it's table (don't affect K3 tables named in lowecase)
$table_name = $this->Application->getUnitOption($prefix, 'TableName');
}
}
$table_info = $this->Conn->Query('DESCRIBE '.$table_name);
// 1. prepare config keys
$grids = Array (
'Default' => Array (
'Icons' => Array ('default' => 'icon16_item.png'),
'Fields' => Array (),
)
);
$grids_fields = Array();
$id_field = '';
$fields = Array ();
$float_types = Array ('float', 'double', 'numeric');
foreach ($table_info as $field_info) {
if ( preg_match('/l[\d]+_.*/', $field_info['Field']) ) {
// don't put multilingual fields in config
continue;
}
$field_options = Array ();
if ( $field_info['Key'] == 'PRI' ) {
if ( $field_info['Field'] == 'Id' ) {
$grid_col_options = Array ('filter_block' => 'grid_range_filter', 'width' => 80);
}
else {
$grid_col_options = Array ('title' => 'column:la_fld_Id', 'filter_block' => 'grid_range_filter', 'width' => 80);
}
}
else {
$grid_col_options = Array ('filter_block' => 'grid_like_filter');
}
// 1. get php field type by mysql field type
foreach ($types_hash as $php_type => $db_types) {
if ( preg_match('/' . $db_types . '/', $field_info['Type']) ) {
$field_options['type'] = $php_type;
break;
}
}
// 2. get field default value
$default_value = $field_info['Default'];
$not_null = $field_info['Null'] != 'YES';
if ( is_numeric($default_value) ) {
$default_value = preg_match('/[\.,]/', $default_value) ? (float)$default_value : (int)$default_value;
}
if ( is_null($default_value) && $not_null ) {
$default_value = $field_options['type'] == 'string' ? '' : 0;
}
if ( in_array($php_type, $float_types) ) {
// this is float number
if ( preg_match('/' . $db_types . '\([\d]+,([\d]+)\)/i', $field_info['Type'], $regs) ) {
// size is described in structure -> add formatter
$field_options['formatter'] = 'kFormatter';
$field_options['format'] = '%01.' . $regs[1] . 'f';
if ( $not_null ) {
// null fields, will most likely have NULL as default value
$default_value = 0;
}
}
elseif ( $not_null ) {
// no size information, just convert to float
// null fields, will most likely have NULL as default value
$default_value = (float)$default_value;
}
}
if ( preg_match('/varchar\(([\d]+)\)/i', $field_info['Type'], $regs) ) {
$field_options['max_len'] = (int)$regs[1];
}
if ( preg_match('/tinyint\([\d]+\)/i', $field_info['Type']) ) {
$field_options['formatter'] = 'kOptionsFormatter';
$field_options['options'] = Array (1 => 'la_Yes', 0 => 'la_No');
$field_options['use_phrases'] = 1;
$grid_col_options['filter_block'] = 'grid_options_filter';
}
if ( $not_null ) {
$field_options['not_null'] = 1;
}
if ( $field_info['Key'] == 'PRI' ) {
$default_value = 0;
$id_field = $field_info['Field'];
}
if ( $php_type == 'int' && !$not_null ) {
// numeric null field
if ( preg_match('/(On|Date)$/', $field_info['Field']) || $field_info['Field'] == 'Modified' ) {
$field_options['formatter'] = 'kDateFormatter';
$grid_col_options['filter_block'] = 'grid_date_range_filter';
$grid_col_options['width'] = 120;
}
else {
$grid_col_options['filter_block'] = 'grid_range_filter';
$grid_col_options['width'] = 80;
}
}
if ( $php_type == 'int' && ($not_null || is_numeric($default_value)) ) {
// is integer field AND not null
$field_options['default'] = (int)$default_value;
}
else {
$field_options['default'] = $default_value;
}
$fields[$field_info['Field']] = $field_options;
$grids_fields[$field_info['Field']] = $grid_col_options;
}
$grids['Default']['Fields'] = $grids_fields;
$ret = Array (
'IDField' => $id_field,
'Fields' => $fields,
'Grids' => $grids,
);
$decorator = new UnitConfigDecorator();
$ret = $decorator->decorate($ret);
$this->Application->InitParser();
ob_start();
echo $this->Application->ParseBlock(Array('name' => 'incs/header', 'body_properties' => 'style="background-color: #E7E7E7; margin: 8px;"'));
?>
<script type="text/javascript">
set_window_title('Table "<?php echo $table_name; ?>" Structure');
</script>
<a href="javascript:window_close();">Close Window</a><br /><br />
<?php echo $GLOBALS['debugger']->highlightString($ret); ?>
<br /><br /><a href="javascript:window_close();">Close Window</a><br />
<?php
echo $this->Application->ParseBlock(Array('name' => 'incs/footer'));
echo ob_get_clean();
$event->status = kEvent::erSTOP;
}
/**
* Refreshes ThemeFiles & Themes tables by actual content on HDD
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnRebuildThemes(kEvent $event)
{
if ( $this->Application->GetVar('ajax') == 'yes' ) {
$event->status = kEvent::erSTOP;
}
/** @var kThemesHelper $themes_helper */
$themes_helper = $this->Application->recallObject('ThemesHelper');
$themes_helper->refreshThemes();
$event->SetRedirectParam('action_completed', 1);
}
/**
* Dumps assets
*
* @param kEvent $event Event.
*
* @return void
*/
protected function OnDumpAssets(kEvent $event)
{
if ( $this->Application->GetVar('ajax') == 'yes' ) {
$event->status = kEvent::erSTOP;
}
/** @var MinifyHelper $minify_helper */
$minify_helper = $this->Application->recallObject('MinifyHelper');
$minify_helper->delete();
$minify_helper->dump();
$event->SetRedirectParam('action_completed', 1);
}
/**
* Saves grid column widths after their resize by user
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnSaveColumns(kEvent $event)
{
$picker_helper = new kColumnPickerHelper(
$this->Application->GetVar('main_prefix'),
$this->Application->GetLinkedVar('grid_name')
);
$picked = trim($this->Application->GetVar('picked_str'), '|');
$hidden = trim($this->Application->GetVar('hidden_str'), '|');
$picker_helper->saveColumns($picked, $hidden);
$this->finalizePopup($event);
}
/**
* Saves various admin settings via ajax
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnSaveSetting(kEvent $event)
{
if ( $this->Application->GetVar('ajax') != 'yes' ) {
return;
}
$var_name = $this->Application->GetVar('var_name');
$var_value = $this->Application->GetVar('var_value');
$this->Application->StorePersistentVar($var_name, $var_value);
$event->status = kEvent::erSTOP;
}
/**
* Just closes popup & deletes last_template & opener_stack if popup, that is closing
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnClosePopup(kEvent $event)
{
$event->SetRedirectParam('opener', 'u');
}
/**
* Occurs right after initialization of the kernel, used mainly as hook-to event
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnStartup(kEvent $event)
{
if ( $this->Application->isAdmin ) {
return;
}
$base_url = preg_quote($this->Application->BaseURL(), '/');
$referrer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
if ( $referrer && !preg_match('/^' . $base_url . '/', $referrer) ) {
$this->Application->Session->SetCookie('original_referrer', $referrer);
$this->Application->SetVar('original_referrer', $referrer);
}
}
/**
* Occurs right before echoing the output, in Done method of application, used mainly as hook-to event
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnBeforeShutdown(kEvent $event)
{
}
/**
* Is called after tree was build (when not from cache)
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnAfterBuildTree(kEvent $event)
{
}
/**
* Called by AJAX to perform CSV export
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnExportCSV(kEvent $event)
{
/** @var kCSVHelper $csv_helper */
$csv_helper = $this->Application->recallObject('CSVHelper');
$csv_helper->PrefixSpecial = $csv_helper->getPrefix(false);
$csv_helper->grid = $this->Application->GetVar('grid');
$csv_helper->ExportStep();
$event->status = kEvent::erSTOP;
}
/**
* Returning created by AJAX CSV file
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnGetCSV(kEvent $event)
{
/** @var kCSVHelper $csv_helper */
$csv_helper = $this->Application->recallObject('CSVHelper');
$csv_helper->GetCSV();
}
/**
* Start CSV import
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnCSVImportBegin(kEvent $event)
{
/** @var kDBItem $object */
$object = $event->getObject(Array ('skip_autoload' => true));
$object->setID(0);
$field_values = $this->getSubmittedFields($event);
$object->SetFieldsFromHash($field_values);
$event->setEventParam('form_data', $field_values);
$event->redirect = false;
$result = 'required';
if ( $object->GetDBField('ImportFile') ) {
/** @var kCSVHelper $csv_helper */
$csv_helper = $this->Application->recallObject('CSVHelper');
$csv_helper->PrefixSpecial = $csv_helper->getPrefix(true);
$csv_helper->grid = $this->Application->GetVar('grid');
$result = $csv_helper->ImportStart($object->GetField('ImportFile', 'file_paths'));
if ( $result === true ) {
$event->redirect = $this->Application->GetVar('next_template');
$event->SetRedirectParam('PrefixSpecial', $this->Application->GetVar('PrefixSpecial'));
$event->SetRedirectParam('grid', $this->Application->GetVar('grid'));
}
}
if ( $event->redirect === false ) {
$object->SetError('ImportFile', $result);
$event->status = kEvent::erFAIL;
}
}
/**
* Performs one CSV import step
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnCSVImportStep(kEvent $event)
{
/** @var kCSVHelper $import_helper */
$import_helper = $this->Application->recallObject('CSVHelper');
$import_helper->ImportStep();
$event->status = kEvent::erSTOP;
}
/**
* Shows unit config filename, where requested prefix is defined
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnCheckPrefixConfig(kEvent $event)
{
$prefix = $this->Application->GetVar('config_prefix');
$config_file = $this->Application->UnitConfigReader->prefixFiles[$prefix];
$this->Application->InitParser();
ob_start();
echo $this->Application->ParseBlock(Array('name' => 'incs/header', 'body_properties' => 'style="background-color: #E7E7E7; margin: 8px;"'));
?>
<script type="text/javascript">
set_window_title('Unit Config of "<?php echo $prefix; ?>" prefix');
</script>
<a href="javascript:window_close();">Close Window</a><br /><br />
<strong>Prefix:</strong> <?php echo $prefix; ?><br />
<strong>Unit Config:</strong> <?php echo $GLOBALS['debugger']->highlightString($config_file); ?><br />
<br /><a href="javascript:window_close();">Close Window</a><br />
<?php
echo $this->Application->ParseBlock(Array ('name' => 'incs/footer'));
echo ob_get_clean();
$event->status = kEvent::erSTOP;
}
/**
* Deletes temp tables, when user closes window using "x" button in top right corner
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnDropTempTablesByWID(kEvent $event)
{
- $sid = $this->Application->GetSID();
+ $sid = $this->Application->GetSID(Session::PURPOSE_REFERENCE);
$wid = $this->Application->GetVar('m_wid');
$tables = $this->Conn->GetCol('SHOW TABLES');
$mask_edit_table = '/' . TABLE_PREFIX . 'ses_' . $sid . '_' . $wid . '_edit_(.*)$/';
foreach ($tables as $table) {
if ( preg_match($mask_edit_table, $table, $rets) ) {
$this->Conn->Query('DROP TABLE IF EXISTS ' . $table);
}
}
echo 'OK';
$event->status = kEvent::erSTOP;
}
/**
* Backup all data
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnBackup(kEvent $event)
{
/** @var BackupHelper $backup_helper */
$backup_helper = $this->Application->recallObject('BackupHelper');
if ( !$backup_helper->initBackup() ) {
$event->status = kEvent::erFAIL;
}
$event->redirect = 'tools/backup2';
}
/**
* Perform next backup step
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnBackupProgress(kEvent $event)
{
/** @var BackupHelper $backup_helper */
$backup_helper = $this->Application->recallObject('BackupHelper');
$done_percent = $backup_helper->performBackup();
if ( $done_percent == 100 ) {
$event->redirect = 'tools/backup3';
return;
}
$event->status = kEvent::erSTOP;
echo $done_percent;
}
/**
* Stops Backup & redirect to Backup template
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnBackupCancel(kEvent $event)
{
$event->redirect = 'tools/backup1';
}
/**
* Starts restore process
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnRestore(kEvent $event)
{
/** @var BackupHelper $backup_helper */
$backup_helper = $this->Application->recallObject('BackupHelper');
$backup_helper->initRestore();
$event->redirect = 'tools/restore3';
}
/**
* Performs next restore step
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnRestoreProgress(kEvent $event)
{
/** @var BackupHelper $backup_helper */
$backup_helper = $this->Application->recallObject('BackupHelper');
$done_percent = $backup_helper->performRestore();
if ( $done_percent == BackupHelper::SQL_ERROR_DURING_RESTORE ) {
$event->redirect = 'tools/restore4';
}
elseif ( $done_percent == BackupHelper::FAILED_READING_BACKUP_FILE ) {
$this->Application->StoreVar('adm.restore_error', 'File read error');
$event->redirect = 'tools/restore4';
}
elseif ( $done_percent == 100 ) {
$backup_helper->replaceRestoredFiles();
$this->Application->StoreVar('adm.restore_success', 1);
$event->redirect = 'tools/restore4';
}
else {
$event->status = kEvent::erSTOP;
echo $done_percent;
}
}
/**
* Stops Restore & redirect to Restore template
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnRestoreCancel(kEvent $event)
{
$event->redirect = 'tools/restore1';
}
/**
* Deletes one backup file
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnDeleteBackup(kEvent $event)
{
/** @var BackupHelper $backup_helper */
$backup_helper = $this->Application->recallObject('BackupHelper');
$backup_helper->delete();
}
/**
* Starts restore process
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnSqlQuery(kEvent $event)
{
$sql = $this->Application->GetVar('sql');
if ( $sql ) {
$start = microtime(true);
$result = $this->Conn->Query($sql);
$this->Application->SetVar('sql_time', round(microtime(true) - $start, 7));
if ( $result && is_array($result) ) {
$this->Application->SetVar('sql_has_rows', 1);
$this->Application->SetVar('sql_rows', serialize($result));
}
$check_sql = trim(strtolower($sql));
if ( preg_match('/^(insert|update|replace|delete)/', $check_sql) ) {
$this->Application->SetVar('sql_has_affected', 1);
$this->Application->SetVar('sql_affected', $this->Conn->getAffectedRows());
}
}
$this->Application->SetVar('query_status', 1);
$event->status = kEvent::erFAIL;
}
/**
* Occurs after unit config cache was successfully rebuilt
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnAfterCacheRebuild(kEvent $event)
{
}
/**
* Removes "Community -> Groups" section when it is not allowed
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnAfterConfigRead(kEvent $event)
{
parent::OnAfterConfigRead($event);
$section_adjustments = $this->Application->getUnitOption($event->Prefix, 'SectionAdjustments', Array());
if ( !$this->Application->ConfigValue('AdvancedUserManagement') ) {
$section_adjustments['in-portal:user_groups'] = 'remove';
}
$section_adjustments['in-portal:root'] = Array (
'label' => $this->Application->ConfigValue('Site_Name')
);
$this->Application->setUnitOption($event->Prefix, 'SectionAdjustments', $section_adjustments);
}
/**
* Saves menu (tree) frame width
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnSaveMenuFrameWidth(kEvent $event)
{
$event->status = kEvent::erSTOP;
if ( !$this->Application->ConfigValue('ResizableFrames') ) {
return;
}
$this->Application->StorePersistentVar('MenuFrameWidth', (int)$this->Application->GetVar('width'));
}
/**
* Retrieves data from memory cache
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnMemoryCacheGet(kEvent $event)
{
$event->status = kEvent::erSTOP;
$ret = Array ('message' => '', 'code' => 0); // 0 - ok, > 0 - error
$key = $this->Application->GetVar('key');
if ( !$key ) {
$ret['code'] = 1;
$ret['message'] = 'Key name missing';
}
else {
$value = $this->Application->getCache($key);
$ret['value'] =& $value;
$ret['size'] = is_string($value) ? kUtil::formatSize(strlen($value)) : '?';
$ret['type'] = gettype($value);
if ( kUtil::IsSerialized($value) ) {
$value = unserialize($value);
}
if ( is_array($value) ) {
$ret['value'] = print_r($value, true);
}
if ( $ret['value'] === false ) {
$ret['code'] = 2;
$ret['message'] = 'Key "' . $key . '" doesn\'t exist';
}
}
/** @var JSONHelper $json_helper */
$json_helper = $this->Application->recallObject('JSONHelper');
echo $json_helper->encode($ret);
}
/**
* Retrieves data from memory cache
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnMemoryCacheSet(kEvent $event)
{
$event->status = kEvent::erSTOP;
$ret = Array ('message' => '', 'code' => 0); // 0 - ok, > 0 - error
$key = $this->Application->GetVar('key');
if ( !$key ) {
$ret['code'] = 1;
$ret['message'] = 'Key name missing';
}
else {
$value = $this->Application->GetVar('value');
$res = $this->Application->setCache($key, $value);
$ret['result'] = $res ? 'OK' : 'FAILED';
}
/** @var JSONHelper $json_helper */
$json_helper = $this->Application->recallObject('JSONHelper');
echo $json_helper->encode($ret);
}
/**
* Deploy changes
*
* Usage: "php tools/run_event.php adm:OnDeploy b674006f3edb1d9cd4d838c150b0567d"
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnDeploy(kEvent $event)
{
$this->_deploymentAction($event);
}
/**
* Synchronizes database revisions from "project_upgrades.sql" file
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnSynchronizeDBRevisions(kEvent $event)
{
$this->_deploymentAction($event, true);
}
/**
* Common code to invoke deployment helper
*
* @param kEvent $event
* @param bool $dry_run
* @return void
* @access protected
*/
protected function _deploymentAction(kEvent $event, $dry_run = false)
{
/** @var DeploymentHelper $deployment_helper */
$deployment_helper = $this->Application->recallObject('DeploymentHelper');
$deployment_helper->setEvent($event);
if ( $deployment_helper->deployAll($dry_run) ) {
$event->SetRedirectParam('action_completed', 1);
if ( !$deployment_helper->isCommandLine ) {
// browser invocation -> don't perform redirect
$event->redirect = false;
// no redirect, but deployment succeeded - set redirect params directly
foreach ($event->getRedirectParams() as $param_name => $param_value) {
$this->Application->SetVar($param_name, $param_value);
}
}
}
else {
$event->status = kEvent::erFAIL;
}
}
/**
* [SCHEDULED TASK]
- * 1. Delete all Debug files from system/.restricted folder (format debug_@977827436@.txt)
+ * 1. Delete all Debug files from system/.restricted folder (format debug_@f353wfsds43g5...@.txt)
* 2. Run MySQL OPTIMIZE SQL one by one on all In-Portal tables (found by prefix).
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnOptimizePerformance(kEvent $event)
{
$start_time = adodb_mktime();
$sql = 'SELECT SessionKey
FROM ' . TABLE_PREFIX . 'UserSessions
WHERE LastAccessed > ' . $start_time;
$active_sessions = array_flip($this->Conn->GetCol($sql));
$files = scandir(RESTRICTED);
$file_path = RESTRICTED . '/';
- foreach ($files AS $file_name) {
- if ( !preg_match('#^debug_@([0-9]{9})@.txt$#', $file_name, $matches) ) {
- // not debug file
+ foreach ( $files as $file_name ) {
+ if ( !preg_match('#^debug_@([^@]+)@.txt$#', $file_name, $matches) ) {
+ // Not debug file.
continue;
}
$sid = $matches[1];
if ( isset($active_sessions[$sid]) || (filemtime($file_path . $file_name) > $start_time) ) {
// debug file belongs to an active session
// debug file is recently created (after sessions snapshot)
continue;
}
unlink($file_path . $file_name);
}
$system_tables = $this->Conn->GetCol('SHOW TABLES LIKE "' . TABLE_PREFIX . '%"');
foreach ($system_tables AS $table_name) {
$this->Conn->Query('OPTIMIZE TABLE ' . $table_name);
}
}
/**
* Returns popup size (by template), if not cached, then parse template to get value
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnGetPopupSize(kEvent $event)
{
$event->status = kEvent::erSTOP;
if ( $this->Application->GetVar('ajax') != 'yes' ) {
return;
}
$t = $this->Application->GetVar('template_name');
$sql = 'SELECT *
FROM ' . TABLE_PREFIX . 'PopupSizes
WHERE TemplateName = ' . $this->Conn->qstr($t);
$popup_info = $this->Conn->GetRow($sql);
$this->Application->setContentType('text/plain');
if ( !$popup_info ) {
// dies when SetPopupSize tag found & in ajax request
$this->Application->InitParser();
$this->Application->ParseBlock(Array ('name' => $t));
// tag SetPopupSize not found in template -> use default size
echo '750x400';
}
else {
echo $popup_info['PopupWidth'] . 'x' . $popup_info['PopupHeight'];
}
}
/**
* Writes HTTP request to System Log
*
* @param kEvent $event
* @return void
* @access public
*/
public function OnLogHttpRequest(kEvent $event)
{
if ( defined('DBG_REQUEST_LOG') && DBG_REQUEST_LOG && $this->Application->LoggedIn() ) {
$log = $this->Application->log('HTTP_REQUEST')->addRequestData();
if ( !$log->write() ) {
trigger_error('Unable to log Http Request due disabled "System Log"', E_USER_WARNING);
}
}
}
/**
* Purges expired database cache entries.
*
* @param kEvent $event Event.
*
* @return void
*/
protected function OnPurgeExpiredDatabaseCacheScheduledTask(kEvent $event)
{
$sql = 'DELETE FROM ' . TABLE_PREFIX . 'SystemCache
WHERE LifeTime > 0 AND Cached + LifeTime < ' . time();
$this->Conn->Query($sql);
}
/**
* Populates URL unit cache
*
* @param kEvent $event Event.
*
* @return void
*/
protected function OnPopulateUrlUnitCacheScheduledTask(kEvent $event)
{
$sql = 'SELECT DISTINCT Prefixes
FROM ' . TABLE_PREFIX . 'CachedUrls';
$urls = $this->Conn->GetColIterator($sql);
$prefixes = array();
foreach ( $urls as $url_prefixes ) {
$url_prefixes = explode('|', trim($url_prefixes, '|'));
foreach ( $url_prefixes as $url_prefix ) {
$url_prefix = explode(':', $url_prefix);
$prefixes[$url_prefix[0]] = 1;
}
}
if ( $this->Application->isCachingType(CACHING_TYPE_MEMORY) ) {
$this->Application->setCache('cached_urls_unit_prefixes', array_keys($prefixes), 3600);
}
else {
$this->Application->setDBCache('cached_urls_unit_prefixes', serialize(array_keys($prefixes)), 3600);
}
}
/**
* Deletes stuck semaphore records.
*
* @param kEvent $event Event.
*
* @return void
*/
protected function OnDeleteStuckSemaphoresScheduledTask(kEvent $event)
{
$semaphore_lifetime = $this->Application->ConfigValue('SemaphoreLifetimeInSeconds');
$sql = 'SELECT *
FROM ' . TABLE_PREFIX . 'Semaphores
WHERE Timestamp < ' . strtotime('-' . $semaphore_lifetime . ' seconds');
$stuck_semaphores = $this->Conn->Query($sql, 'SemaphoreId');
if ( !$stuck_semaphores ) {
return;
}
/** @var LanguagesItem $language */
$language = $this->Application->recallObject('lang.current', null, array('skip_autoload' => true));
$date_format = $language->GetDBField('DateFormat') . ' ' . $language->GetDBField('TimeFormat');
foreach ( $stuck_semaphores as $semaphore_id => $semaphore_data ) {
$log = $this->Application->log('Stuck semaphore detected (unit: ' . $semaphore_data['MainPrefix'] . ')');
$log->setLogLevel(kLogger::LL_ERROR);
$log->addTrace(unserialize($semaphore_data['Backtrace']));
$log->setUserData(implode(PHP_EOL, array(
'Main Prefix: ' . $semaphore_data['MainPrefix'],
'Main IDs: ' . $semaphore_data['MainIDs'],
'Created On: ' . date($date_format, $semaphore_data['Timestamp']),
'Deleted On: ' . date($date_format),
)));
$log->setLogField('LogHostname', $semaphore_data['Hostname']);
$log->setLogField('LogRequestSource', 1); // Web.
$log->setLogField('LogInterface', kLogger::LI_ADMIN);
$log->setLogField('LogRequestURI', $semaphore_data['RequestURI']);
$log->setLogField('LogUserId', $semaphore_data['UserId']);
$log->setLogField('IpAddress', $semaphore_data['IpAddress']);
$log->setLogField('LogSessionKey', $semaphore_data['SessionKey']);
$log->write();
$sql = 'DELETE FROM ' . TABLE_PREFIX . 'Semaphores
WHERE SemaphoreId = ' . $semaphore_id;
$this->Conn->Query($sql);
}
}
}
class UnitConfigDecorator {
var $parentPath = Array ();
/**
* Decorates given array
*
* @param Array $var
* @param int $level
* @return string
*/
public function decorate($var, $level = 0)
{
$ret = '';
$deep_level = count($this->parentPath);
if ( $deep_level && ($this->parentPath[0] == 'Fields') ) {
$expand = $level < 2;
}
elseif ( $deep_level && ($this->parentPath[0] == 'Grids') ) {
if ( $deep_level == 3 && $this->parentPath[2] == 'Icons' ) {
$expand = false;
}
else {
$expand = $level < 4;
}
}
else {
$expand = $level == 0;
}
if ( is_array($var) ) {
$ret .= 'array(';
$prepend = $expand ? "\n" . str_repeat("\t", $level + 1) : '';
foreach ($var as $key => $value) {
array_push($this->parentPath, $key);
$ret .= $prepend . (is_string($key) ? "'" . $key . "'" : $key) . ' => ' . $this->decorate($value, $level + 1);
$ret .= ',' . ($expand ? '' : ' ');
array_pop($this->parentPath);
}
$prepend = $expand ? "\n" . str_repeat("\t", $level) : '';
if ( !$expand ) {
$ret = rtrim($ret, ', ');
}
$ret .= $prepend . ')';
}
else {
if ( is_null($var) ) {
$ret = 'null';
}
elseif ( is_string($var) ) {
$ret = "'" . $var . "'";
}
else {
$ret = $var;
}
}
return $ret;
}
}
Index: branches/5.2.x/core/admin_templates/logs/session_logs/session_log_list.tpl
===================================================================
--- branches/5.2.x/core/admin_templates/logs/session_logs/session_log_list.tpl (revision 16796)
+++ branches/5.2.x/core/admin_templates/logs/session_logs/session_log_list.tpl (revision 16797)
@@ -1,86 +1,90 @@
<inp2:m_include t="incs/header" />
<inp2:m_RenderElement name="combined_header" section="in-portal:session_logs" prefix="session-log" title_preset="session_log_list" pagination="1"/>
<!-- ToolBar -->
<table class="toolbar" height="30" cellspacing="0" cellpadding="0" width="100%" border="0">
<tbody>
<tr>
<td>
<table width="100%" cellpadding="0" cellspacing="0">
<tr>
<td>
<script type="text/javascript">
a_toolbar = new ToolBar();
function edit() {
}
a_toolbar.AddButton(
new ToolBarButton(
'delete',
'<inp2:m_phrase label="la_ToolTip_Delete" escape="1"/>',
function() {
std_delete_items('session-log')
}
)
);
a_toolbar.AddButton( new ToolBarSeparator('sep1') );
a_toolbar.AddButton(
new ToolBarButton(
'view',
'<inp2:m_phrase label="la_ToolTip_View" escape="1"/>',
function(id) {
show_viewmenu(a_toolbar,'view');
}
)
);
a_toolbar.Render();
</script>
</td>
<inp2:m_RenderElement name="search_main_toolbar" prefix="session-log" grid="Default"/>
</tr>
</table>
</td>
</tr>
</tbody>
</table>
<style type="text/css">
tr.row-active td {
background-color: #EAFFDC;
}
tr.row-expired td {
color: #555;
}
+
+ tr.grid-data-row td.SessionKey {
+ text-overflow: ellipsis;
+ }
</style>
<inp2:m_DefineElement name="row_class">
<inp2:m_if check="FieldEquals" field="Status" value="0">
row-active
<inp2:m_else/>
<inp2:m_if check="FieldEquals" field="Status" value="2">
row-expired
</inp2:m_if>
</inp2:m_if>
</inp2:m_DefineElement>
<inp2:m_DefineElement name="affected_td">
<inp2:m_if check="Field" name="AffectedItems">
<inp2:Field name="SessionLogId" result_to_var="sessionlog_id"/>
<a href="<inp2:m_t t='logs/change_logs/change_log_list' pass='m,change-log' grid_name='Default' custom_filters[change-log][Default][SessionLogId][range][from]='$sessionlog_id' custom_filters[change-log][Default][SessionLogId][range][to]='' change-log_event='OnSearch'/>"><inp2:Field name="AffectedItems"/></a>
<inp2:m_else/>
<inp2:Field name="AffectedItems"/>
</inp2:m_if>
</inp2:m_DefineElement>
<inp2:m_RenderElement name="grid" PrefixSpecial="session-log" IdField="SessionLogId" grid="Default" row_class_render_as="row_class"/>
<script type="text/javascript">
Grids['session-log'].SetDependantToolbarButtons( new Array('delete') );
</script>
-<inp2:m_include t="incs/footer"/>
\ No newline at end of file
+<inp2:m_include t="incs/footer"/>
Index: branches/5.2.x/core/admin_templates/logs/system_logs/system_log_list.tpl
===================================================================
--- branches/5.2.x/core/admin_templates/logs/system_logs/system_log_list.tpl (revision 16796)
+++ branches/5.2.x/core/admin_templates/logs/system_logs/system_log_list.tpl (revision 16797)
@@ -1,111 +1,115 @@
<inp2:m_include t="incs/header" />
<inp2:m_RenderElement name="combined_header" section="in-portal:system_logs" prefix="system-log" title_preset="system_log_list" pagination="1"/>
<!-- ToolBar -->
<table class="toolbar" height="30" cellspacing="0" cellpadding="0" width="100%" border="0">
<tbody>
<tr>
<td>
<table width="100%" cellpadding="0" cellspacing="0">
<tr>
<td>
<script type="text/javascript">
a_toolbar = new ToolBar();
function edit() {
std_edit_temp_item('system-log', 'logs/system_logs/system_log_edit');
}
a_toolbar.AddButton(
new ToolBarButton(
'edit',
'<inp2:m_phrase label="la_ToolTip_ViewDetails" escape="1"/>::<inp2:m_phrase label="la_ToolTip_Details" escape="1"/>',
edit
)
);
a_toolbar.AddButton(
new ToolBarButton(
'delete',
'<inp2:m_phrase label="la_ToolTip_Delete" escape="1"/>',
function() {
std_delete_items('system-log')
}
)
);
a_toolbar.AddButton(
new ToolBarButton(
'reset',
'<inp2:m_phrase label="la_ToolTip_DeleteAll" escape="1"/>',
function() {
if (inpConfirm('<inp2:m_Phrase name="la_Delete_Confirm" escape="1"/>')) {
submit_event('system-log', 'OnDeleteAll');
}
}
)
);
a_toolbar.AddButton( new ToolBarSeparator('sep1') );
a_toolbar.AddButton(
new ToolBarButton(
'view',
'<inp2:m_phrase label="la_ToolTip_View" escape="1"/>',
function(id) {
show_viewmenu(a_toolbar,'view');
}
)
);
a_toolbar.Render();
</script>
</td>
<inp2:m_RenderElement name="search_main_toolbar" prefix="system-log" grid="Default"/>
</tr>
</table>
</td>
</tr>
</tbody>
</table>
<style type="text/css">
.log_backtrace {
margin: 0;
padding-left: 25px;
font-size: 11px;
}
+
+ tr.grid-data-row td.LogSessionKey {
+ text-overflow: ellipsis;
+ }
</style>
<inp2:m_DefineElement name="grid_filename_td">
<inp2:Filename/>
</inp2:m_DefineElement>
<inp2:m_DefineElement name="grid_uri_td">
<inp2:RequestURI/>
</inp2:m_DefineElement>
<inp2:m_DefineElement name="grid_memory_td">
<span title="<inp2:Field name='$field'/> bytes"><inp2:MemoryUsage/></span>
</inp2:m_DefineElement>
<inp2:m_DefineElement name="backtrace_element">
<li>
<inp2:m_Phrase name="la_LogBacktraceFunction"/>: <inp2:m_Param name="file_info"/>
</li>
</inp2:m_DefineElement>
<inp2:m_DefineElement name="grid_backtrace_td">
<ol class="log_backtrace">
<inp2:PrintBacktrace render_as="backtrace_element"/>
</ol>
</inp2:m_DefineElement>
<inp2:m_RenderElement name="grid" PrefixSpecial="system-log" IdField="LogId" grid="Default"/>
<script type="text/javascript">
Grids['system-log'].SetDependantToolbarButtons( new Array('edit', 'delete') );
</script>
<inp2:m_include t="incs/footer"/>
Index: branches/5.2.x/core/install/install_schema.sql
===================================================================
--- branches/5.2.x/core/install/install_schema.sql (revision 16796)
+++ branches/5.2.x/core/install/install_schema.sql (revision 16797)
@@ -1,1449 +1,1452 @@
CREATE TABLE CategoryPermissionsConfig (
PermissionConfigId int(11) NOT NULL auto_increment,
PermissionName varchar(255) NOT NULL default '',
Description varchar(255) NOT NULL default '',
ModuleId varchar(20) NOT NULL default '0',
IsSystem tinyint(1) NOT NULL DEFAULT '0',
PRIMARY KEY (PermissionConfigId),
KEY PermissionName (PermissionName)
);
CREATE TABLE Permissions (
PermissionId int(11) NOT NULL auto_increment,
Permission varchar(255) NOT NULL default '',
GroupId int(11) default '0',
PermissionValue int(11) NOT NULL default '0',
`Type` tinyint(4) NOT NULL default '0',
CatId int(11) NOT NULL default '0',
PRIMARY KEY (PermissionId),
UNIQUE KEY PermIndex (Permission,GroupId,CatId,`Type`)
);
CREATE TABLE CustomFields (
CustomFieldId int(11) NOT NULL auto_increment,
`Type` int(11) NOT NULL default '0',
FieldName varchar(255) NOT NULL default '',
FieldLabel varchar(40) default NULL,
MultiLingual tinyint(3) unsigned NOT NULL default '1',
Heading varchar(60) default NULL,
Prompt varchar(60) default NULL,
ElementType varchar(50) NOT NULL default '',
ValueList text,
DefaultValue varchar(255) NOT NULL default '',
DisplayOrder int(11) NOT NULL default '0',
OnGeneralTab tinyint(4) NOT NULL default '0',
IsSystem tinyint(3) unsigned NOT NULL default '0',
IsRequired tinyint(3) unsigned NOT NULL default '0',
PRIMARY KEY (CustomFieldId),
KEY `Type` (`Type`),
KEY MultiLingual (MultiLingual),
KEY DisplayOrder (DisplayOrder),
KEY OnGeneralTab (OnGeneralTab),
KEY IsSystem (IsSystem),
KEY DefaultValue (DefaultValue)
);
CREATE TABLE SystemSettings (
VariableId int(11) NOT NULL AUTO_INCREMENT,
VariableName varchar(255) NOT NULL DEFAULT '',
VariableValue text,
ModuleOwner varchar(20) DEFAULT 'In-Portal',
Section varchar(255) NOT NULL DEFAULT '',
Heading varchar(255) NOT NULL DEFAULT '',
Prompt varchar(255) NOT NULL DEFAULT '',
ElementType varchar(255) NOT NULL DEFAULT '',
Validation text,
ValueList text,
DisplayOrder double NOT NULL DEFAULT '0',
GroupDisplayOrder double NOT NULL DEFAULT '0',
`Install` int(11) NOT NULL DEFAULT '1',
HintLabel varchar(255) DEFAULT NULL,
PRIMARY KEY (VariableId),
UNIQUE KEY VariableName (VariableName),
KEY DisplayOrder (DisplayOrder),
KEY GroupDisplayOrder (GroupDisplayOrder),
KEY `Install` (`Install`),
KEY HintLabel (HintLabel)
);
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 DEFAULT NULL,
SendRetries int(10) unsigned NOT NULL DEFAULT '0',
LastSendRetry int(10) unsigned DEFAULT NULL,
MailingId int(10) unsigned NOT NULL DEFAULT '0',
LogData longtext,
PRIMARY KEY (EmailQueueId),
KEY LastSendRetry (LastSendRetry),
KEY SendRetries (SendRetries),
KEY MailingId (MailingId)
);
CREATE TABLE EmailTemplates (
TemplateId int(11) NOT NULL AUTO_INCREMENT,
TemplateName varchar(40) NOT NULL DEFAULT '',
ReplacementTags text,
AllowChangingSender tinyint(4) NOT NULL DEFAULT '0',
CustomSender tinyint(4) NOT NULL DEFAULT '0',
SenderName varchar(255) NOT NULL DEFAULT '',
SenderAddressType tinyint(4) NOT NULL DEFAULT '0',
SenderAddress varchar(255) NOT NULL DEFAULT '',
AllowChangingRecipient tinyint(4) NOT NULL DEFAULT '0',
CustomRecipient tinyint(4) NOT NULL DEFAULT '0',
Recipients text,
l1_Subject text,
l2_Subject text,
l3_Subject text,
l4_Subject text,
l5_Subject text,
l1_HtmlBody longtext,
l2_HtmlBody longtext,
l3_HtmlBody longtext,
l4_HtmlBody longtext,
l5_HtmlBody longtext,
l1_PlainTextBody longtext,
l2_PlainTextBody longtext,
l3_PlainTextBody longtext,
l4_PlainTextBody longtext,
l5_PlainTextBody longtext,
Headers text,
Enabled int(11) NOT NULL DEFAULT '1',
FrontEndOnly tinyint(3) unsigned NOT NULL DEFAULT '0',
Module varchar(40) NOT NULL DEFAULT 'Core',
Description text,
`Type` int(11) NOT NULL DEFAULT '0',
LastChanged int(10) unsigned DEFAULT NULL,
BindToSystemEvent varchar(255) NOT NULL DEFAULT '',
PRIMARY KEY (TemplateId),
KEY `Type` (`Type`),
KEY Enabled (Enabled),
KEY `Event` (TemplateName),
KEY FrontEndOnly (FrontEndOnly),
KEY AllowChangingSender (AllowChangingSender),
KEY CustomSender (CustomSender),
KEY SenderAddressType (SenderAddressType),
KEY AllowChangingRecipient (AllowChangingRecipient),
KEY CustomRecipient (CustomRecipient),
KEY l1_HtmlBody (l1_HtmlBody(5)),
KEY l2_HtmlBody (l2_HtmlBody(5)),
KEY l3_HtmlBody (l3_HtmlBody(5)),
KEY l4_HtmlBody (l4_HtmlBody(5)),
KEY l5_HtmlBody (l5_HtmlBody(5)),
KEY l1_PlainTextBody (l1_PlainTextBody(5)),
KEY l2_PlainTextBody (l2_PlainTextBody(5)),
KEY l3_PlainTextBody (l3_PlainTextBody(5)),
KEY l4_PlainTextBody (l4_PlainTextBody(5)),
KEY l5_PlainTextBody (l5_PlainTextBody(5))
);
CREATE TABLE SystemEventSubscriptions (
SubscriptionId int(11) NOT NULL AUTO_INCREMENT,
EmailTemplateId int(11) DEFAULT NULL,
SubscriberEmail varchar(255) NOT NULL DEFAULT '',
UserId int(11) DEFAULT NULL,
CategoryId int(11) DEFAULT NULL,
IncludeSublevels tinyint(4) NOT NULL DEFAULT '1',
ItemId int(11) DEFAULT NULL,
ParentItemId int(11) DEFAULT NULL,
SubscribedOn int(11) DEFAULT NULL,
PRIMARY KEY (SubscriptionId),
KEY EmailEventId (EmailTemplateId)
);
CREATE TABLE IdGenerator (
lastid int(11) default NULL
);
CREATE TABLE Languages (
LanguageId int(11) NOT NULL AUTO_INCREMENT,
PackName varchar(40) NOT NULL DEFAULT '',
LocalName varchar(40) NOT NULL DEFAULT '',
Enabled int(11) NOT NULL DEFAULT '1',
PrimaryLang int(11) NOT NULL DEFAULT '0',
AdminInterfaceLang tinyint(3) unsigned NOT NULL DEFAULT '0',
Priority int(11) NOT NULL DEFAULT '0',
IconURL varchar(255) DEFAULT NULL,
IconDisabledURL varchar(255) DEFAULT NULL,
DateFormat varchar(50) NOT NULL DEFAULT 'm/d/Y',
ShortDateFormat varchar(255) NOT NULL DEFAULT 'm/d',
TimeFormat varchar(50) NOT NULL DEFAULT 'g:i:s A',
ShortTimeFormat varchar(255) NOT NULL DEFAULT 'g:i A',
InputDateFormat varchar(50) NOT NULL DEFAULT 'm/d/Y',
InputTimeFormat varchar(50) NOT NULL DEFAULT 'g:i:s A',
DecimalPoint varchar(10) NOT NULL DEFAULT '.',
ThousandSep varchar(10) NOT NULL DEFAULT '',
`Charset` varchar(20) NOT NULL DEFAULT 'utf-8',
UnitSystem tinyint(4) NOT NULL DEFAULT '1',
FilenameReplacements text,
Locale varchar(10) NOT NULL DEFAULT 'en-US',
UserDocsUrl varchar(255) NOT NULL DEFAULT '',
SynchronizationModes varchar(255) NOT NULL DEFAULT '',
HtmlEmailTemplate text,
TextEmailTemplate text,
PRIMARY KEY (LanguageId),
KEY Enabled (Enabled),
KEY PrimaryLang (PrimaryLang),
KEY AdminInterfaceLang (AdminInterfaceLang),
KEY Priority (Priority)
);
CREATE TABLE Modules (
`Name` varchar(255) NOT NULL DEFAULT '',
Path varchar(255) NOT NULL DEFAULT '',
ClassNamespace varchar(255) NOT NULL DEFAULT '',
Var varchar(100) NOT NULL DEFAULT '',
Version varchar(10) NOT NULL DEFAULT '0.0.0',
Loaded tinyint(4) NOT NULL DEFAULT '1',
LoadOrder tinyint(4) NOT NULL DEFAULT '0',
TemplatePath varchar(255) NOT NULL DEFAULT '',
RootCat int(11) NOT NULL DEFAULT '0',
BuildDate int(10) unsigned DEFAULT NULL,
AppliedDBRevisions text,
PRIMARY KEY (`Name`),
KEY Loaded (Loaded),
KEY LoadOrder (LoadOrder)
);
CREATE TABLE UserPersistentSessionData (
VariableId bigint(20) NOT NULL AUTO_INCREMENT,
PortalUserId int(11) NOT NULL DEFAULT '0',
VariableName varchar(255) NOT NULL DEFAULT '',
VariableValue text,
PRIMARY KEY (VariableId),
KEY UserId (PortalUserId),
KEY VariableName (VariableName)
);
CREATE TABLE LanguageLabels (
PhraseId int(11) NOT NULL AUTO_INCREMENT,
Phrase varchar(255) NOT NULL DEFAULT '',
PhraseKey varchar(255) NOT NULL DEFAULT '',
l1_Translation text,
l2_Translation text,
l3_Translation text,
l4_Translation text,
l5_Translation text,
l1_HintTranslation text,
l2_HintTranslation text,
l3_HintTranslation text,
l4_HintTranslation text,
l5_HintTranslation text,
l1_ColumnTranslation text,
l2_ColumnTranslation text,
l3_ColumnTranslation text,
l4_ColumnTranslation text,
l5_ColumnTranslation text,
PhraseType int(11) NOT NULL DEFAULT '0',
LastChanged int(10) unsigned DEFAULT NULL,
LastChangeIP varchar(15) NOT NULL DEFAULT '',
Module varchar(30) NOT NULL DEFAULT 'In-Portal',
PRIMARY KEY (PhraseId),
KEY Phrase_Index (Phrase),
KEY PhraseKey (PhraseKey),
KEY l1_Translation (l1_Translation(5)),
KEY l1_HintTranslation (l1_HintTranslation(5)),
KEY l1_ColumnTranslation (l1_ColumnTranslation(5))
);
CREATE TABLE PhraseCache (
Template varchar(40) NOT NULL DEFAULT '',
PhraseList text,
CacheDate int(11) NOT NULL DEFAULT '0',
ThemeId int(11) NOT NULL DEFAULT '0',
StylesheetId int(10) unsigned NOT NULL DEFAULT '0',
ConfigVariables text,
PRIMARY KEY (Template),
KEY CacheDate (CacheDate),
KEY ThemeId (ThemeId),
KEY StylesheetId (StylesheetId)
);
CREATE TABLE UserGroups (
GroupId int(11) NOT NULL AUTO_INCREMENT,
`Name` varchar(255) NOT NULL DEFAULT '',
Description varchar(255) DEFAULT NULL,
CreatedOn int(10) unsigned DEFAULT NULL,
`System` tinyint(4) NOT NULL DEFAULT '0',
Personal tinyint(4) NOT NULL DEFAULT '0',
Enabled tinyint(4) NOT NULL DEFAULT '1',
FrontRegistration tinyint(3) unsigned NOT NULL DEFAULT '0',
IPRestrictions text,
PRIMARY KEY (GroupId),
UNIQUE KEY `Name` (`Name`),
KEY Personal (Personal),
KEY Enabled (Enabled),
KEY CreatedOn (CreatedOn)
);
CREATE TABLE Users (
PortalUserId int(11) NOT NULL AUTO_INCREMENT,
Username varchar(255) NOT NULL DEFAULT '',
`Password` varchar(255) DEFAULT 'd41d8cd98f00b204e9800998ecf8427e',
PasswordHashingMethod tinyint(4) NOT NULL DEFAULT '3',
FirstName varchar(255) NOT NULL DEFAULT '',
LastName varchar(255) NOT NULL DEFAULT '',
Company varchar(255) NOT NULL DEFAULT '',
Email varchar(255) NOT NULL DEFAULT '',
PrevEmails text,
CreatedOn int(11) DEFAULT NULL,
Phone varchar(255) NOT NULL DEFAULT '',
Fax varchar(255) NOT NULL DEFAULT '',
Street varchar(255) NOT NULL DEFAULT '',
Street2 varchar(255) NOT NULL DEFAULT '',
City varchar(255) NOT NULL DEFAULT '',
State varchar(20) NOT NULL DEFAULT '',
Zip varchar(20) NOT NULL DEFAULT '',
Country varchar(20) NOT NULL DEFAULT '',
ResourceId int(11) NOT NULL DEFAULT '0',
`Status` tinyint(4) NOT NULL DEFAULT '1',
EmailVerified tinyint(4) NOT NULL,
Modified int(11) DEFAULT NULL,
dob int(11) DEFAULT NULL,
TimeZone varchar(255) NOT NULL DEFAULT '',
IPAddress varchar(15) NOT NULL DEFAULT '',
IsBanned tinyint(1) NOT NULL DEFAULT '0',
PwResetConfirm varchar(255) NOT NULL DEFAULT '',
PwRequestTime int(11) unsigned DEFAULT NULL,
FrontLanguage int(11) DEFAULT NULL,
AdminLanguage int(11) DEFAULT NULL,
DisplayToPublic text,
UserType tinyint(4) NOT NULL,
PrimaryGroupId int(11) DEFAULT NULL,
OldStyleLogin tinyint(4) NOT NULL,
IPRestrictions text,
PRIMARY KEY (PortalUserId),
UNIQUE KEY ResourceId (ResourceId),
KEY CreatedOn (CreatedOn),
KEY `Status` (`Status`),
KEY Modified (Modified),
KEY dob (dob),
KEY IsBanned (IsBanned),
KEY UserType (UserType),
KEY Username (Username),
KEY Email (Email)
);
CREATE TABLE UserCustomData (
CustomDataId int(11) NOT NULL auto_increment,
ResourceId int(10) unsigned NOT NULL default '0',
KEY ResourceId (ResourceId),
PRIMARY KEY (CustomDataId)
);
CREATE TABLE UserSessionData (
- SessionKey varchar(50) NOT NULL DEFAULT '',
+ SessionId int unsigned NOT NULL DEFAULT '0',
VariableName varchar(255) NOT NULL DEFAULT '',
VariableValue longtext,
- PRIMARY KEY (SessionKey,VariableName),
- KEY SessionKey (SessionKey),
+ PRIMARY KEY (SessionId,VariableName),
+ KEY SessionId (SessionId),
KEY VariableName (VariableName)
);
CREATE TABLE Themes (
ThemeId int(11) NOT NULL AUTO_INCREMENT,
`Name` varchar(40) NOT NULL DEFAULT '',
Enabled int(11) NOT NULL DEFAULT '1',
Description varchar(255) DEFAULT NULL,
PrimaryTheme int(11) NOT NULL DEFAULT '0',
CacheTimeout int(11) NOT NULL DEFAULT '0',
StylesheetId int(10) unsigned NOT NULL DEFAULT '0',
LanguagePackInstalled tinyint(3) unsigned NOT NULL DEFAULT '0',
TemplateAliases text,
StylesheetFile varchar(255) NOT NULL DEFAULT '',
PRIMARY KEY (ThemeId),
KEY Enabled (Enabled),
KEY StylesheetId (StylesheetId),
KEY PrimaryTheme (PrimaryTheme),
KEY LanguagePackInstalled (LanguagePackInstalled)
);
CREATE TABLE ThemeFiles (
FileId int(11) NOT NULL AUTO_INCREMENT,
ThemeId int(11) NOT NULL DEFAULT '0',
FileName varchar(255) NOT NULL DEFAULT '',
FilePath varchar(255) NOT NULL DEFAULT '',
TemplateAlias varchar(255) NOT NULL DEFAULT '',
Description varchar(255) DEFAULT NULL,
FileType int(11) NOT NULL DEFAULT '0',
FileFound tinyint(3) unsigned NOT NULL DEFAULT '0',
FileMetaInfo text,
PRIMARY KEY (FileId),
KEY theme (ThemeId),
KEY FileName (FileName),
KEY FilePath (FilePath),
KEY FileFound (FileFound),
KEY TemplateAlias (TemplateAlias)
);
CREATE TABLE UserGroupRelations (
PortalUserId int(11) NOT NULL DEFAULT '0',
GroupId int(11) NOT NULL DEFAULT '0',
MembershipExpires int(10) unsigned DEFAULT NULL,
ExpirationReminderSent tinyint(4) NOT NULL DEFAULT '0',
PRIMARY KEY (PortalUserId,GroupId),
KEY GroupId (GroupId),
KEY MembershipExpires (MembershipExpires),
KEY ExpirationReminderSent (ExpirationReminderSent)
);
CREATE TABLE UserSessions (
- SessionKey int(10) unsigned NOT NULL DEFAULT '0',
+ SessionId int NOT NULL AUTO_INCREMENT,
+ SessionKey char(64) NOT NULL DEFAULT '',
LastAccessed int(10) unsigned NOT NULL DEFAULT '0',
PortalUserId int(11) NOT NULL DEFAULT '-2',
`Language` int(11) NOT NULL DEFAULT '1',
Theme int(11) NOT NULL DEFAULT '1',
GroupId int(11) NOT NULL DEFAULT '0',
IpAddress varchar(20) NOT NULL DEFAULT '0.0.0.0',
`Status` int(11) NOT NULL DEFAULT '1',
GroupList varchar(255) DEFAULT NULL,
TimeZone varchar(255) NOT NULL DEFAULT '',
BrowserSignature varchar(32) NOT NULL DEFAULT '',
- PRIMARY KEY (SessionKey),
+ PRIMARY KEY (SessionId),
+ UNIQUE KEY SessionKey (SessionKey) USING BTREE,
KEY UserId (PortalUserId),
KEY LastAccessed (LastAccessed),
KEY BrowserSignature (BrowserSignature)
);
CREATE TABLE EmailLog (
EmailLogId int(11) NOT NULL AUTO_INCREMENT,
`From` varchar(255) NOT NULL DEFAULT '',
`To` varchar(255) NOT NULL DEFAULT '',
OtherRecipients text,
`Subject` varchar(255) NOT NULL DEFAULT '',
HtmlBody longtext,
TextBody longtext,
SentOn int(11) DEFAULT NULL,
TemplateName varchar(255) NOT NULL DEFAULT '',
EventType tinyint(4) DEFAULT NULL,
EventParams text,
AccessKey varchar(32) NOT NULL DEFAULT '',
PRIMARY KEY (EmailLogId),
KEY `timestamp` (SentOn)
);
CREATE TABLE SystemLog (
LogId int(11) NOT NULL AUTO_INCREMENT,
LogUniqueId int(11) DEFAULT NULL,
LogLevel tinyint(4) NOT NULL DEFAULT '7',
LogType tinyint(4) NOT NULL DEFAULT '3',
LogCode int(11) DEFAULT NULL,
LogMessage longtext,
LogTimestamp int(11) DEFAULT NULL,
LogDate datetime DEFAULT NULL,
LogEventName varchar(100) NOT NULL DEFAULT '',
LogHostname varchar(255) NOT NULL DEFAULT '',
LogRequestSource tinyint(4) DEFAULT NULL,
LogRequestURI varchar(255) NOT NULL DEFAULT '',
LogRequestData longtext,
LogUserId int(11) DEFAULT NULL,
LogInterface tinyint(4) DEFAULT NULL,
IpAddress varchar(15) NOT NULL DEFAULT '',
- LogSessionKey int(11) DEFAULT NULL,
+ LogSessionKey char(64) NOT NULL DEFAULT '',
LogSessionData longtext,
LogBacktrace longtext,
LogSourceFilename varchar(255) NOT NULL DEFAULT '',
LogSourceFileLine int(11) DEFAULT NULL,
LogCodeFragment longtext,
LogCodeFragmentsRotated tinyint(4) NOT NULL DEFAULT '0',
LogProcessId bigint(20) unsigned DEFAULT NULL,
LogMemoryUsed bigint(20) unsigned NOT NULL,
LogUserData longtext NOT NULL,
LogNotificationStatus tinyint(4) NOT NULL DEFAULT '0',
PRIMARY KEY (LogId),
KEY LogLevel (LogLevel),
KEY LogType (LogType),
KEY LogNotificationStatus (LogNotificationStatus),
KEY `TIMESTAMP_CODE_FRAGMENTS_ROTATED` (`LogTimestamp`,`LogCodeFragmentsRotated`) USING BTREE
);
CREATE TABLE SystemCache (
VarName varchar(255) NOT NULL default '',
Data longtext,
Cached int(11) default NULL,
LifeTime int(11) NOT NULL default '-1',
PRIMARY KEY (VarName),
KEY Cached (Cached)
);
CREATE TABLE CountryStates (
CountryStateId int(11) NOT NULL AUTO_INCREMENT,
`Type` int(11) NOT NULL DEFAULT '1',
StateCountryId int(11) DEFAULT NULL,
l1_Name varchar(255) NOT NULL DEFAULT '',
l2_Name varchar(255) NOT NULL DEFAULT '',
l3_Name varchar(255) NOT NULL DEFAULT '',
l4_Name varchar(255) NOT NULL DEFAULT '',
l5_Name varchar(255) NOT NULL DEFAULT '',
IsoCode char(3) NOT NULL DEFAULT '',
ShortIsoCode char(2) DEFAULT NULL,
PRIMARY KEY (CountryStateId),
KEY `Type` (`Type`),
KEY StateCountryId (StateCountryId),
KEY l1_Name (l1_Name(5))
);
CREATE TABLE Categories (
CategoryId int(11) NOT NULL AUTO_INCREMENT,
`Type` int(11) NOT NULL DEFAULT '1',
SymLinkCategoryId int(10) unsigned DEFAULT NULL,
ParentId int(11) NOT NULL DEFAULT '0',
`Name` varchar(255) NOT NULL DEFAULT '',
l1_Name varchar(255) NOT NULL DEFAULT '',
l2_Name varchar(255) NOT NULL DEFAULT '',
l3_Name varchar(255) NOT NULL DEFAULT '',
l4_Name varchar(255) NOT NULL DEFAULT '',
l5_Name varchar(255) NOT NULL DEFAULT '',
Filename varchar(255) NOT NULL DEFAULT '',
AutomaticFilename tinyint(3) unsigned NOT NULL DEFAULT '1',
Description text,
l1_Description text,
l2_Description text,
l3_Description text,
l4_Description text,
l5_Description text,
CreatedOn int(11) DEFAULT NULL,
EditorsPick tinyint(4) NOT NULL DEFAULT '0',
`Status` tinyint(4) NOT NULL DEFAULT '1',
Priority int(11) NOT NULL DEFAULT '0',
MetaKeywords text,
CachedDescendantCatsQty int(11) NOT NULL DEFAULT '0',
CachedNavbar text,
l1_CachedNavbar text,
l2_CachedNavbar text,
l3_CachedNavbar text,
l4_CachedNavbar text,
l5_CachedNavbar text,
CreatedById int(11) DEFAULT NULL,
ResourceId int(11) DEFAULT NULL,
ParentPath text,
TreeLeft bigint(20) NOT NULL DEFAULT '0',
TreeRight bigint(20) NOT NULL DEFAULT '0',
NamedParentPath text,
NamedParentPathHash int(10) unsigned NOT NULL DEFAULT '0',
MetaDescription text,
HotItem int(11) NOT NULL DEFAULT '2',
NewItem int(11) NOT NULL DEFAULT '2',
PopItem int(11) NOT NULL DEFAULT '2',
Modified int(11) DEFAULT NULL,
ModifiedById int(11) DEFAULT NULL,
CachedTemplate varchar(255) NOT NULL DEFAULT '',
CachedTemplateHash int(10) unsigned NOT NULL DEFAULT '0',
Template varchar(255) NOT NULL DEFAULT '#inherit#',
UseExternalUrl tinyint(3) unsigned NOT NULL DEFAULT '0',
ExternalUrl varchar(255) NOT NULL DEFAULT '',
UseMenuIconUrl tinyint(3) unsigned NOT NULL DEFAULT '0',
MenuIconUrl varchar(255) NOT NULL DEFAULT '',
l1_Title varchar(255) DEFAULT '',
l2_Title varchar(255) DEFAULT '',
l3_Title varchar(255) DEFAULT '',
l4_Title varchar(255) DEFAULT '',
l5_Title varchar(255) DEFAULT '',
l1_MenuTitle varchar(255) NOT NULL DEFAULT '',
l2_MenuTitle varchar(255) NOT NULL DEFAULT '',
l3_MenuTitle varchar(255) NOT NULL DEFAULT '',
l4_MenuTitle varchar(255) NOT NULL DEFAULT '',
l5_MenuTitle varchar(255) NOT NULL DEFAULT '',
MetaTitle text,
IndexTools text,
IsMenu tinyint(4) NOT NULL DEFAULT '1',
Protected tinyint(4) NOT NULL DEFAULT '0',
FormId int(11) DEFAULT NULL,
FormSubmittedTemplate varchar(255) DEFAULT NULL,
FriendlyURL varchar(255) NOT NULL DEFAULT '',
ThemeId int(10) unsigned NOT NULL DEFAULT '0',
EnablePageCache tinyint(4) NOT NULL DEFAULT '0',
OverridePageCacheKey tinyint(4) NOT NULL DEFAULT '0',
PageCacheKey varchar(255) NOT NULL DEFAULT '',
PageExpiration int(11) DEFAULT NULL,
LiveRevisionNumber int(11) NOT NULL DEFAULT '1',
DirectLinkEnabled tinyint(4) NOT NULL DEFAULT '1',
DirectLinkAuthKey varchar(20) NOT NULL DEFAULT '',
PromoBlockGroupId int(10) unsigned NOT NULL DEFAULT '0',
RequireSSL tinyint(4) NOT NULL DEFAULT '0',
RequireLogin tinyint(4) NOT NULL DEFAULT '0',
PRIMARY KEY (CategoryId),
UNIQUE KEY ResourceId (ResourceId),
KEY ParentId (ParentId),
KEY Modified (Modified),
KEY Priority (Priority),
KEY sorting (`Name`,Priority),
KEY Filename (Filename(5)),
KEY l1_Name (l1_Name(5)),
KEY l2_Name (l2_Name(5)),
KEY l3_Name (l3_Name(5)),
KEY l4_Name (l4_Name(5)),
KEY l5_Name (l5_Name(5)),
KEY l1_Description (l1_Description(5)),
KEY l2_Description (l2_Description(5)),
KEY l3_Description (l3_Description(5)),
KEY l4_Description (l4_Description(5)),
KEY l5_Description (l5_Description(5)),
KEY TreeLeft (TreeLeft),
KEY TreeRight (TreeRight),
KEY SymLinkCategoryId (SymLinkCategoryId),
KEY `Status` (`Status`),
KEY CreatedOn (CreatedOn),
KEY EditorsPick (EditorsPick),
KEY ThemeId (ThemeId),
KEY EnablePageCache (EnablePageCache),
KEY OverridePageCacheKey (OverridePageCacheKey),
KEY PageExpiration (PageExpiration),
KEY Protected (Protected),
KEY LiveRevisionNumber (LiveRevisionNumber),
KEY PromoBlockGroupId (PromoBlockGroupId),
KEY NamedParentPathHash (NamedParentPathHash),
KEY CachedTemplateHash (CachedTemplateHash)
);
CREATE TABLE CategoryCustomData (
CustomDataId int(11) NOT NULL auto_increment,
ResourceId int(10) unsigned NOT NULL default '0',
KEY ResourceId (ResourceId),
PRIMARY KEY (CustomDataId)
);
CREATE TABLE CategoryItems (
CategoryId int(11) NOT NULL default '0',
ItemResourceId int(11) NOT NULL default '0',
PrimaryCat tinyint(4) NOT NULL default '0',
ItemPrefix varchar(50) NOT NULL default '',
Filename varchar(255) NOT NULL default '',
UNIQUE KEY CategoryId (CategoryId,ItemResourceId),
KEY PrimaryCat (PrimaryCat),
KEY ItemPrefix (ItemPrefix),
KEY ItemResourceId (ItemResourceId),
KEY Filename (Filename)
);
CREATE TABLE CategoryPermissionsCache (
PermCacheId int(11) NOT NULL auto_increment,
CategoryId int(11) NOT NULL default '0',
PermId int(11) NOT NULL default '0',
ACL varchar(255) NOT NULL default '',
PRIMARY KEY (PermCacheId),
KEY CategoryId (CategoryId),
KEY PermId (PermId),
KEY ACL (ACL)
);
CREATE TABLE PopupSizes (
PopupId int(10) unsigned NOT NULL auto_increment,
TemplateName varchar(255) NOT NULL default '',
PopupWidth int(11) NOT NULL default '0',
PopupHeight int(11) NOT NULL default '0',
PRIMARY KEY (PopupId),
KEY TemplateName (TemplateName)
);
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),
KEY IsClone (IsClone),
KEY LifeTime (LifeTime),
KEY LastCounted (LastCounted)
);
CREATE TABLE AdminSkins (
SkinId int(11) NOT NULL AUTO_INCREMENT,
`Name` varchar(255) DEFAULT NULL,
CSS text,
Logo varchar(255) DEFAULT NULL,
LogoBottom varchar(255) NOT NULL DEFAULT '',
LogoLogin varchar(255) NOT NULL DEFAULT '',
`Options` text,
LastCompiled int(11) NOT NULL DEFAULT '0',
IsPrimary int(1) NOT NULL DEFAULT '0',
DisplaySiteNameInHeader tinyint(1) NOT NULL DEFAULT '1',
PRIMARY KEY (SkinId),
KEY IsPrimary (IsPrimary),
KEY LastCompiled (LastCompiled)
);
CREATE TABLE ChangeLogs (
ChangeLogId bigint(20) NOT NULL AUTO_INCREMENT,
PortalUserId int(11) NOT NULL DEFAULT '0',
SessionLogId int(11) NOT NULL DEFAULT '0',
`Action` tinyint(4) NOT NULL DEFAULT '0',
OccuredOn int(11) DEFAULT NULL,
Prefix varchar(255) NOT NULL DEFAULT '',
ItemId bigint(20) NOT NULL DEFAULT '0',
Changes text,
MasterPrefix varchar(255) NOT NULL DEFAULT '',
MasterId bigint(20) NOT NULL DEFAULT '0',
PRIMARY KEY (ChangeLogId),
KEY PortalUserId (PortalUserId),
KEY SessionLogId (SessionLogId),
KEY `Action` (`Action`),
KEY OccuredOn (OccuredOn),
KEY Prefix (Prefix),
KEY MasterPrefix (MasterPrefix)
);
CREATE TABLE UserSessionLogs (
SessionLogId bigint(20) NOT NULL AUTO_INCREMENT,
PortalUserId int(11) NOT NULL DEFAULT '0',
SessionId int(10) NOT NULL DEFAULT '0',
+ SessionKey char(64) NOT NULL DEFAULT '',
`Status` tinyint(4) NOT NULL DEFAULT '1',
SessionStart int(11) DEFAULT NULL,
SessionEnd int(11) DEFAULT NULL,
IP varchar(15) NOT NULL DEFAULT '',
AffectedItems int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (SessionLogId),
KEY SessionId (SessionId),
KEY `Status` (`Status`),
KEY PortalUserId (PortalUserId)
);
CREATE TABLE StatisticsCapture (
StatisticsId int(10) unsigned NOT NULL auto_increment,
TemplateName varchar(255) NOT NULL default '',
Hits int(10) unsigned NOT NULL default '0',
LastHit int(11) NOT NULL default '0',
ScriptTimeMin decimal(40,20) unsigned NOT NULL default '0.00000000000000000000',
ScriptTimeAvg decimal(40,20) unsigned NOT NULL default '0.00000000000000000000',
ScriptTimeMax decimal(40,20) unsigned NOT NULL default '0.00000000000000000000',
SqlTimeMin decimal(40,20) unsigned NOT NULL default '0.00000000000000000000',
SqlTimeAvg decimal(40,20) unsigned NOT NULL default '0.00000000000000000000',
SqlTimeMax decimal(40,20) unsigned NOT NULL default '0.00000000000000000000',
SqlCountMin decimal(40,20) unsigned NOT NULL default '0.00000000000000000000',
SqlCountAvg decimal(40,20) unsigned NOT NULL default '0.00000000000000000000',
SqlCountMax decimal(40,20) unsigned NOT NULL default '0.00000000000000000000',
PRIMARY KEY (StatisticsId),
KEY TemplateName (TemplateName),
KEY Hits (Hits),
KEY LastHit (LastHit),
KEY ScriptTimeMin (ScriptTimeMin),
KEY ScriptTimeAvg (ScriptTimeAvg),
KEY ScriptTimeMax (ScriptTimeMax),
KEY SqlTimeMin (SqlTimeMin),
KEY SqlTimeAvg (SqlTimeAvg),
KEY SqlTimeMax (SqlTimeMax),
KEY SqlCountMin (SqlCountMin),
KEY SqlCountAvg (SqlCountAvg),
KEY SqlCountMax (SqlCountMax)
);
CREATE TABLE SlowSqlCapture (
CaptureId int(10) unsigned NOT NULL AUTO_INCREMENT,
TemplateNames text,
Hits int(10) unsigned NOT NULL DEFAULT '0',
LastHit int(11) NOT NULL DEFAULT '0',
SqlQuery text,
TimeMin decimal(40,20) unsigned NOT NULL DEFAULT '0.00000000000000000000',
TimeAvg decimal(40,20) unsigned NOT NULL DEFAULT '0.00000000000000000000',
TimeMax decimal(40,20) unsigned NOT NULL DEFAULT '0.00000000000000000000',
QueryCrc bigint(11) NOT NULL DEFAULT '0',
PRIMARY KEY (CaptureId),
KEY Hits (Hits),
KEY LastHit (LastHit),
KEY TimeMin (TimeMin),
KEY TimeAvg (TimeAvg),
KEY TimeMax (TimeMax),
KEY QueryCrc (QueryCrc)
);
CREATE TABLE ScheduledTasks (
ScheduledTaskId int(11) NOT NULL AUTO_INCREMENT,
`Name` varchar(255) NOT NULL DEFAULT '',
`Type` tinyint(3) unsigned NOT NULL DEFAULT '1',
`Status` tinyint(3) unsigned NOT NULL DEFAULT '1',
`Event` varchar(255) NOT NULL DEFAULT '',
RunSchedule varchar(255) NOT NULL DEFAULT '* * * * *',
LastRunOn int(10) unsigned DEFAULT NULL,
LastRunStatus tinyint(3) unsigned NOT NULL DEFAULT '1',
NextRunOn int(11) DEFAULT NULL,
RunTime int(10) unsigned NOT NULL DEFAULT '0',
Timeout int(10) unsigned DEFAULT NULL,
LastTimeoutOn int(10) unsigned DEFAULT NULL,
SiteDomainLimitation varchar(255) NOT NULL DEFAULT '',
PRIMARY KEY (ScheduledTaskId),
KEY `Status` (`Status`),
KEY LastRunOn (LastRunOn),
KEY LastRunStatus (LastRunStatus),
KEY RunTime (RunTime),
KEY NextRunOn (NextRunOn),
KEY SiteDomainLimitation (SiteDomainLimitation),
KEY Timeout (Timeout),
KEY `Type` (`Type`)
);
CREATE TABLE SpellingDictionary (
SpellingDictionaryId int(11) NOT NULL auto_increment,
MisspelledWord varchar(255) NOT NULL default '',
SuggestedCorrection varchar(255) NOT NULL default '',
PRIMARY KEY (SpellingDictionaryId),
KEY MisspelledWord (MisspelledWord),
KEY SuggestedCorrection (SuggestedCorrection)
);
CREATE TABLE Thesaurus (
ThesaurusId int(11) NOT NULL auto_increment,
SearchTerm varchar(255) NOT NULL default '',
ThesaurusTerm varchar(255) NOT NULL default '',
ThesaurusType tinyint(3) unsigned NOT NULL default '0',
PRIMARY KEY (ThesaurusId),
KEY ThesaurusType (ThesaurusType),
KEY SearchTerm (SearchTerm)
);
CREATE TABLE LocalesList (
LocaleId int(11) NOT NULL auto_increment,
LocaleIdentifier varchar(6) NOT NULL default '',
LocaleName varchar(255) NOT NULL default '',
Locale varchar(20) NOT NULL default '',
ScriptTag varchar(255) NOT NULL default '',
ANSICodePage varchar(10) NOT NULL default '',
PRIMARY KEY (LocaleId)
);
CREATE TABLE UserBanRules (
RuleId int(11) NOT NULL auto_increment,
RuleType tinyint(4) NOT NULL default '0',
ItemField varchar(255) default NULL,
ItemVerb tinyint(4) NOT NULL default '0',
ItemValue varchar(255) NOT NULL default '',
ItemType int(11) NOT NULL default '0',
Priority int(11) NOT NULL default '0',
Status tinyint(4) NOT NULL default '1',
ErrorTag varchar(255) default NULL,
PRIMARY KEY (RuleId),
KEY Status (Status),
KEY Priority (Priority),
KEY ItemType (ItemType)
);
CREATE TABLE CountCache (
ListType int(11) NOT NULL default '0',
ItemType int(11) NOT NULL default '-1',
Value int(11) NOT NULL default '0',
CountCacheId int(11) NOT NULL auto_increment,
LastUpdate int(11) NOT NULL default '0',
ExtraId varchar(50) default NULL,
TodayOnly tinyint(4) NOT NULL default '0',
PRIMARY KEY (CountCacheId)
);
CREATE TABLE UserFavorites (
FavoriteId int(11) NOT NULL auto_increment,
PortalUserId int(11) NOT NULL default '0',
ResourceId int(11) NOT NULL default '0',
ItemTypeId int(11) NOT NULL default '0',
Modified int(11) NOT NULL default '0',
PRIMARY KEY (FavoriteId),
UNIQUE KEY main (PortalUserId,ResourceId),
KEY Modified (Modified),
KEY ItemTypeId (ItemTypeId)
);
CREATE TABLE CatalogImages (
ImageId int(11) NOT NULL auto_increment,
ResourceId int(11) NOT NULL default '0',
Url varchar(255) NOT NULL default '',
Name varchar(255) NOT NULL default '',
AltName VARCHAR(255) NOT NULL DEFAULT '',
ImageIndex int(11) NOT NULL default '0',
LocalImage tinyint(4) NOT NULL default '1',
LocalPath varchar(240) NOT NULL default '',
Enabled int(11) NOT NULL default '1',
DefaultImg int(11) NOT NULL default '0',
ThumbUrl varchar(255) default NULL,
Priority int(11) NOT NULL default '0',
ThumbPath varchar(255) default NULL,
LocalThumb tinyint(4) NOT NULL default '1',
SameImages tinyint(4) NOT NULL default '1',
PRIMARY KEY (ImageId),
KEY ResourceId (ResourceId),
KEY Enabled (Enabled),
KEY Priority (Priority)
);
CREATE TABLE CatalogRatings (
RatingId int(11) NOT NULL auto_increment,
IPAddress varchar(255) NOT NULL default '',
CreatedOn INT UNSIGNED NULL DEFAULT NULL,
RatingValue int(11) NOT NULL default '0',
ItemId int(11) NOT NULL default '0',
PRIMARY KEY (RatingId),
KEY CreatedOn (CreatedOn),
KEY ItemId (ItemId),
KEY RatingValue (RatingValue)
);
CREATE TABLE CatalogReviews (
ReviewId int(11) NOT NULL AUTO_INCREMENT,
CreatedOn int(10) unsigned DEFAULT NULL,
ReviewText longtext,
Rating tinyint(3) unsigned NOT NULL DEFAULT '0',
IPAddress varchar(255) NOT NULL DEFAULT '',
ItemId int(11) NOT NULL DEFAULT '0',
CreatedById int(11) DEFAULT NULL,
ItemType tinyint(4) NOT NULL DEFAULT '0',
Priority int(11) NOT NULL DEFAULT '0',
`Status` tinyint(4) NOT NULL DEFAULT '2',
TextFormat int(11) NOT NULL DEFAULT '0',
Module varchar(255) NOT NULL DEFAULT '',
HelpfulCount int(11) NOT NULL,
NotHelpfulCount int(11) NOT NULL,
PRIMARY KEY (ReviewId),
KEY CreatedOn (CreatedOn),
KEY ItemId (ItemId),
KEY ItemType (ItemType),
KEY Priority (Priority),
KEY `Status` (`Status`)
);
CREATE TABLE ItemFilters (
FilterId int(11) NOT NULL AUTO_INCREMENT,
ItemPrefix varchar(255) NOT NULL DEFAULT '',
FilterField varchar(255) NOT NULL DEFAULT '',
FilterType varchar(100) NOT NULL DEFAULT '',
Enabled tinyint(4) NOT NULL DEFAULT '1',
RangeCount int(11) DEFAULT NULL,
PRIMARY KEY (FilterId),
KEY ItemPrefix (ItemPrefix),
KEY Enabled (Enabled)
);
CREATE TABLE SpamReports (
ReportId int(11) NOT NULL AUTO_INCREMENT,
ItemPrefix varchar(255) NOT NULL DEFAULT '',
ItemId int(11) NOT NULL,
MessageText text,
ReportedOn int(11) DEFAULT NULL,
ReportedById int(11) DEFAULT NULL,
PRIMARY KEY (ReportId),
KEY ItemPrefix (ItemPrefix),
KEY ItemId (ItemId),
KEY ReportedById (ReportedById)
);
CREATE TABLE ItemTypes (
ItemType int(11) NOT NULL default '0',
Module varchar(50) NOT NULL default '',
Prefix varchar(20) NOT NULL default '',
SourceTable varchar(100) NOT NULL default '',
TitleField varchar(50) default NULL,
CreatorField varchar(255) NOT NULL default '',
PopField varchar(255) default NULL,
RateField varchar(255) default NULL,
LangVar varchar(255) NOT NULL default '',
PrimaryItem int(11) NOT NULL default '0',
EditUrl varchar(255) NOT NULL default '',
ClassName varchar(40) NOT NULL default '',
ItemName varchar(50) NOT NULL default '',
PRIMARY KEY (ItemType),
KEY Module (Module)
);
CREATE TABLE CatalogFiles (
FileId int(11) NOT NULL AUTO_INCREMENT,
ResourceId int(11) unsigned NOT NULL DEFAULT '0',
FileName varchar(255) NOT NULL DEFAULT '',
FilePath varchar(255) NOT NULL DEFAULT '',
Size int(11) NOT NULL DEFAULT '0',
`Status` tinyint(4) NOT NULL DEFAULT '1',
CreatedOn int(11) unsigned DEFAULT NULL,
CreatedById int(11) DEFAULT NULL,
MimeType varchar(255) NOT NULL DEFAULT '',
PRIMARY KEY (FileId),
KEY ResourceId (ResourceId),
KEY CreatedOn (CreatedOn),
KEY `Status` (`Status`)
);
CREATE TABLE CatalogRelationships (
RelationshipId int(11) NOT NULL auto_increment,
SourceId int(11) default NULL,
TargetId int(11) default NULL,
SourceType tinyint(4) NOT NULL default '0',
TargetType tinyint(4) NOT NULL default '0',
Type int(11) NOT NULL default '0',
Enabled int(11) NOT NULL default '1',
Priority int(11) NOT NULL default '0',
PRIMARY KEY (RelationshipId),
KEY RelSource (SourceId),
KEY RelTarget (TargetId),
KEY `Type` (`Type`),
KEY Enabled (Enabled),
KEY Priority (Priority),
KEY SourceType (SourceType),
KEY TargetType (TargetType)
);
CREATE TABLE SearchConfig (
TableName varchar(40) NOT NULL default '',
FieldName varchar(40) NOT NULL default '',
SimpleSearch tinyint(4) NOT NULL default '1',
AdvancedSearch tinyint(4) NOT NULL default '1',
Description varchar(255) default NULL,
DisplayName varchar(80) default NULL,
ModuleName VARCHAR(20) NOT NULL DEFAULT 'In-Portal',
ConfigHeader varchar(255) default NULL,
DisplayOrder int(11) NOT NULL default '0',
SearchConfigId int(11) NOT NULL auto_increment,
Priority int(11) NOT NULL default '0',
FieldType varchar(20) NOT NULL default 'text',
ForeignField TEXT,
JoinClause TEXT,
IsWhere text,
IsNotWhere text,
ContainsWhere text,
NotContainsWhere text,
CustomFieldId int(11) default NULL,
PRIMARY KEY (SearchConfigId),
KEY SimpleSearch (SimpleSearch),
KEY AdvancedSearch (AdvancedSearch),
KEY DisplayOrder (DisplayOrder),
KEY Priority (Priority),
KEY CustomFieldId (CustomFieldId)
);
CREATE TABLE SearchLogs (
SearchLogId int(11) NOT NULL auto_increment,
Keyword varchar(255) NOT NULL default '',
Indices bigint(20) NOT NULL default '0',
SearchType int(11) NOT NULL default '0',
PRIMARY KEY (SearchLogId),
KEY Keyword (Keyword),
KEY SearchType (SearchType)
);
CREATE TABLE SpamControl (
ItemResourceId int(11) NOT NULL default '0',
IPaddress varchar(20) NOT NULL default '',
Expire INT UNSIGNED NULL DEFAULT NULL,
PortalUserId int(11) NOT NULL default '0',
DataType varchar(20) default NULL,
KEY PortalUserId (PortalUserId),
KEY Expire (Expire),
KEY DataType (DataType),
KEY ItemResourceId (ItemResourceId)
);
CREATE TABLE StatItem (
StatItemId int(11) NOT NULL auto_increment,
Module varchar(20) NOT NULL default '',
ValueSQL varchar(255) default NULL,
ResetSQL varchar(255) default NULL,
ListLabel varchar(255) NOT NULL default '',
Priority int(11) NOT NULL default '0',
AdminSummary int(11) NOT NULL default '0',
PRIMARY KEY (StatItemId),
KEY AdminSummary (AdminSummary),
KEY Priority (Priority)
);
CREATE TABLE ImportScripts (
ImportId int(11) NOT NULL AUTO_INCREMENT,
`Name` varchar(255) NOT NULL DEFAULT '',
Description text,
Prefix varchar(10) NOT NULL DEFAULT '',
Module varchar(50) NOT NULL DEFAULT '',
ExtraFields varchar(255) NOT NULL DEFAULT '',
`Type` varchar(10) NOT NULL DEFAULT '',
`Status` tinyint(4) NOT NULL DEFAULT '1',
PRIMARY KEY (ImportId),
KEY Module (Module),
KEY `Status` (`Status`)
);
CREATE TABLE UserVisits (
VisitId int(11) NOT NULL AUTO_INCREMENT,
VisitDate int(10) unsigned DEFAULT NULL,
Referer varchar(255) NOT NULL DEFAULT '',
IPAddress varchar(15) NOT NULL DEFAULT '',
AffiliateId int(10) unsigned NOT NULL DEFAULT '0',
PortalUserId int(11) NOT NULL DEFAULT '-2',
PRIMARY KEY (VisitId),
KEY PortalUserId (PortalUserId),
KEY AffiliateId (AffiliateId),
KEY VisitDate (VisitDate)
);
CREATE TABLE ImportCache (
CacheId int(11) NOT NULL AUTO_INCREMENT,
CacheName varchar(255) NOT NULL DEFAULT '',
VarName bigint(11) NOT NULL DEFAULT '0',
VarValue text,
PRIMARY KEY (CacheId),
KEY CacheName (CacheName),
KEY VarName (VarName)
);
CREATE TABLE CategoryRelatedSearches (
RelatedSearchId int(11) NOT NULL auto_increment,
ResourceId int(11) NOT NULL default '0',
Keyword varchar(255) NOT NULL default '',
ItemType tinyint(4) NOT NULL default '0',
Enabled tinyint(4) NOT NULL default '1',
Priority int(11) NOT NULL default '0',
PRIMARY KEY (RelatedSearchId),
KEY Enabled (Enabled),
KEY ItemType (ItemType),
KEY ResourceId (ResourceId)
);
CREATE TABLE StopWords (
StopWordId int(11) NOT NULL auto_increment,
StopWord varchar(255) NOT NULL default '',
PRIMARY KEY (StopWordId),
KEY StopWord (StopWord)
);
CREATE TABLE MailingLists (
MailingId int(10) unsigned NOT NULL AUTO_INCREMENT,
PortalUserId int(11) NOT NULL DEFAULT '-1',
`To` longtext,
ToParsed longtext,
Attachments text,
`Subject` varchar(255) NOT NULL DEFAULT '',
MessageText longtext,
MessageHtml longtext,
`Status` tinyint(3) unsigned NOT NULL DEFAULT '1',
EmailsQueuedTotal int(10) unsigned NOT NULL DEFAULT '0',
EmailsSent int(10) unsigned NOT NULL DEFAULT '0',
EmailsTotal int(10) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (MailingId),
KEY EmailsTotal (EmailsTotal),
KEY EmailsSent (EmailsSent),
KEY EmailsQueued (EmailsQueuedTotal),
KEY `Status` (`Status`),
KEY PortalUserId (PortalUserId)
);
CREATE TABLE PageContent (
PageContentId int(11) NOT NULL AUTO_INCREMENT,
ContentNum bigint(11) NOT NULL DEFAULT '0',
PageId int(11) NOT NULL DEFAULT '0',
RevisionId int(11) NOT NULL,
l1_Content text,
l2_Content text,
l3_Content text,
l4_Content text,
l5_Content text,
PRIMARY KEY (PageContentId),
KEY ContentNum (ContentNum,PageId),
KEY RevisionId (RevisionId)
);
CREATE TABLE PageRevisions (
RevisionId int(11) NOT NULL AUTO_INCREMENT,
PageId int(11) NOT NULL,
RevisionNumber int(11) NOT NULL,
IsDraft tinyint(4) NOT NULL,
FromRevisionId int(11) NOT NULL,
l1_PageContent longtext null,
l2_PageContent longtext null,
l3_PageContent longtext null,
l4_PageContent longtext null,
l5_PageContent longtext null,
CreatedById int(11) DEFAULT NULL,
CreatedOn int(11) DEFAULT NULL,
AutoSavedOn int(11) DEFAULT NULL,
`Status` tinyint(4) NOT NULL DEFAULT '2',
PRIMARY KEY (RevisionId),
KEY PageId (PageId),
KEY RevisionNumber (RevisionNumber),
KEY IsDraft (IsDraft),
KEY `Status` (`Status`)
);
CREATE TABLE FormFields (
FormFieldId int(11) NOT NULL AUTO_INCREMENT,
FormId int(11) NOT NULL DEFAULT '0',
`Type` int(11) NOT NULL DEFAULT '0',
FieldName varchar(255) NOT NULL DEFAULT '',
FieldLabel varchar(255) DEFAULT NULL,
Heading varchar(255) DEFAULT NULL,
Prompt varchar(255) DEFAULT NULL,
ElementType varchar(50) NOT NULL DEFAULT '',
ValueList varchar(255) DEFAULT NULL,
Priority int(11) NOT NULL DEFAULT '0',
IsSystem tinyint(3) unsigned NOT NULL DEFAULT '0',
Required tinyint(1) NOT NULL DEFAULT '0',
DisplayInGrid tinyint(1) NOT NULL DEFAULT '1',
DefaultValue text,
Validation tinyint(4) NOT NULL DEFAULT '0',
UploadExtensions varchar(255) NOT NULL DEFAULT '',
UploadMaxSize int(11) DEFAULT NULL,
Visibility tinyint(4) NOT NULL DEFAULT '1',
EmailCommunicationRole tinyint(4) NOT NULL DEFAULT '0',
PRIMARY KEY (FormFieldId),
KEY `Type` (`Type`),
KEY FormId (FormId),
KEY Priority (Priority),
KEY IsSystem (IsSystem),
KEY DisplayInGrid (DisplayInGrid),
KEY Visibility (Visibility),
KEY EmailCommunicationRole (EmailCommunicationRole)
);
CREATE TABLE FormSubmissions (
FormSubmissionId int(11) NOT NULL AUTO_INCREMENT,
FormId int(11) NOT NULL DEFAULT '0',
SubmissionTime int(11) DEFAULT NULL,
IPAddress varchar(15) NOT NULL DEFAULT '',
ReferrerURL text NULL,
LogStatus tinyint(3) unsigned NOT NULL DEFAULT '2',
LastUpdatedOn int(10) unsigned DEFAULT NULL,
Notes text,
MessageId varchar(255) DEFAULT NULL,
PRIMARY KEY (FormSubmissionId),
KEY FormId (FormId),
KEY SubmissionTime (SubmissionTime),
KEY LogStatus (LogStatus),
KEY LastUpdatedOn (LastUpdatedOn),
KEY MessageId (MessageId)
);
CREATE TABLE FormSubmissionReplies (
SubmissionLogId int(11) NOT NULL AUTO_INCREMENT,
FormSubmissionId int(10) unsigned NOT NULL,
FromEmail varchar(255) NOT NULL DEFAULT '',
ToEmail varchar(255) NOT NULL DEFAULT '',
Cc text,
Bcc text,
`Subject` varchar(255) NOT NULL DEFAULT '',
Message text,
Attachment text,
ReplyStatus tinyint(3) unsigned NOT NULL DEFAULT '0',
SentStatus tinyint(3) unsigned NOT NULL DEFAULT '0',
SentOn int(10) unsigned DEFAULT NULL,
RepliedOn int(10) unsigned DEFAULT NULL,
VerifyCode varchar(32) NOT NULL DEFAULT '',
DraftId int(10) unsigned NOT NULL DEFAULT '0',
MessageId varchar(255) NOT NULL DEFAULT '',
BounceInfo text,
BounceDate int(11) DEFAULT NULL,
PRIMARY KEY (SubmissionLogId),
KEY FormSubmissionId (FormSubmissionId),
KEY ReplyStatus (ReplyStatus),
KEY SentStatus (SentStatus),
KEY SentOn (SentOn),
KEY RepliedOn (RepliedOn),
KEY VerifyCode (VerifyCode),
KEY DraftId (DraftId),
KEY BounceDate (BounceDate),
KEY MessageId (MessageId)
);
CREATE TABLE FormSubmissionReplyDrafts (
DraftId int(11) NOT NULL AUTO_INCREMENT,
FormSubmissionId int(10) unsigned NOT NULL DEFAULT '0',
CreatedOn int(10) unsigned DEFAULT NULL,
CreatedById int(11) DEFAULT NULL,
Message text,
PRIMARY KEY (DraftId),
KEY FormSubmissionId (FormSubmissionId),
KEY CreatedOn (CreatedOn),
KEY CreatedById (CreatedById)
);
CREATE TABLE Forms (
FormId int(11) NOT NULL AUTO_INCREMENT,
Title varchar(255) NOT NULL DEFAULT '',
Description text,
RequireLogin tinyint(4) NOT NULL DEFAULT '0',
UseSecurityImage tinyint(4) NOT NULL DEFAULT '0',
SubmitNotifyEmail varchar(255) NOT NULL DEFAULT '',
EnableEmailCommunication tinyint(4) NOT NULL DEFAULT '0',
ProcessUnmatchedEmails tinyint(4) NOT NULL DEFAULT '0',
ReplyFromName varchar(255) NOT NULL DEFAULT '',
ReplyFromEmail varchar(255) NOT NULL DEFAULT '',
ReplyCc varchar(255) NOT NULL DEFAULT '',
ReplyBcc varchar(255) NOT NULL DEFAULT '',
ReplyMessageSignature text,
ReplyServer varchar(255) NOT NULL DEFAULT '',
ReplyPort int(11) NOT NULL DEFAULT '110',
ReplyUsername varchar(255) NOT NULL DEFAULT '',
ReplyPassword varchar(255) NOT NULL DEFAULT '',
BounceEmail varchar(255) NOT NULL DEFAULT '',
BounceServer varchar(255) NOT NULL DEFAULT '',
BouncePort int(11) NOT NULL DEFAULT '110',
BounceUsername varchar(255) NOT NULL DEFAULT '',
BouncePassword varchar(255) NOT NULL DEFAULT '',
PRIMARY KEY (FormId),
KEY UseSecurityImage (UseSecurityImage),
KEY RequireLogin (RequireLogin),
KEY EnableEmailCommunication (EnableEmailCommunication),
KEY ProcessUnmatchedEmails (ProcessUnmatchedEmails)
);
CREATE TABLE Semaphores (
`SemaphoreId` int(11) NOT NULL AUTO_INCREMENT,
- `SessionKey` int(10) unsigned NOT NULL DEFAULT '0',
+ `SessionKey` char(64) NOT NULL DEFAULT '',
`Timestamp` int(10) unsigned NOT NULL DEFAULT '0',
`MainPrefix` varchar(255) NOT NULL DEFAULT '',
`MainIDs` text,
`UserId` int(11) DEFAULT NULL,
`IpAddress` varchar(15) NOT NULL DEFAULT '',
`Hostname` varchar(255) NOT NULL DEFAULT '',
`RequestURI` varchar(255) NOT NULL DEFAULT '',
`Backtrace` longtext,
PRIMARY KEY (`SemaphoreId`),
KEY `SessionKey` (`SessionKey`),
KEY `Timestamp` (`Timestamp`),
KEY `MainPrefix` (`MainPrefix`)
);
CREATE TABLE CachedUrls (
UrlId int(11) NOT NULL AUTO_INCREMENT,
Url varchar(255) NOT NULL DEFAULT '',
DomainId int(11) NOT NULL DEFAULT '0',
`Hash` bigint(11) NOT NULL DEFAULT '0',
Prefixes varchar(255) NOT NULL DEFAULT '',
ParsedVars text,
Cached int(10) unsigned DEFAULT NULL,
LifeTime int(11) NOT NULL DEFAULT '-1',
PRIMARY KEY (UrlId),
KEY Url (Url),
KEY `Hash` (`Hash`),
KEY Prefixes (Prefixes),
KEY Cached (Cached),
KEY LifeTime (LifeTime),
KEY DomainId (DomainId)
);
CREATE TABLE SiteDomains (
DomainId int(11) NOT NULL AUTO_INCREMENT,
DomainName varchar(255) NOT NULL DEFAULT '',
DomainNameUsesRegExp tinyint(4) NOT NULL DEFAULT '0',
SSLUrl varchar(255) NOT NULL DEFAULT '',
SSLUrlUsesRegExp tinyint(4) NOT NULL DEFAULT '0',
AdminEmail varchar(255) NOT NULL DEFAULT '',
DefaultEmailRecipients text,
Country varchar(3) NOT NULL DEFAULT '',
PrimaryLanguageId int(11) NOT NULL DEFAULT '0',
Languages varchar(255) NOT NULL DEFAULT '',
PrimaryThemeId int(11) NOT NULL DEFAULT '0',
Themes varchar(255) NOT NULL DEFAULT '',
DomainIPRange text,
ExternalUrl varchar(255) NOT NULL DEFAULT '',
RedirectOnIPMatch tinyint(4) NOT NULL DEFAULT '0',
Priority int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (DomainId),
KEY DomainName (DomainName),
KEY DomainNameUsesRegExp (DomainNameUsesRegExp),
KEY SSLUrl (SSLUrl),
KEY SSLUrlUsesRegExp (SSLUrlUsesRegExp),
KEY AdminEmail (AdminEmail),
KEY Country (Country),
KEY PrimaryLanguageId (PrimaryLanguageId),
KEY Languages (Languages),
KEY PrimaryThemeId (PrimaryThemeId),
KEY Themes (Themes),
KEY ExternalUrl (ExternalUrl),
KEY RedirectOnIPMatch (RedirectOnIPMatch),
KEY Priority (Priority)
);
CREATE TABLE CurlLog (
LogId int(11) NOT NULL AUTO_INCREMENT,
Message varchar(255) NOT NULL DEFAULT '',
PageUrl varchar(255) NOT NULL DEFAULT '',
RequestUrl varchar(255) NOT NULL DEFAULT '',
PortalUserId int(11) NOT NULL,
- SessionKey int(11) NOT NULL,
+ SessionKey char(64) NOT NULL DEFAULT '',
IsAdmin tinyint(4) NOT NULL,
PageData text,
RequestData text,
ResponseData text,
RequestDate int(11) DEFAULT NULL,
ResponseDate int(11) DEFAULT NULL,
ResponseHttpCode int(11) NOT NULL,
CurlError varchar(255) NOT NULL DEFAULT '',
PRIMARY KEY (LogId),
KEY Message (Message),
KEY PageUrl (PageUrl),
KEY RequestUrl (RequestUrl),
KEY PortalUserId (PortalUserId),
KEY SessionKey (SessionKey),
KEY IsAdmin (IsAdmin),
KEY RequestDate (RequestDate),
KEY ResponseDate (ResponseDate),
KEY ResponseHttpCode (ResponseHttpCode),
KEY CurlError (CurlError)
);
CREATE TABLE PromoBlocks (
BlockId int(11) NOT NULL AUTO_INCREMENT,
l1_Title varchar(50) NOT NULL DEFAULT '',
l2_Title varchar(50) NOT NULL DEFAULT '',
l3_Title varchar(50) NOT NULL DEFAULT '',
l4_Title varchar(50) NOT NULL DEFAULT '',
l5_Title varchar(50) NOT NULL DEFAULT '',
l1_ButtonText varchar(255) NOT NULL DEFAULT '',
l2_ButtonText varchar(255) NOT NULL DEFAULT '',
l3_ButtonText varchar(255) NOT NULL DEFAULT '',
l4_ButtonText varchar(255) NOT NULL DEFAULT '',
l5_ButtonText varchar(255) NOT NULL DEFAULT '',
Priority int(11) NOT NULL DEFAULT '0',
`Status` tinyint(1) NOT NULL DEFAULT '1',
l1_Image varchar(255) NOT NULL DEFAULT '',
l2_Image varchar(255) NOT NULL DEFAULT '',
l3_Image varchar(255) NOT NULL DEFAULT '',
l4_Image varchar(255) NOT NULL DEFAULT '',
l5_Image varchar(255) NOT NULL DEFAULT '',
CSSClassName varchar(255) NOT NULL DEFAULT '',
LinkType tinyint(1) NOT NULL DEFAULT '1',
CategoryId int(11) DEFAULT NULL,
ExternalLink varchar(255) NOT NULL DEFAULT '',
OpenInNewWindow tinyint(3) unsigned NOT NULL DEFAULT '0',
ScheduleFromDate int(11) DEFAULT NULL,
ScheduleToDate int(11) DEFAULT NULL,
NumberOfClicks int(11) NOT NULL DEFAULT '0',
NumberOfViews int(11) NOT NULL DEFAULT '0',
Sticky tinyint(1) NOT NULL DEFAULT '0',
l1_Html text,
l2_Html text,
l3_Html text,
l4_Html text,
l5_Html text,
PromoBlockGroupId int(10) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (BlockId),
KEY OpenInNewWindow (OpenInNewWindow),
KEY PromoBlockGroupId (PromoBlockGroupId),
KEY l1_Title (l1_Title(5)),
KEY l2_Title (l2_Title(5)),
KEY l3_Title (l3_Title(5)),
KEY l4_Title (l4_Title(5)),
KEY l5_Title (l5_Title(5)),
KEY l1_ButtonText (l1_ButtonText(5)),
KEY l2_ButtonText (l2_ButtonText(5)),
KEY l3_ButtonText (l3_ButtonText(5)),
KEY l4_ButtonText (l4_ButtonText(5)),
KEY l5_ButtonText (l5_ButtonText(5))
);
CREATE TABLE PromoBlockGroups (
PromoBlockGroupId int(11) NOT NULL AUTO_INCREMENT,
Title varchar(255) NOT NULL DEFAULT '',
CreatedOn int(10) unsigned DEFAULT NULL,
`Status` tinyint(1) NOT NULL DEFAULT '1',
RotationDelay decimal(9,2) DEFAULT NULL,
TransitionTime decimal(9,2) DEFAULT NULL,
TransitionControls tinyint(1) NOT NULL DEFAULT '1',
TransitionEffect varchar(255) NOT NULL DEFAULT '',
TransitionEffectCustom varchar(255) NOT NULL DEFAULT '',
PRIMARY KEY (PromoBlockGroupId)
);
CREATE TABLE ExportUserPresets (
PortalUserId int NOT NULL DEFAULT 0,
ItemPrefix varchar(100) NOT NULL DEFAULT '',
PresetName varchar(100) NOT NULL DEFAULT '',
PresetData text NULL DEFAULT NULL,
PRIMARY KEY (PortalUserId, ItemPrefix, PresetName)
);
Index: branches/5.2.x/core/install/upgrades.php
===================================================================
--- branches/5.2.x/core/install/upgrades.php (revision 16796)
+++ branches/5.2.x/core/install/upgrades.php (revision 16797)
@@ -1,2457 +1,2570 @@
<?php
/**
* @version $Id$
* @package In-Portal
* @copyright Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license GNU/GPL
* In-Portal is Open Source software.
* This means that this software may have been modified pursuant
* the GNU General Public License, and as distributed it includes
* or is derivative of works licensed under the GNU General Public License
* or other free or open source software licenses.
* See http://www.in-portal.org/license for copyright notices and details.
*/
defined('FULL_PATH') or die('restricted access!');
$upgrade_class = 'CoreUpgrades';
/**
* Class, that holds all upgrade scripts for "Core" module
*
*/
class CoreUpgrades extends kUpgradeHelper {
/**
* Tables, that were renamed during 5.2.0 version upgrade
*
* @var Array
* @access private
*/
private $renamedTables = Array (
'ban-rule' => Array ('from' => 'BanRules', 'to' => 'UserBanRules'),
'conf' => Array ('from' => 'ConfigurationValues', 'to' => 'SystemSettings'),
'c' => Array ('from' => 'Category', 'to' => 'Categories'),
'cf' => Array ('from' => 'CustomField', 'to' => 'CustomFields'),
'draft' => Array ('from' => 'Drafts', 'to' => 'FormSubmissionReplyDrafts'),
'email-template' => Array ('from' => 'Events', 'to' => 'EmailEvents'),
'fav' => Array ('from' => 'Favorites', 'to' => 'UserFavorites'),
'img' => Array ('from' => 'Images', 'to' => 'CatalogImages'),
'#file' => Array ('from' => 'ItemFiles', 'to' => 'CatalogFiles'),
'rev' => Array ('from' => 'ItemReview', 'to' => 'CatalogReviews'),
'lang' => Array ('from' => 'Language', 'to' => 'Languages'),
'permission-type' => Array ('from' => 'PermissionConfig', 'to' => 'CategoryPermissionsConfig'),
'phrases' => Array ('from' => 'Phrase', 'to' => 'LanguageLabels'),
'g' => Array ('from' => 'PortalGroup', 'to' => 'UserGroups'),
'user-profile' => Array ('from' => 'PersistantSessionData', 'to' => 'UserPersistentSessionData'),
'u' => Array ('from' => 'PortalUser', 'to' => 'Users'),
'u-cdata' => Array ('from' => 'PortalUserCustomData', 'to' => 'UserCustomData'),
'search' => Array ('from' => 'RelatedSearches', 'to' => 'CategoryRelatedSearches'),
'rel' => Array ('from' => 'Relationship', 'to' => 'CatalogRelationships'),
'search-log' => Array ('from' => 'SearchLog', 'to' => 'SearchLogs'),
'skin' => Array ('from' => 'Skins', 'to' => 'AdminSkins'),
'submission-log' => Array ('from' => 'SubmissionLog', 'to' => 'FormSubmissionReplies'),
'theme' => Array ('from' => 'Theme', 'to' => 'Themes'),
'ug' => Array ('from' => 'UserGroup', 'to' => 'UserGroupRelations'),
'visits' => Array ('from' => 'Visits', 'to' => 'UserVisits'),
'session-log' => Array ('from' => 'SessionLogs', 'to' => 'UserSessionLogs'),
);
/**
* Changes table structure, where multilingual fields of TEXT type are present
*
* @param string $mode when called mode {before, after)
*/
function Upgrade_4_1_0($mode)
{
if ($mode == 'before') {
// don't user after, because In-Portal calls this method too
$this->_toolkit->SaveConfig();
}
if ($mode == 'after') {
/** @var kMultiLanguageHelper $ml_helper */
$ml_helper = $this->Application->recallObject('kMultiLanguageHelper');
$this->Application->UnitConfigReader->iterateConfigs(Array (&$this, 'updateTextFields'), $ml_helper->getLanguages());
}
}
/**
* Moves ReplacementTags functionality from EmailMessage to Events table
*
* @param string $mode when called mode {before, after)
*/
function Upgrade_4_1_1($mode)
{
if ($mode == 'after') {
$sql = 'SELECT ReplacementTags, EventId
FROM '.TABLE_PREFIX.'EmailMessage
WHERE (ReplacementTags IS NOT NULL) AND (ReplacementTags <> "") AND (LanguageId = 1)';
$replacement_tags = $this->Conn->GetCol($sql, 'EventId');
foreach ($replacement_tags as $event_id => $replacement_tag) {
$sql = 'UPDATE '.TABLE_PREFIX.'Events
SET ReplacementTags = '.$this->Conn->qstr($replacement_tag).'
WHERE EventId = '.$event_id;
$this->Conn->Query($sql);
}
// drop moved field from source table
$sql = 'ALTER TABLE '.TABLE_PREFIX.'EmailMessage
DROP `ReplacementTags`';
$this->Conn->Query($sql);
}
}
/**
* Callback function, that makes all ml fields of text type null with same default value
*
* @param string $prefix
* @param Array $config_data
* @param Array $languages
* @return bool
*/
function updateTextFields($prefix, &$config_data, $languages)
{
if (!isset($config_data['TableName']) || !isset($config_data['Fields'])) {
// invalid config found or prefix not found
return false;
}
$table_name = $config_data['TableName'];
$table_structure = $this->Conn->Query('DESCRIBE '.$table_name, 'Field');
if (!$table_structure) {
// table not found
return false;
}
$sqls = Array ();
foreach ($config_data['Fields'] as $field => $options) {
if (isset($options['formatter']) && $options['formatter'] == 'kMultiLanguage' && !isset($options['master_field'])) {
// update all l<lang_id>_<field_name> fields (new format)
foreach ($languages as $language_id) {
$ml_field = 'l'.$language_id.'_'.$field;
if ($table_structure[$ml_field]['Type'] == 'text') {
$sqls[] = 'CHANGE '.$ml_field.' '.$ml_field.' TEXT NULL DEFAULT NULL';
}
}
// update <field_name> if found (old format)
if (isset($table_structure[$field]) && $table_structure[$field]['Type'] == 'text') {
$sqls[] = 'CHANGE '.$field.' '.$field.' TEXT NULL DEFAULT NULL';
}
}
}
if ($sqls) {
$sql = 'ALTER TABLE '.$table_name.' '.implode(', ', $sqls);
$this->Conn->Query($sql);
}
return true;
}
/**
* Replaces In-Portal tags in Forgot Password related email events to K4 ones
*
* @param string $mode when called mode {before, after)
*/
function Upgrade_4_2_0($mode)
{
if ($mode == 'after') {
// 1. get event ids based on their name and type combination
$event_names = Array (
'USER.PSWD_' . EmailTemplate::TEMPLATE_TYPE_ADMIN,
'USER.PSWD_' . EmailTemplate::TEMPLATE_TYPE_FRONTEND,
'USER.PSWDC_' . EmailTemplate::TEMPLATE_TYPE_FRONTEND,
);
$event_sql = Array ();
foreach ($event_names as $mixed_event) {
list ($event_name, $event_type) = explode('_', $mixed_event, 2);
$event_sql[] = 'Event = "'.$event_name.'" AND Type = '.$event_type;
}
$sql = 'SELECT EventId
FROM '.TABLE_PREFIX.'Events
WHERE ('.implode(') OR (', $event_sql).')';
$event_ids = implode(',', $this->Conn->GetCol($sql));
// 2. replace In-Portal tags to K4 tags
$replacements = Array (
'<inp:touser _Field="Password" />' => '<inp2:u_ForgottenPassword />',
'<inp:m_confirm_password_link />' => '<inp2:u_ConfirmPasswordLink no_amp="1"/>',
);
foreach ($replacements as $old_tag => $new_tag) {
$sql = 'UPDATE '.TABLE_PREFIX.'EmailMessage
SET Template = REPLACE(Template, '.$this->Conn->qstr($old_tag).', '.$this->Conn->qstr($new_tag).')
WHERE EventId IN ('.$event_ids.')';
$this->Conn->Query($sql);
}
}
}
/**
* Makes admin primary language same as front-end - not needed, done in SQL
*
* @param string $mode when called mode {before, after)
*/
function Upgrade_4_2_1($mode)
{
}
function Upgrade_4_2_2($mode)
{
if ( $mode == 'before' ) {
$sql = 'SELECT LanguageId
FROM ' . TABLE_PREFIX . 'Language
WHERE PrimaryLang = 1';
if ( $this->Conn->GetOne($sql) ) {
return;
}
$this->Conn->Query('UPDATE ' . TABLE_PREFIX . 'Language SET PrimaryLang = 1 ORDER BY LanguageId LIMIT 1');
}
}
/**
* Adds index to "dob" field in "PortalUser" table when it's missing
*
* @param string $mode when called mode {before, after)
*/
function Upgrade_4_3_1($mode)
{
if ($mode == 'after') {
$sql = 'DESCRIBE ' . TABLE_PREFIX . 'PortalUser';
$structure = $this->Conn->Query($sql);
foreach ($structure as $field_info) {
if ($field_info['Field'] == 'dob') {
if (!$field_info['Key']) {
$sql = 'ALTER TABLE ' . TABLE_PREFIX . 'PortalUser
ADD INDEX (dob)';
$this->Conn->Query($sql);
}
break;
}
}
}
}
/**
* Removes duplicate phrases, update file paths in database
*
* @param string $mode when called mode {before, after)
*/
function Upgrade_4_3_9($mode)
{
// 1. find In-Portal old <inp: tags
$sql = 'SELECT EmailMessageId
FROM '.TABLE_PREFIX.'EmailMessage
WHERE Template LIKE \'%<inp:%\'';
$event_ids = implode(',', $this->Conn->GetCol($sql));
// 2. replace In-Portal old <inp: tags to K4 tags
$replacements = Array (
'<inp:m_category_field _Field="Name" _StripHTML="1"' => '<inp2:c_Field name="Name"',
'<inp:touser _Field="password"' => '<inp2:u_Field name="Password_plain"',
'<inp:touser _Field="UserName"' => '<inp2:u_Field name="Login"',
'<inp:touser _Field="' => '<inp2:u_Field name="',
'<inp:m_page_title' => '<inp2:m_BaseUrl',
'<inp:m_theme_url _page="current"' => '<inp2:m_BaseUrl',
'<inp:topic _field="text"' => '<inp2:bb-post_Field name="PostingText"',
'<inp:topic _field="link" _Template="inbulletin/post_list"' => '<inp2:bb_TopicLink template="__default__"',
);
if ($event_ids) {
foreach ($replacements as $old_tag => $new_tag) {
$sql = 'UPDATE '.TABLE_PREFIX.'EmailMessage
SET Template = REPLACE(Template, '.$this->Conn->qstr($old_tag).', '.$this->Conn->qstr($new_tag).')
WHERE EventId IN ('.$event_ids.')';
$this->Conn->Query($sql);
}
}
if ($mode == 'after') {
$this->_insertInPortalData();
$this->_moveDatabaseFolders();
// in case, when In-Portal module is enabled -> turn AdvancedUserManagement on too
if ($this->Application->findModule('Name', 'In-Portal')) {
$sql = 'UPDATE ' . TABLE_PREFIX . 'ConfigurationValues
SET VariableValue = 1
WHERE VariableName = "AdvancedUserManagement"';
$this->Conn->Query($sql);
}
}
if ($mode == 'languagepack') {
$this->_removeDuplicatePhrases();
}
}
function _insertInPortalData()
{
$data = Array (
'ConfigurationAdmin' => Array (
'UniqueField' => 'VariableName',
'Records' => Array (
'AllowDeleteRootCats' => "('AllowDeleteRootCats', 'la_Text_General', 'la_AllowDeleteRootCats', 'checkbox', NULL , NULL , 10.09, 0, 0)",
'Catalog_PreselectModuleTab' => "('Catalog_PreselectModuleTab', 'la_Text_General', 'la_config_CatalogPreselectModuleTab', 'checkbox', NULL, NULL, 10.10, 0, 1)",
'RecycleBinFolder' => "('RecycleBinFolder', 'la_Text_General', 'la_config_RecycleBinFolder', 'text', NULL , NULL , 10.11, 0, 0)",
'AdvancedUserManagement' => "('AdvancedUserManagement', 'la_Text_General', 'la_prompt_AdvancedUserManagement', 'checkbox', NULL, NULL, '10.011', 0, 1)",
),
),
'ConfigurationValues' => Array (
'UniqueField' => 'VariableName',
'Records' => Array (
'AdvancedUserManagement' => "(DEFAULT, 'AdvancedUserManagement', 0, 'In-Portal:Users', 'in-portal:configure_users')",
),
),
'ItemTypes' => Array (
'UniqueField' => 'ItemType',
'Records' => Array (
'1' => "(1, 'In-Portal', 'c', 'Category', 'Name', 'CreatedById', NULL, NULL, 'la_ItemTab_Categories', 1, 'admin/category/addcategory.php', 'clsCategory', 'Category')",
'6' => "(6, 'In-Portal', 'u', 'PortalUser', 'Login', 'PortalUserId', NULL, NULL, '', 0, '', 'clsPortalUser', 'User')",
),
),
'PermissionConfig' => Array (
'UniqueField' => 'PermissionName',
'Records' => Array (
'CATEGORY.ADD' => "(DEFAULT, 'CATEGORY.ADD', 'lu_PermName_Category.Add_desc', 'lu_PermName_Category.Add_error', 'In-Portal')",
'CATEGORY.DELETE' => "(DEFAULT, 'CATEGORY.DELETE', 'lu_PermName_Category.Delete_desc', 'lu_PermName_Category.Delete_error', 'In-Portal')",
'CATEGORY.ADD.PENDING' => "(DEFAULT, 'CATEGORY.ADD.PENDING', 'lu_PermName_Category.AddPending_desc', 'lu_PermName_Category.AddPending_error', 'In-Portal')",
'CATEGORY.MODIFY' => "(DEFAULT, 'CATEGORY.MODIFY', 'lu_PermName_Category.Modify_desc', 'lu_PermName_Category.Modify_error', 'In-Portal')",
'ADMIN' => "(DEFAULT, 'ADMIN', 'lu_PermName_Admin_desc', 'lu_PermName_Admin_error', 'Admin')",
'LOGIN' => "(DEFAULT, 'LOGIN', 'lu_PermName_Login_desc', 'lu_PermName_Admin_error', 'Front')",
'DEBUG.ITEM' => "(DEFAULT, 'DEBUG.ITEM', 'lu_PermName_Debug.Item_desc', '', 'Admin')",
'DEBUG.LIST' => "(DEFAULT, 'DEBUG.LIST', 'lu_PermName_Debug.List_desc', '', 'Admin')",
'DEBUG.INFO' => "(DEFAULT, 'DEBUG.INFO', 'lu_PermName_Debug.Info_desc', '', 'Admin')",
'PROFILE.MODIFY' => "(DEFAULT, 'PROFILE.MODIFY', 'lu_PermName_Profile.Modify_desc', '', 'Admin')",
'SHOWLANG' => "(DEFAULT, 'SHOWLANG', 'lu_PermName_ShowLang_desc', '', 'Admin')",
'FAVORITES' => "(DEFAULT, 'FAVORITES', 'lu_PermName_favorites_desc', 'lu_PermName_favorites_error', 'In-Portal')",
'SYSTEM_ACCESS.READONLY' => "(DEFAULT, 'SYSTEM_ACCESS.READONLY', 'la_PermName_SystemAccess.ReadOnly_desc', 'la_PermName_SystemAccess.ReadOnly_error', 'Admin')",
),
),
'Permissions' => Array (
'UniqueField' => 'Permission;GroupId;Type;CatId',
'Records' => Array (
'LOGIN;12;1;0' => "(DEFAULT, 'LOGIN', 12, 1, 1, 0)",
'in-portal:site.view;11;1;0' => "(DEFAULT, 'in-portal:site.view', 11, 1, 1, 0)",
'in-portal:browse.view;11;1;0' => "(DEFAULT, 'in-portal:browse.view', 11, 1, 1, 0)",
'in-portal:advanced_view.view;11;1;0' => "(DEFAULT, 'in-portal:advanced_view.view', 11, 1, 1, 0)",
'in-portal:reviews.view;11;1;0' => "(DEFAULT, 'in-portal:reviews.view', 11, 1, 1, 0)",
'in-portal:configure_categories.view;11;1;0' => "(DEFAULT, 'in-portal:configure_categories.view', 11, 1, 1, 0)",
'in-portal:configure_categories.edit;11;1;0' => "(DEFAULT, 'in-portal:configure_categories.edit', 11, 1, 1, 0)",
'in-portal:configuration_search.view;11;1;0' => "(DEFAULT, 'in-portal:configuration_search.view', 11, 1, 1, 0)",
'in-portal:configuration_search.edit;11;1;0' => "(DEFAULT, 'in-portal:configuration_search.edit', 11, 1, 1, 0)",
'in-portal:configuration_email.view;11;1;0' => "(DEFAULT, 'in-portal:configuration_email.view', 11, 1, 1, 0)",
'in-portal:configuration_email.edit;11;1;0' => "(DEFAULT, 'in-portal:configuration_email.edit', 11, 1, 1, 0)",
'in-portal:configuration_custom.view;11;1;0' => "(DEFAULT, 'in-portal:configuration_custom.view', 11, 1, 1, 0)",
'in-portal:configuration_custom.add;11;1;0' => "(DEFAULT, 'in-portal:configuration_custom.add', 11, 1, 1, 0)",
'in-portal:configuration_custom.edit;11;1;0' => "(DEFAULT, 'in-portal:configuration_custom.edit', 11, 1, 1, 0)",
'in-portal:configuration_custom.delete;11;1;0' => "(DEFAULT, 'in-portal:configuration_custom.delete', 11, 1, 1, 0)",
'in-portal:users.view;11;1;0' => "(DEFAULT, 'in-portal:users.view', 11, 1, 1, 0)",
'in-portal:user_list.advanced:ban;11;1;0' => "(DEFAULT, 'in-portal:user_list.advanced:ban', 11, 1, 1, 0)",
'in-portal:user_list.advanced:send_email;11;1;0' => "(DEFAULT, 'in-portal:user_list.advanced:send_email', 11, 1, 1, 0)",
'in-portal:user_groups.view;11;1;0' => "(DEFAULT, 'in-portal:user_groups.view', 11, 1, 1, 0)",
'in-portal:user_groups.add;11;1;0' => "(DEFAULT, 'in-portal:user_groups.add', 11, 1, 1, 0)",
'in-portal:user_groups.edit;11;1;0' => "(DEFAULT, 'in-portal:user_groups.edit', 11, 1, 1, 0)",
'in-portal:user_groups.delete;11;1;0' => "(DEFAULT, 'in-portal:user_groups.delete', 11, 1, 1, 0)",
'in-portal:user_groups.advanced:send_email;11;1;0' => "(DEFAULT, 'in-portal:user_groups.advanced:send_email', 11, 1, 1, 0)",
'in-portal:user_groups.advanced:manage_permissions;11;1;0' => "(DEFAULT, 'in-portal:user_groups.advanced:manage_permissions', 11, 1, 1, 0)",
'in-portal:configure_users.view;11;1;0' => "(DEFAULT, 'in-portal:configure_users.view', 11, 1, 1, 0)",
'in-portal:configure_users.edit;11;1;0' => "(DEFAULT, 'in-portal:configure_users.edit', 11, 1, 1, 0)",
'in-portal:user_email.view;11;1;0' => "(DEFAULT, 'in-portal:user_email.view', 11, 1, 1, 0)",
'in-portal:user_email.edit;11;1;0' => "(DEFAULT, 'in-portal:user_email.edit', 11, 1, 1, 0)",
'in-portal:user_custom.view;11;1;0' => "(DEFAULT, 'in-portal:user_custom.view', 11, 1, 1, 0)",
'in-portal:user_custom.add;11;1;0' => "(DEFAULT, 'in-portal:user_custom.add', 11, 1, 1, 0)",
'in-portal:user_custom.edit;11;1;0' => "(DEFAULT, 'in-portal:user_custom.edit', 11, 1, 1, 0)",
'in-portal:user_custom.delete;11;1;0' => "(DEFAULT, 'in-portal:user_custom.delete', 11, 1, 1, 0)",
'in-portal:user_banlist.view;11;1;0' => "(DEFAULT, 'in-portal:user_banlist.view', 11, 1, 1, 0)",
'in-portal:user_banlist.add;11;1;0' => "(DEFAULT, 'in-portal:user_banlist.add', 11, 1, 1, 0)",
'in-portal:user_banlist.edit;11;1;0' => "(DEFAULT, 'in-portal:user_banlist.edit', 11, 1, 1, 0)",
'in-portal:user_banlist.delete;11;1;0' => "(DEFAULT, 'in-portal:user_banlist.delete', 11, 1, 1, 0)",
'in-portal:reports.view;11;1;0' => "(DEFAULT, 'in-portal:reports.view', 11, 1, 1, 0)",
'in-portal:log_summary.view;11;1;0' => "(DEFAULT, 'in-portal:log_summary.view', 11, 1, 1, 0)",
'in-portal:searchlog.view;11;1;0' => "(DEFAULT, 'in-portal:searchlog.view', 11, 1, 1, 0)",
'in-portal:searchlog.delete;11;1;0' => "(DEFAULT, 'in-portal:searchlog.delete', 11, 1, 1, 0)",
'in-portal:sessionlog.view;11;1;0' => "(DEFAULT, 'in-portal:sessionlog.view', 11, 1, 1, 0)",
'in-portal:sessionlog.delete;11;1;0' => "(DEFAULT, 'in-portal:sessionlog.delete', 11, 1, 1, 0)",
'in-portal:emaillog.view;11;1;0' => "(DEFAULT, 'in-portal:emaillog.view', 11, 1, 1, 0)",
'in-portal:emaillog.delete;11;1;0' => "(DEFAULT, 'in-portal:emaillog.delete', 11, 1, 1, 0)",
'in-portal:visits.view;11;1;0' => "(DEFAULT, 'in-portal:visits.view', 11, 1, 1, 0)",
'in-portal:visits.delete;11;1;0' => "(DEFAULT, 'in-portal:visits.delete', 11, 1, 1, 0)",
'in-portal:configure_general.view;11;1;0' => "(DEFAULT, 'in-portal:configure_general.view', 11, 1, 1, 0)",
'in-portal:configure_general.edit;11;1;0' => "(DEFAULT, 'in-portal:configure_general.edit', 11, 1, 1, 0)",
'in-portal:modules.view;11;1;0' => "(DEFAULT, 'in-portal:modules.view', 11, 1, 1, 0)",
'in-portal:mod_status.view;11;1;0' => "(DEFAULT, 'in-portal:mod_status.view', 11, 1, 1, 0)",
'in-portal:mod_status.edit;11;1;0' => "(DEFAULT, 'in-portal:mod_status.edit', 11, 1, 1, 0)",
'in-portal:mod_status.advanced:approve;11;1;0' => "(DEFAULT, 'in-portal:mod_status.advanced:approve', 11, 1, 1, 0)",
'in-portal:mod_status.advanced:decline;11;1;0' => "(DEFAULT, 'in-portal:mod_status.advanced:decline', 11, 1, 1, 0)",
'in-portal:addmodule.view;11;1;0' => "(DEFAULT, 'in-portal:addmodule.view', 11, 1, 1, 0)",
'in-portal:addmodule.add;11;1;0' => "(DEFAULT, 'in-portal:addmodule.add', 11, 1, 1, 0)",
'in-portal:addmodule.edit;11;1;0' => "(DEFAULT, 'in-portal:addmodule.edit', 11, 1, 1, 0)",
'in-portal:tag_library.view;11;1;0' => "(DEFAULT, 'in-portal:tag_library.view', 11, 1, 1, 0)",
'in-portal:configure_themes.view;11;1;0' => "(DEFAULT, 'in-portal:configure_themes.view', 11, 1, 1, 0)",
'in-portal:configure_themes.add;11;1;0' => "(DEFAULT, 'in-portal:configure_themes.add', 11, 1, 1, 0)",
'in-portal:configure_themes.edit;11;1;0' => "(DEFAULT, 'in-portal:configure_themes.edit', 11, 1, 1, 0)",
'in-portal:configure_themes.delete;11;1;0' => "(DEFAULT, 'in-portal:configure_themes.delete', 11, 1, 1, 0)",
'in-portal:configure_styles.view;11;1;0' => "(DEFAULT, 'in-portal:configure_styles.view', 11, 1, 1, 0)",
'in-portal:configure_styles.add;11;1;0' => "(DEFAULT, 'in-portal:configure_styles.add', 11, 1, 1, 0)",
'in-portal:configure_styles.edit;11;1;0' => "(DEFAULT, 'in-portal:configure_styles.edit', 11, 1, 1, 0)",
'in-portal:configure_styles.delete;11;1;0' => "(DEFAULT, 'in-portal:configure_styles.delete', 11, 1, 1, 0)",
'in-portal:configure_lang.advanced:set_primary;11;1;0' => "(DEFAULT, 'in-portal:configure_lang.advanced:set_primary', 11, 1, 1, 0)",
'in-portal:configure_lang.advanced:import;11;1;0' => "(DEFAULT, 'in-portal:configure_lang.advanced:import', 11, 1, 1, 0)",
'in-portal:configure_lang.advanced:export;11;1;0' => "(DEFAULT, 'in-portal:configure_lang.advanced:export', 11, 1, 1, 0)",
'in-portal:tools.view;11;1;0' => "(DEFAULT, 'in-portal:tools.view', 11, 1, 1, 0)",
'in-portal:backup.view;11;1;0' => "(DEFAULT, 'in-portal:backup.view', 11, 1, 1, 0)",
'in-portal:restore.view;11;1;0' => "(DEFAULT, 'in-portal:restore.view', 11, 1, 1, 0)",
'in-portal:export.view;11;1;0' => "(DEFAULT, 'in-portal:export.view', 11, 1, 1, 0)",
'in-portal:main_import.view;11;1;0' => "(DEFAULT, 'in-portal:main_import.view', 11, 1, 1, 0)",
'in-portal:sql_query.view;11;1;0' => "(DEFAULT, 'in-portal:sql_query.view', 11, 1, 1, 0)",
'in-portal:sql_query.edit;11;1;0' => "(DEFAULT, 'in-portal:sql_query.edit', 11, 1, 1, 0)",
'in-portal:server_info.view;11;1;0' => "(DEFAULT, 'in-portal:server_info.view', 11, 1, 1, 0)",
'in-portal:help.view;11;1;0' => "(DEFAULT, 'in-portal:help.view', 11, 1, 1, 0)",
),
),
'SearchConfig' => Array (
'UniqueField' => 'TableName;FieldName;ModuleName',
'Records' => Array (
'Category;NewItem;In-Portal' => "('Category', 'NewItem', 0, 1, 'lu_fielddesc_category_newitem', 'lu_field_newitem', 'In-Portal', 'la_text_category', 18, DEFAULT, 0, 'boolean', NULL, NULL, NULL, NULL, NULL, NULL, NULL)",
'Category;PopItem;In-Portal' => "('Category', 'PopItem', 0, 1, 'lu_fielddesc_category_popitem', 'lu_field_popitem', 'In-Portal', 'la_text_category', 19, DEFAULT, 0, 'boolean', NULL, NULL, NULL, NULL, NULL, NULL, NULL)",
'Category;HotItem;In-Portal' => "('Category', 'HotItem', 0, 1, 'lu_fielddesc_category_hotitem', 'lu_field_hotitem', 'In-Portal', 'la_text_category', 17, DEFAULT, 0, 'boolean', NULL, NULL, NULL, NULL, NULL, NULL, NULL)",
'Category;MetaDescription;In-Portal' => "('Category', 'MetaDescription', 0, 1, 'lu_fielddesc_category_metadescription', 'lu_field_metadescription', 'In-Portal', 'la_text_category', 16, DEFAULT, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, NULL)",
'Category;ParentPath;In-Portal' => "('Category', 'ParentPath', 0, 1, 'lu_fielddesc_category_parentpath', 'lu_field_parentpath', 'In-Portal', 'la_text_category', 15, DEFAULT, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, NULL)",
'Category;ResourceId;In-Portal' => "('Category', 'ResourceId', 0, 1, 'lu_fielddesc_category_resourceid', 'lu_field_resourceid', 'In-Portal', 'la_text_category', 14, DEFAULT, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, NULL)",
'Category;CreatedById;In-Portal' => "('Category', 'CreatedById', 0, 1, 'lu_fielddesc_category_createdbyid', 'lu_field_createdbyid', 'In-Portal', 'la_text_category', 13, DEFAULT, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, NULL)",
'Category;CachedNavbar;In-Portal' => "('Category', 'CachedNavbar', 0, 1, 'lu_fielddesc_category_cachednavbar', 'lu_field_cachednavbar', 'In-Portal', 'la_text_category', 12, DEFAULT, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, NULL)",
'Category;CachedDescendantCatsQty;In-Portal' => "('Category', 'CachedDescendantCatsQty', 0, 1, 'lu_fielddesc_category_cacheddescendantcatsqty', 'lu_field_cacheddescendantcatsqty', 'In-Portal', 'la_text_category', 11, DEFAULT, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, NULL)",
'Category;MetaKeywords;In-Portal' => "('Category', 'MetaKeywords', 0, 1, 'lu_fielddesc_category_metakeywords', 'lu_field_metakeywords', 'In-Portal', 'la_text_category', 10, DEFAULT, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, NULL)",
'Category;Priority;In-Portal' => "('Category', 'Priority', 0, 1, 'lu_fielddesc_category_priority', 'lu_field_priority', 'In-Portal', 'la_text_category', 9, DEFAULT, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, NULL)",
'Category;Status;In-Portal' => "('Category', 'Status', 0, 1, 'lu_fielddesc_category_status', 'lu_field_status', 'In-Portal', 'la_text_category', 7, DEFAULT, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, NULL)",
'Category;EditorsPick;In-Portal' => "('Category', 'EditorsPick', 0, 1, 'lu_fielddesc_category_editorspick', 'lu_field_editorspick', 'In-Portal', 'la_text_category', 6, DEFAULT, 0, 'boolean', NULL, NULL, NULL, NULL, NULL, NULL, NULL)",
'Category;CreatedOn;In-Portal' => "('Category', 'CreatedOn', 0, 1, 'lu_fielddesc_category_createdon', 'lu_field_createdon', 'In-Portal', 'la_text_category', 5, DEFAULT, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, NULL)",
'Category;Description;In-Portal' => "('Category', 'Description', 1, 1, 'lu_fielddesc_category_description', 'lu_field_description', 'In-Portal', 'la_text_category', 4, DEFAULT, 2, 'text', NULL, NULL, NULL, NULL, NULL, NULL, NULL)",
'Category;Name;In-Portal' => "('Category', 'Name', 1, 1, 'lu_fielddesc_category_name', 'lu_field_name', 'In-Portal', 'la_text_category', 3, DEFAULT, 2, 'text', NULL, NULL, NULL, NULL, NULL, NULL, NULL)",
'Category;ParentId;In-Portal' => "('Category', 'ParentId', 0, 1, 'lu_fielddesc_category_parentid', 'lu_field_parentid', 'In-Portal', 'la_text_category', 2, DEFAULT, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, NULL)",
'Category;CategoryId;In-Portal' => "('Category', 'CategoryId', 0, 1, 'lu_fielddesc_category_categoryid', 'lu_field_categoryid', 'In-Portal', 'la_text_category', 0, DEFAULT, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, NULL)",
'Category;Modified;In-Portal' => "('Category', 'Modified', 0, 1, 'lu_fielddesc_category_modified', 'lu_field_modified', 'In-Portal', 'la_text_category', 20, DEFAULT, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, NULL)",
'Category;ModifiedById;In-Portal' => "('Category', 'ModifiedById', 0, 1, 'lu_fielddesc_category_modifiedbyid', 'lu_field_modifiedbyid', 'In-Portal', 'la_text_category', 21, DEFAULT, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, NULL)",
'PortalUser;PortalUserId;In-Portal' => "('PortalUser', 'PortalUserId', -1, 0, 'lu_fielddesc_user_portaluserid', 'lu_field_portaluserid', 'In-Portal', 'la_text_user', 0, DEFAULT, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, NULL)",
'PortalUser;Login;In-Portal' => "('PortalUser', 'Login', -1, 0, 'lu_fielddesc_user_login', 'lu_field_login', 'In-Portal', 'la_text_user', 1, DEFAULT, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, NULL)",
'PortalUser;Password;In-Portal' => "('PortalUser', 'Password', -1, 0, 'lu_fielddesc_user_password', 'lu_field_password', 'In-Portal', 'la_text_user', 2, DEFAULT, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, NULL)",
'PortalUser;tz;In-Portal' => "('PortalUser', 'tz', -1, 0, 'lu_fielddesc_user_tz', 'lu_field_tz', 'In-Portal', 'la_text_user', 17, DEFAULT, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, NULL)",
'PortalUser;dob;In-Portal' => "('PortalUser', 'dob', -1, 0, 'lu_fielddesc_user_dob', 'lu_field_dob', 'In-Portal', 'la_text_user', 16, DEFAULT, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, NULL)",
'PortalUser;Modified;In-Portal' => "('PortalUser', 'Modified', -1, 0, 'lu_fielddesc_user_modified', 'lu_field_modified', 'In-Portal', 'la_text_user', 15, DEFAULT, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, NULL)",
'PortalUser;Status;In-Portal' => "('PortalUser', 'Status', -1, 0, 'lu_fielddesc_user_status', 'lu_field_status', 'In-Portal', 'la_text_user', 14, DEFAULT, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, NULL)",
'PortalUser;ResourceId;In-Portal' => "('PortalUser', 'ResourceId', -1, 0, 'lu_fielddesc_user_resourceid', 'lu_field_resourceid', 'In-Portal', 'la_text_user', 13, DEFAULT, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, NULL)",
'PortalUser;Country;In-Portal' => "('PortalUser', 'Country', -1, 0, 'lu_fielddesc_user_country', 'lu_field_country', 'In-Portal', 'la_text_user', 12, DEFAULT, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, NULL)",
'PortalUser;Zip;In-Portal' => "('PortalUser', 'Zip', -1, 0, 'lu_fielddesc_user_zip', 'lu_field_zip', 'In-Portal', 'la_text_user', 11, DEFAULT, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, NULL)",
'PortalUser;State;In-Portal' => "('PortalUser', 'State', -1, 0, 'lu_fielddesc_user_state', 'lu_field_state', 'In-Portal', 'la_text_user', 10, DEFAULT, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, NULL)",
'PortalUser;City;In-Portal' => "('PortalUser', 'City', -1, 0, 'lu_fielddesc_user_city', 'lu_field_city', 'In-Portal', 'la_text_user', 9, DEFAULT, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, NULL)",
'PortalUser;Street;In-Portal' => "('PortalUser', 'Street', -1, 0, 'lu_fielddesc_user_street', 'lu_field_street', 'In-Portal', 'la_text_user', 8, DEFAULT, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, NULL)",
'PortalUser;Phone;In-Portal' => "('PortalUser', 'Phone', -1, 0, 'lu_fielddesc_user_phone', 'lu_field_phone', 'In-Portal', 'la_text_user', 7, DEFAULT, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, NULL)",
'PortalUser;CreatedOn;In-Portal' => "('PortalUser', 'CreatedOn', -1, 0, 'lu_fielddesc_user_createdon', 'lu_field_createdon', 'In-Portal', 'la_text_user', 6, DEFAULT, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, NULL)",
'PortalUser;Email;In-Portal' => "('PortalUser', 'Email', -1, 0, 'lu_fielddesc_user_email', 'lu_field_email', 'In-Portal', 'la_text_user', 5, DEFAULT, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, NULL)",
'PortalUser;LastName;In-Portal' => "('PortalUser', 'LastName', -1, 0, 'lu_fielddesc_user_lastname', 'lu_field_lastname', 'In-Portal', 'la_text_user', 4, DEFAULT, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, NULL)",
'PortalUser;FirstName;In-Portal' => "('PortalUser', 'FirstName', -1, 0, 'lu_fielddesc_user_firstname', 'lu_field_firstname', 'In-Portal', 'la_text_user', 3, DEFAULT, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, NULL)",
),
),
'StatItem' => Array (
'UniqueField' => 'Module;ListLabel',
'Records' => Array (
'In-Portal;la_prompt_ActiveCategories' => "(DEFAULT, 'In-Portal', 'SELECT count(*) FROM <%prefix%>Category WHERE Status=1 ', NULL, 'la_prompt_ActiveCategories', '0', '1')",
'In-Portal;la_prompt_ActiveUsers' => "(DEFAULT, 'In-Portal', 'SELECT count(*) FROM <%prefix%>PortalUser WHERE Status=1 ', NULL, 'la_prompt_ActiveUsers', '0', '1')",
'In-Portal;la_prompt_CurrentSessions' => "(DEFAULT, 'In-Portal', 'SELECT count(*) FROM <%prefix%>UserSession', NULL, 'la_prompt_CurrentSessions', '0', '1')",
'In-Portal;la_prompt_TotalCategories' => "(DEFAULT, 'In-Portal', 'SELECT COUNT(*) as CategoryCount FROM <%prefix%>Category', NULL, 'la_prompt_TotalCategories', 0, 2)",
'In-Portal;la_prompt_ActiveCategories' => "(DEFAULT, 'In-Portal', 'SELECT COUNT(*) AS ActiveCategories FROM <%prefix%>Category WHERE Status = 1', NULL, 'la_prompt_ActiveCategories', 0, 2)",
'In-Portal;la_prompt_PendingCategories' => "(DEFAULT, 'In-Portal', 'SELECT COUNT(*) AS PendingCategories FROM <%prefix%>Category WHERE Status = 2', NULL, 'la_prompt_PendingCategories', 0, 2)",
'In-Portal;la_prompt_DisabledCategories' => "(DEFAULT, 'In-Portal', 'SELECT COUNT(*) AS DisabledCategories FROM <%prefix%>Category WHERE Status = 0', NULL, 'la_prompt_DisabledCategories', 0, 2)",
'In-Portal;la_prompt_NewCategories' => "(DEFAULT, 'In-Portal', 'SELECT COUNT(*) AS NewCategories FROM <%prefix%>Category WHERE (NewItem = 1) OR ( (UNIX_TIMESTAMP() - CreatedOn) <= <%m:config name=\"Category_DaysNew\"%>*86400 AND (NewItem = 2) )', NULL, 'la_prompt_NewCategories', 0, 2)",
'In-Portal;la_prompt_CategoryEditorsPick' => "(DEFAULT, 'In-Portal', 'SELECT COUNT(*) FROM <%prefix%>Category WHERE EditorsPick = 1', NULL, 'la_prompt_CategoryEditorsPick', 0, 2)",
'In-Portal;la_prompt_NewestCategoryDate' => "(DEFAULT, 'In-Portal', 'SELECT <%m:post_format field=\"MAX(CreatedOn)\" type=\"date\"%> FROM <%prefix%>Category', NULL, 'la_prompt_NewestCategoryDate', 0, 2)",
'In-Portal;la_prompt_LastCategoryUpdate' => "(DEFAULT, 'In-Portal', 'SELECT <%m:post_format field=\"MAX(Modified)\" type=\"date\"%> FROM <%prefix%>Category', NULL, 'la_prompt_LastCategoryUpdate', 0, 2)",
'In-Portal;la_prompt_TopicsUsers' => "(DEFAULT, 'In-Portal', 'SELECT COUNT(*) AS TotalUsers FROM <%prefix%>PortalUser', NULL, 'la_prompt_TopicsUsers', 0, 2)",
'In-Portal;la_prompt_UsersActive' => "(DEFAULT, 'In-Portal', 'SELECT COUNT(*) AS ActiveUsers FROM <%prefix%>PortalUser WHERE Status = 1', NULL, 'la_prompt_UsersActive', 0, 2)",
'In-Portal;la_prompt_UsersPending' => "(DEFAULT, 'In-Portal', 'SELECT COUNT(*) AS PendingUsers FROM <%prefix%>PortalUser WHERE Status = 2', NULL, 'la_prompt_UsersPending', 0, 2)",
'In-Portal;la_prompt_UsersDisabled' => "(DEFAULT, 'In-Portal', 'SELECT COUNT(*) AS DisabledUsers FROM <%prefix%>PortalUser WHERE Status = 0', NULL, 'la_prompt_UsersDisabled', 0, 2)",
'In-Portal;la_prompt_NewestUserDate' => "(DEFAULT, 'In-Portal', 'SELECT <%m:post_format field=\"MAX(CreatedOn)\" type=\"date\"%> FROM <%prefix%>PortalUser', NULL, 'la_prompt_NewestUserDate', 0, 2)",
'In-Portal;la_prompt_UsersUniqueCountries' => "(DEFAULT, 'In-Portal', 'SELECT COUNT( DISTINCT LOWER( Country ) ) FROM <%prefix%>PortalUser WHERE LENGTH(Country) > 0', NULL, 'la_prompt_UsersUniqueCountries', 0, 2)",
'In-Portal;la_prompt_UsersUniqueStates' => "(DEFAULT, 'In-Portal', 'SELECT COUNT( DISTINCT LOWER( State ) ) FROM <%prefix%>PortalUser WHERE LENGTH(State) > 0', NULL, 'la_prompt_UsersUniqueStates', 0, 2)",
'In-Portal;la_prompt_TotalUserGroups' => "(DEFAULT, 'In-Portal', 'SELECT COUNT(*) AS TotalUserGroups FROM <%prefix%>PortalGroup', NULL, 'la_prompt_TotalUserGroups', 0, 2)",
'In-Portal;la_prompt_BannedUsers' => "(DEFAULT, 'In-Portal', 'SELECT COUNT(*) AS BannedUsers FROM <%prefix%>PortalUser WHERE IsBanned = 1', NULL, 'la_prompt_BannedUsers', 0, 2)",
'In-Portal;la_prompt_NonExpiredSessions' => "(DEFAULT, 'In-Portal', 'SELECT COUNT(*) AS NonExipedSessions FROM <%prefix%>UserSession WHERE Status = 1', NULL, 'la_prompt_NonExpiredSessions', 0, 2)",
'In-Portal;la_prompt_ThemeCount' => "(DEFAULT, 'In-Portal', 'SELECT COUNT(*) AS ThemeCount FROM <%prefix%>Theme', NULL, 'la_prompt_ThemeCount', 0, 2)",
'In-Portal;la_prompt_RegionsCount' => "(DEFAULT, 'In-Portal', 'SELECT COUNT(*) AS RegionsCount FROM <%prefix%>Language', NULL, 'la_prompt_RegionsCount', 0, 2)",
'In-Portal;la_prompt_TablesCount' => "(DEFAULT, 'In-Portal', '<%m:sql_action sql=\"SHOW+TABLES\" action=\"COUNT\" field=\"*\"%>', NULL, 'la_prompt_TablesCount', 0, 2)",
'In-Portal;la_prompt_RecordsCount' => "(DEFAULT, 'In-Portal', '<%m:sql_action sql=\"SHOW+TABLE+STATUS\" action=\"SUM\" field=\"Rows\"%>', NULL, 'la_prompt_RecordsCount', 0, 2)",
'In-Portal;la_prompt_SystemFileSize' => "(DEFAULT, 'In-Portal', '<%m:custom_action sql=\"empty\" action=\"SysFileSize\"%>', NULL, 'la_prompt_SystemFileSize', 0, 2)",
'In-Portal;la_prompt_DataSize' => "(DEFAULT, 'In-Portal', '<%m:sql_action sql=\"SHOW+TABLE+STATUS\" action=\"SUM\" format_as=\"file\" field=\"Data_length\"%>', NULL, 'la_prompt_DataSize', 0, 2)",
),
),
'StylesheetSelectors' => Array (
'UniqueField' => 'SelectorId',
'Records' => Array (
'169' => "(169, 8, 'Calendar''s selected days', '.calendar tbody .selected', 'a:0:{}', '', 1, 'font-weight: bold;\\\r\\nbackground-color: #9ED7ED;\\r\\nborder: 1px solid #83B2C5;', 0)",
'118' => "(118, 8, 'Data grid row', 'td.block-data-row', 'a:0:{}', '', 2, 'border-bottom: 1px solid #cccccc;', 48)",
'81' => "(81, 8, '\"More\" link', 'a.link-more', 'a:0:{}', '', 2, 'text-decoration: underline;', 64)",
'88' => "(88, 8, 'Block data, separated rows', 'td.block-data-grid', 'a:0:{}', '', 2, 'border: 1px solid #cccccc;', 48)",
'42' => "(42, 8, 'Block Header', 'td.block-header', 'a:4:{s:5:\"color\";s:16:\"rgb(0, 159, 240)\";s:9:\"font-size\";s:4:\"20px\";s:11:\"font-weight\";s:6:\"normal\";s:7:\"padding\";s:3:\"5px\";}', 'Block Header', 1, 'font-family: Verdana, Helvetica, sans-serif;', 0)",
'76' => "(76, 8, 'Navigation bar menu', 'tr.head-nav td', 'a:0:{}', '', 1, 'vertical-align: middle;', 0)",
'48' => "(48, 8, 'Block data', 'td.block-data', 'a:2:{s:9:\"font-size\";s:5:\"12px;\";s:7:\"padding\";s:3:\"5px\";}', '', 1, '', 0)",
'78' => "(78, 8, 'Body main style', 'body', 'a:0:{}', '', 1, 'padding: 0px; \\r\\nbackground-color: #ffffff; \\r\\nfont-family: arial, verdana, helvetica; \\r\\nfont-size: small;\\r\\nwidth: auto;\\r\\nmargin: 0px;', 0)",
'58' => "(58, 8, 'Main table', 'table.main-table', 'a:0:{}', '', 1, 'width: 770px;\\r\\nmargin: 0px;\\r\\n/*table-layout: fixed;*/', 0)",
'79' => "(79, 8, 'Block: header of data block', 'span.block-data-grid-header', 'a:0:{}', '', 1, 'font-family: Arial, Helvetica, sans-serif;\\r\\ncolor: #009DF6;\\r\\nfont-size: 12px;\\r\\nfont-weight: bold;\\r\\nbackground-color: #E6EEFF;\\r\\npadding: 6px;\\r\\nwhite-space: nowrap;', 0)",
'64' => "(64, 8, 'Link', 'a', 'a:0:{}', '', 1, '', 0)",
'46' => "(46, 8, 'Product title link', 'a.link-product1', 'a:0:{}', 'Product title link', 1, 'color: #62A1DE;\\r\\nfont-size: 14px;\\r\\nfont-weight: bold;\\r\\nline-height: 20px;\\r\\npadding-bottom: 10px;', 0)",
'75' => "(75, 8, 'Copy of Main path link', 'table.main-path td a:hover', 'a:0:{}', '', 1, 'color: #ffffff;', 0)",
'160' => "(160, 8, 'Current item in navigation bar', '.checkout-step-current', 'a:0:{}', '', 1, 'color: #A20303;\\r\\nfont-weight: bold;', 0)",
'51' => "(51, 8, 'Right block data', 'td.right-block-data', 'a:1:{s:9:\"font-size\";s:4:\"11px\";}', '', 2, 'padding: 7px;\\r\\nbackground: #e3edf6 url(\"/in-commerce4/themes/default/img/bgr_login.jpg\") repeat-y scroll left top;\\r\\nborder-bottom: 1px solid #64a1df;', 48)",
'67' => "(67, 8, 'Pagination bar: text', 'table.block-pagination td', 'a:3:{s:5:\"color\";s:7:\"#8B898B\";s:9:\"font-size\";s:4:\"12px\";s:11:\"font-weight\";s:6:\"normal\";}', '', 1, '', 0)",
'45' => "(45, 8, 'Category link', 'a.subcat', 'a:0:{}', 'Category link', 1, 'color: #2069A4', 0)",
'68' => "(68, 8, 'Pagination bar: link', 'table.block-pagination td a', 'a:3:{s:5:\"color\";s:7:\"#8B898B\";s:9:\"font-size\";s:5:\"12px;\";s:11:\"font-weight\";s:6:\"normal\";}', '', 1, '', 0)",
'69' => "(69, 8, 'Product description in product list', '.product-list-description', 'a:2:{s:5:\"color\";s:7:\"#8B898B\";s:9:\"font-size\";s:4:\"12px\";}', '', 1, '', 0)",
'73' => "(73, 8, 'Main path link', 'table.main-path td a', 'a:0:{}', '', 1, 'color: #d5e231;', 0)",
'83' => "(83, 8, 'Product title link in list (shopping cart)', 'a.link-product-cart', 'a:0:{}', 'Product title link', 1, 'color: #18559C;\\r\\nfont-size: 12px;\\r\\nfont-weight: bold;\\r\\ntext-decoration: none;\\r\\n\\r\\n', 0)",
'72' => "(72, 8, 'Main path block text', 'table.main-path td', 'a:0:{}', '', 1, 'color: #ffffff;\\r\\nfont-size: 10px;\\r\\nfont-weight: normal;\\r\\npadding: 1px;\\r\\n', 0)",
'61' => "(61, 8, 'Block: header of data table', 'td.block-data-grid-header', 'a:6:{s:4:\"font\";s:28:\"Arial, Helvetica, sans-serif\";s:5:\"color\";s:7:\"#009DF6\";s:9:\"font-size\";s:4:\"12px\";s:11:\"font-weight\";s:4:\"bold\";s:16:\"background-color\";s:7:\"#E6EEFF\";s:7:\"padding\";s:3:\"6px\";}', '', 1, 'white-space: nowrap;\\r\\npadding-left: 10px;\\r\\n/*\\r\\nbackground-image: url(/in-commerce4/themes/default/img/bullet1.gif);\\r\\nbackground-position: 10px 12px;\\r\\nbackground-repeat: no-repeat;\\r\\n*/', 0)",
'65' => "(65, 8, 'Link in product list additional row', 'td.product-list-additional a', 'a:1:{s:5:\"color\";s:7:\"#8B898B\";}', '', 2, '', 64)",
'55' => "(55, 8, 'Main table, left column', 'td.main-column-left', 'a:0:{}', '', 1, 'width:180px;\\r\\nborder: 1px solid #62A1DE;\\r\\nborder-top: 0px;', 0)",
'70' => "(70, 8, 'Product title link in list (category)', 'a.link-product-category', 'a:0:{}', 'Product title link', 1, 'color: #18559C;\\r\\nfont-size: 12px;\\r\\nfont-weight: bold;\\r\\ntext-decoration: none;\\r\\n\\r\\n', 0)",
'66' => "(66, 8, 'Pagination bar block', 'table.block-pagination', 'a:0:{}', '', 1, '', 0)",
'49' => "(49, 8, 'Bulleted list inside block', 'td.block-data ul li', 'a:0:{}', '', 1, ' list-style-image: url(/in-commerce4/themes/default/img/bullet2.gif);\\r\\n margin-bottom: 10px;\\r\\n font-size: 11px;', 0)",
'87' => "(87, 8, 'Cart item input form element', 'td.cart-item-atributes input', 'a:0:{}', '', 1, 'border: 1px solid #7BB2E6;', 0)",
'119' => "(119, 8, 'Data grid row header', 'td.block-data-row-hdr', 'a:0:{}', 'Used in order preview', 2, 'background-color: #eeeeee;\\r\\nborder-bottom: 1px solid #dddddd;\\r\\nborder-top: 1px solid #cccccc;\\r\\nfont-weight: bold;', 48)",
'82' => "(82, 8, '\"More\" link image', 'a.link-more img', 'a:0:{}', '', 2, 'text-decoration: none;\\r\\npadding-left: 5px;', 64)",
'63' => "(63, 8, 'Additional info under product description in list', 'td.product-list-additional', 'a:5:{s:5:\"color\";s:7:\"#8B898B\";s:9:\"font-size\";s:4:\"11px\";s:11:\"font-weight\";s:6:\"normal\";s:10:\"border-top\";s:18:\"1px dashed #8B898B\";s:13:\"border-bottom\";s:18:\"1px dashed #8B898B\";}', '', 2, '', 48)",
'43' => "(43, 8, 'Block', 'table.block', 'a:2:{s:16:\"background-color\";s:7:\"#E3EEF9\";s:6:\"border\";s:17:\"1px solid #64A1DF\";}', 'Block', 1, 'border: 0; \\r\\nmargin-bottom: 1px;\\r\\nwidth: 100%;', 0)",
'84' => "(84, 8, 'Cart item cell', 'td.cart-item', 'a:0:{}', '', 1, 'background-color: #F6FAFF;\\r\\nborder-left: 1px solid #ffffff;\\r\\nborder-bottom: 1px solid #ffffff;\\r\\npadding: 4px;', 0)",
'57' => "(57, 8, 'Main table, right column', 'td.main-column-right', 'a:0:{}', '', 1, 'width:220px;\\r\\nborder: 1px solid #62A1DE;\\r\\nborder-top: 0px;', 0)",
'161' => "(161, 8, 'Block for sub categories', 'td.block-data-subcats', 'a:0:{}', '', 2, ' background: #FFFFFF\\r\\nurl(/in-commerce4/themes/default/in-commerce/img/bgr_categories.jpg);\\r\\n background-repeat: no-repeat;\\r\\n background-position: top right;\\r\\nborder-bottom: 5px solid #DEEAFF;\\r\\npadding-left: 10px;', 48)",
'77' => "(77, 8, 'Left block header', 'td.left-block-header', 'a:0:{}', '', 2, 'font-family : verdana, helvetica, sans-serif;\\r\\ncolor : #ffffff;\\r\\nfont-size : 12px;\\r\\nfont-weight : bold;\\r\\ntext-decoration : none;\\r\\nbackground-color: #64a1df;\\r\\npadding: 5px;\\r\\npadding-left: 7px;', 42)",
'80' => "(80, 8, 'Right block data - text', 'td.right-block-data td', 'a:1:{s:9:\"font-size\";s:5:\"11px;\";}', '', 2, '', 48)",
'53' => "(53, 8, 'Right block header', 'td.right-block-header', 'a:0:{}', '', 2, 'font-family : verdana, helvetica, sans-serif;\\r\\ncolor : #ffffff;\\r\\nfont-size : 12px;\\r\\nfont-weight : bold;\\r\\ntext-decoration : none;\\r\\nbackground-color: #64a1df;\\r\\npadding: 5px;\\r\\npadding-left: 7px;', 42)",
'85' => "(85, 8, 'Cart item cell with attributes', 'td.cart-item-attributes', 'a:0:{}', '', 1, 'background-color: #E6EEFF;\\r\\nborder-left: 1px solid #ffffff;\\r\\nborder-bottom: 1px solid #ffffff;\\r\\npadding: 4px;\\r\\ntext-align: center;\\r\\nvertical-align: middle;\\r\\nfont-size: 12px;\\r\\nfont-weight: normal;', 0)",
'86' => "(86, 8, 'Cart item cell with name', 'td.cart-item-name', 'a:0:{}', '', 1, 'background-color: #F6FAFF;\\r\\nborder-left: 1px solid #ffffff;\\r\\nborder-bottom: 1px solid #ffffff;\\r\\npadding: 3px;', 0)",
'47' => "(47, 8, 'Block content of featured product', 'td.featured-block-data', 'a:0:{}', '', 1, 'font-family: Arial,Helvetica,sans-serif;\\r\\nfont-size: 12px;', 0)",
'56' => "(56, 8, 'Main table, middle column', 'td.main-column-center', 'a:0:{}', '', 1, '\\r\\n', 0)",
'50' => "(50, 8, 'Product title link in list', 'a.link-product2', 'a:0:{}', 'Product title link', 1, 'color: #62A1DE;\\r\\nfont-size: 12px;\\r\\nfont-weight: bold;\\r\\ntext-decoration: none;\\r\\n\\r\\n', 0)",
'71' => "(71, 8, 'Main path block', 'table.main-path', 'a:0:{}', '', 1, 'background: #61b0ec url(\"/in-commerce4/themes/default/img/bgr_path.jpg\") repeat-y scroll left top;\\r\\nwidth: 100%;\\r\\nmargin-bottom: 1px;\\r\\nmargin-right: 1px; \\r\\nmargin-left: 1px;', 0)",
'62' => "(62, 8, 'Block: columns header for data table', 'table.block-no-border th', 'a:6:{s:4:\"font\";s:28:\"Arial, Helvetica, sans-serif\";s:5:\"color\";s:7:\"#18559C\";s:9:\"font-size\";s:4:\"11px\";s:11:\"font-weight\";s:4:\"bold\";s:16:\"background-color\";s:7:\"#B4D2EE\";s:7:\"padding\";s:3:\"6px\";}', '', 1, 'text-align: left;', 0)",
'59' => "(59, 8, 'Block without border', 'table.block-no-border', 'a:0:{}', '', 1, 'border: 0px; \\r\\nmargin-bottom: 10px;\\r\\nwidth: 100%;', 0)",
'74' => "(74, 8, 'Main path language selector cell', 'td.main-path-language', 'a:0:{}', '', 1, 'vertical-align: middle;\\r\\ntext-align: right;\\r\\npadding-right: 6px;', 0)",
'171' => "(171, 8, 'Calendar''s highlighted day', '.calendar tbody .hilite', 'a:0:{}', '', 1, 'background-color: #f6f6f6;\\r\\nborder: 1px solid #83B2C5 !important;', 0)",
'175' => "(175, 8, 'Calendar''s days', '.calendar tbody .day', 'a:0:{}', '', 1, 'text-align: right;\\r\\npadding: 2px 4px 2px 2px;\\r\\nwidth: 2em;\\r\\nborder: 1px solid #fefefe;', 0)",
'170' => "(170, 8, 'Calendar''s weekends', '.calendar .weekend', 'a:0:{}', '', 1, 'color: #990000;', 0)",
'173' => "(173, 8, 'Calendar''s control buttons', '.calendar .calendar_button', 'a:0:{}', '', 1, 'color: black;\\r\\nfont-size: 12px;\\r\\nbackground-color: #eeeeee;', 0)",
'174' => "(174, 8, 'Calendar''s day names', '.calendar thead .name', 'a:0:{}', '', 1, 'background-color: #DEEEF6;\\r\\nborder-bottom: 1px solid #000000;', 0)",
'172' => "(172, 8, 'Calendar''s top and bottom titles', '.calendar .title', 'a:0:{}', '', 1, 'color: #FFFFFF;\\r\\nbackground-color: #62A1DE;\\r\\nborder: 1px solid #107DC5;\\r\\nborder-top: 0px;\\r\\npadding: 1px;', 0)",
'60' => "(60, 8, 'Block header for featured product', 'td.featured-block-header', 'a:0:{}', '', 2, '\\r\\n', 42)",
'54' => "(54, 8, 'Right block', 'table.right-block', 'a:0:{}', '', 2, 'background-color: #E3EEF9;\\r\\nborder: 0px;\\r\\nwidth: 100%;', 43)",
'44' => "(44, 8, 'Block content', 'td.block-data-big', 'a:0:{}', 'Block content', 1, ' background: #DEEEF6\\r\\nurl(/in-commerce4/themes/default/img/menu_bg.gif);\\r\\n background-repeat: no-repeat;\\r\\n background-position: top right;\\r\\n', 0)",
),
),
'Stylesheets' => Array (
'UniqueField' => 'StylesheetId',
'Records' => Array (
'8' => "(8, 'Default', 'In-Portal Default Theme', '', 1124952555, 1)",
),
),
'Counters' => Array (
'UniqueField' => 'Name',
'Records' => Array (
'members_count' => "(DEFAULT, 'members_count', 'SELECT COUNT(*) FROM <%PREFIX%>PortalUser WHERE Status = 1', NULL , NULL , '3600', '0', '|PortalUser|')",
'members_online' => "(DEFAULT, 'members_online', 'SELECT COUNT(*) FROM <%PREFIX%>UserSession WHERE PortalUserId > 0', NULL , NULL , '3600', '0', '|UserSession|')",
'guests_online' => "(DEFAULT, 'guests_online', 'SELECT COUNT(*) FROM <%PREFIX%>UserSession WHERE PortalUserId <= 0', NULL , NULL , '3600', '0', '|UserSession|')",
'users_online' => "(DEFAULT, 'users_online', 'SELECT COUNT(*) FROM <%PREFIX%>UserSession', NULL , NULL , '3600', '0', '|UserSession|')",
),
),
);
// check & insert if not found defined before data
foreach ($data as $table_name => $table_info) {
$unique_fields = explode(';', $table_info['UniqueField']);
foreach ($table_info['Records'] as $unique_value => $insert_sql) {
$unique_values = explode(';', $unique_value);
$where_clause = Array ();
foreach ($unique_fields as $field_index => $unique_field) {
$where_clause[] = $unique_field . ' = ' . $this->Conn->qstr($unique_values[$field_index]);
}
$sql = 'SELECT ' . implode(', ', $unique_fields) . '
FROM ' . TABLE_PREFIX . $table_name . '
WHERE (' . implode(') AND (', $where_clause) . ')';
$found = $this->Conn->GetRow($sql);
if ($found) {
$found = implode(';', $found);
}
if ($found != $unique_value) {
$this->Conn->Query('INSERT INTO ' . TABLE_PREFIX . $table_name . ' VALUES ' . $insert_sql);
}
}
}
}
/**
* Removes duplicate phrases per language basis (created during proj-base and in-portal shared installation)
*
*/
function _removeDuplicatePhrases()
{
$id_field = $this->Application->getUnitOption('phrases', 'IDField');
$table_name = $this->Application->getUnitOption('phrases', 'TableName');
$sql = 'SELECT LanguageId, Phrase, MIN(LastChanged) AS LastChanged, COUNT(*) AS DupeCount
FROM ' . $table_name . '
GROUP BY LanguageId, Phrase
HAVING COUNT(*) > 1';
$duplicate_phrases = $this->Conn->Query($sql);
foreach ($duplicate_phrases as $phrase_record) {
// 1. keep phrase, that was added first, because it is selected in PhrasesCache::LoadPhraseByLabel
$where_clause = Array (
'LanguageId = ' . $phrase_record['LanguageId'],
'Phrase = ' . $this->Conn->qstr($phrase_record['Phrase']),
'LastChanged' . ' = ' . $phrase_record['LastChanged'],
);
$sql = 'SELECT ' . $id_field . '
FROM ' . $table_name . '
WHERE (' . implode(') AND (', $where_clause) . ')';
$phrase_id = $this->Conn->GetOne($sql);
// 2. delete all other duplicates
$where_clause = Array (
'LanguageId = ' . $phrase_record['LanguageId'],
'Phrase = ' . $this->Conn->qstr($phrase_record['Phrase']),
$id_field . ' <> ' . $phrase_id,
);
$sql = 'DELETE FROM ' . $table_name . '
WHERE (' . implode(') AND (', $where_clause) . ')';
$this->Conn->Query($sql);
}
}
function _moveDatabaseFolders()
{
// Tables: PageContent, Images
if ($this->Conn->TableFound('PageContent', true)) {
// 1. replaces "/kernel/user_files/" references in content blocks
/** @var kMultiLanguageHelper $ml_helper */
$ml_helper = $this->Application->recallObject('kMultiLanguageHelper');
$languages = $ml_helper->getLanguages();
$replace_sql = '%1$s = REPLACE(%1$s, "/kernel/user_files/", "/system/user_files/")';
$update_sqls = Array ();
foreach ($languages as $language_id) {
$update_sqls[] = sprintf($replace_sql, 'l' . $language_id . '_Content');
}
if ($update_sqls) {
$sql = 'UPDATE ' . TABLE_PREFIX . 'PageContent
SET ' . implode(', ', $update_sqls);
$this->Conn->Query($sql);
}
}
// 2. replace path of images uploaded via "Images" tab of category items
$this->_replaceImageFolder('/kernel/images/', '/system/images/');
// 3. replace path of images uploaded via "Images" tab of category items (when badly formatted)
$this->_replaceImageFolder('kernel/images/', 'system/images/');
// 4. replace images uploaded via "In-Bulletin -> Emoticons" section
$this->_replaceImageFolder('in-bulletin/images/emoticons/', 'system/images/emoticons/');
// 5. update backup path in config
$this->_toolkit->saveConfigValues(
Array (
'Backup_Path' => FULL_PATH . '/system/backupdata'
)
);
}
/**
* Replaces mentions of "/kernel/images" folder in Images table
*
* @param string $from
* @param string $to
*/
function _replaceImageFolder($from, $to)
{
$replace_sql = '%1$s = REPLACE(%1$s, "' . $from . '", "' . $to . '")';
$sql = 'UPDATE ' . TABLE_PREFIX . 'Images
SET ' . sprintf($replace_sql, 'ThumbPath') . ', ' . sprintf($replace_sql, 'LocalPath');
$this->Conn->Query($sql);
}
/**
* Update colors in skin (only if they were not changed manually)
*
* @param string $mode when called mode {before, after)
*/
function Upgrade_5_0_0($mode)
{
if ($mode == 'before') {
$this->_removeDuplicatePhrases(); // because In-Commerce & In-Link share some phrases with Proj-CMS
$this->_createProjCMSTables();
$this->_addMissingConfigurationVariables();
}
if ($mode == 'after') {
$this->_fixSkinColors();
$this->_restructureCatalog();
$this->_sortImages();
// $this->_sortConfigurationVariables('In-Portal', 'in-portal:configure_general');
// $this->_sortConfigurationVariables('In-Portal', 'in-portal:configure_advanced');
}
}
function _sortConfigurationVariables($module, $section)
{
$sql = 'SELECT ca.heading, cv.VariableName
FROM ' . TABLE_PREFIX . 'ConfigurationAdmin ca
LEFT JOIN ' . TABLE_PREFIX . 'ConfigurationValues cv USING(VariableName)
WHERE (cv.ModuleOwner = ' . $this->Conn->qstr($module) . ') AND (cv.Section = ' . $this->Conn->qstr($section) . ')
ORDER BY ca.DisplayOrder asc, ca.GroupDisplayOrder asc';
$variables = $this->Conn->GetCol($sql, 'VariableName');
if (!$variables) {
return ;
}
$variables = $this->_groupRecords($variables);
$group_number = 0;
$variable_order = 1;
$prev_heading = '';
foreach ($variables as $variable_name => $variable_heading) {
if ($prev_heading != $variable_heading) {
$group_number++;
$variable_order = 1;
}
$sql = 'UPDATE ' . TABLE_PREFIX . 'ConfigurationAdmin
SET DisplayOrder = ' . $this->Conn->qstr($group_number * 10 + $variable_order / 100) . '
WHERE VariableName = ' . $this->Conn->qstr($variable_name);
$this->Conn->Query($sql);
$variable_order++;
$prev_heading = $variable_heading;
}
}
/**
* Group list records by header, saves internal order in group
*
* @param Array $variables
* @return Array
*/
function _groupRecords($variables)
{
$sorted = Array();
foreach ($variables as $variable_name => $variable_heading) {
$sorted[$variable_heading][] = $variable_name;
}
$variables = Array();
foreach ($sorted as $heading => $heading_records) {
foreach ($heading_records as $variable_name) {
$variables[$variable_name] = $heading;
}
}
return $variables;
}
/**
* Returns module root category
*
* @param string $module_name
* @param string $module_prefix
* @return int
*/
function _getRootCategory($module_name, $module_prefix)
{
// don't cache anything here (like in static variables), because database value is changed on the fly !!!
$sql = 'SELECT RootCat
FROM ' . TABLE_PREFIX . 'Modules
WHERE LOWER(Name) = ' . $this->Conn->qstr( strtolower($module_name) );
$root_category = $this->Conn->GetOne($sql);
// put to cache too, because CategoriesEventHandler::_prepareAutoPage uses kApplication::findModule
$this->Application->ModuleInfo[$module_name]['Name'] = $module_name;
$this->Application->ModuleInfo[$module_name]['RootCat'] = $root_category;
$this->Application->ModuleInfo[$module_name]['Var'] = $module_prefix;
return $root_category;
}
/**
* Move all categories (except "Content") from "Home" to "Content" category and hide them from menu
*
*/
function _restructureCatalog()
{
$root_category = $this->_getRootCategory('Core', 'adm');
$sql = 'SELECT CategoryId
FROM ' . TABLE_PREFIX . 'Category
WHERE ParentId = 0 AND CategoryId <> ' . $root_category;
$top_categories = $this->Conn->GetCol($sql);
if ($top_categories) {
// hide all categories located outside "Content" category from menu
$sql = 'UPDATE ' . TABLE_PREFIX . 'Category
SET IsMenu = 0
WHERE (ParentPath LIKE "|' . implode('|%") OR (ParentPath LIKE "|', $top_categories) . '|%")';
$this->Conn->Query($sql);
// move all top level categories under "Content" category and make them visible in menu
$sql = 'UPDATE ' . TABLE_PREFIX . 'Category
SET IsMenu = 1, ParentId = ' . $root_category . '
WHERE ParentId = 0 AND CategoryId <> ' . $root_category;
$this->Conn->Query($sql);
}
// make sure, that all categories have valid value for Priority field
/** @var kPriorityHelper $priority_helper */
$priority_helper = $this->Application->recallObject('PriorityHelper');
$event = new kEvent('c:OnListBuild');
// update all categories, because they are all under "Content" category now
$sql = 'SELECT CategoryId
FROM ' . TABLE_PREFIX . 'Category';
$categories = $this->Conn->GetCol($sql);
foreach ($categories as $category_id) {
$priority_helper->recalculatePriorities($event, 'ParentId = ' . $category_id);
}
// create initial theme structure in Category table
$this->_toolkit->rebuildThemes();
// make sure, that all system templates have ThemeId set (only possible during platform project upgrade)
$sql = 'SELECT ThemeId
FROM ' . TABLE_PREFIX . 'Theme
WHERE PrimaryTheme = 1';
$primary_theme_id = $this->Conn->GetOne($sql);
if ($primary_theme_id) {
$sql = 'UPDATE ' . TABLE_PREFIX . 'Category
SET ThemeId = ' . $primary_theme_id . '
WHERE IsSystem = 1 AND ThemeId = 0';
$this->Conn->Query($sql);
}
}
/**
* Changes skin colors to match new ones (only in case, when they match default values)
*
*/
function _fixSkinColors()
{
/** @var kDBItem $skin */
$skin = $this->Application->recallObject('skin', null, Array ('skip_autoload' => 1));
$skin->Load(1, 'IsPrimary');
if ($skin->isLoaded()) {
$skin_options = unserialize( $skin->GetDBField('Options') );
$changes = Array (
// option: from -> to
'HeadBgColor' => Array ('#1961B8', '#007BF4'),
'HeadBarColor' => Array ('#FFFFFF', '#000000'),
'HeadColor' => Array ('#CCFF00', '#FFFFFF'),
'TreeColor' => Array ('#006F99', '#000000'),
'TreeHoverColor' => Array ('', '#009FF0'),
'TreeHighHoverColor' => Array ('', '#FFFFFF'),
'TreeHighBgColor' => Array ('#4A92CE', '#4A92CE'),
'TreeBgColor' => Array ('#FFFFFF', '#DCECF6'),
);
$can_change = true;
foreach ($changes as $option_name => $change) {
list ($change_from, $change_to) = $change;
$can_change = $can_change && ($change_from == $skin_options[$option_name]['Value']);
if ($can_change) {
$skin_options[$option_name]['Value'] = $change_to;
}
}
if ($can_change) {
$skin->SetDBField('Options', serialize($skin_options));
$skin->Update();
/** @var SkinHelper $skin_helper */
$skin_helper = $this->Application->recallObject('SkinHelper');
$skin_file = $skin_helper->getSkinPath();
if (file_exists($skin_file)) {
unlink($skin_file);
}
}
}
}
/**
* 1. Set root category not to generate filename automatically and hide it from catalog
* 2. Hide root category of In-Edit and set it's fields
*
* @param int $category_id
*/
function _resetRootCategory($category_id)
{
$fields_hash = Array (
'l1_Name' => 'Content', 'Filename' => 'Content', 'AutomaticFilename' => 0,
'l1_Description' => 'Content', 'Status' => 4,
);
$this->Conn->doUpdate($fields_hash, TABLE_PREFIX . 'Category', 'CategoryId = ' . $category_id);
}
function _createProjCMSTables()
{
// 0. make sure, that Content category exists
$root_category = $this->_getRootCategory('Proj-CMS', 'st');
if ($root_category) {
// proj-cms module found -> remove it
$sql = 'DELETE FROM ' . TABLE_PREFIX . 'Modules
WHERE Name = "Proj-CMS"';
$this->Conn->Query($sql);
unset($this->Application->ModuleInfo['Proj-CMS']);
$this->_resetRootCategory($root_category);
// unhide all structure categories
$sql = 'UPDATE ' . TABLE_PREFIX . 'Category
SET Status = 1
WHERE (Status = 4) AND (CategoryId <> ' . $root_category . ')';
$this->Conn->Query($sql);
} else {
$root_category = $this->_getRootCategory('In-Edit', 'cms');
if ($root_category) {
// in-edit module found -> remove it
$sql = 'DELETE FROM ' . TABLE_PREFIX . 'Modules
WHERE Name = "In-Edit"';
$this->Conn->Query($sql);
unset($this->Application->ModuleInfo['In-Edit']);
$this->_resetRootCategory($root_category);
}
}
if (!$root_category) {
// create "Content" category when Proj-CMS/In-Edit module was not installed before
// use direct sql here, because category table structure doesn't yet match table structure in object
$fields_hash = Array (
'l1_Name' => 'Content', 'Filename' => 'Content', 'AutomaticFilename' => 0,
'l1_Description' => 'Content', 'Status' => 4,
);
$this->Conn->doInsert($fields_hash, TABLE_PREFIX . 'Category');
$root_category = $this->Conn->getInsertID();
}
$this->_toolkit->deleteCache();
$this->_toolkit->SetModuleRootCategory('Core', $root_category);
// 1. process "Category" table
$structure = $this->Conn->Query('DESCRIBE ' . TABLE_PREFIX . 'Category', 'Field');
if (!array_key_exists('Template', $structure)) {
// fields from "Pages" table were not added to "Category" table (like before "Proj-CMS" module install)
$sql = "ALTER TABLE " . TABLE_PREFIX . "Category
ADD COLUMN Template varchar(255) default NULL,
ADD COLUMN l1_Title varchar(255) default '',
ADD COLUMN l2_Title varchar(255) default '',
ADD COLUMN l3_Title varchar(255) default '',
ADD COLUMN l4_Title varchar(255) default '',
ADD COLUMN l5_Title varchar(255) default '',
ADD COLUMN l1_MenuTitle varchar(255) NOT NULL default '',
ADD COLUMN l2_MenuTitle varchar(255) NOT NULL default '',
ADD COLUMN l3_MenuTitle varchar(255) NOT NULL default '',
ADD COLUMN l4_MenuTitle varchar(255) NOT NULL default '',
ADD COLUMN l5_MenuTitle varchar(255) NOT NULL default '',
ADD COLUMN MetaTitle text,
ADD COLUMN IndexTools text,
ADD COLUMN IsIndex tinyint(1) NOT NULL default '0',
ADD COLUMN IsMenu TINYINT(4) NOT NULL DEFAULT '1',
ADD COLUMN IsSystem tinyint(4) NOT NULL default '0',
ADD COLUMN FormId int(11) default NULL,
ADD COLUMN FormSubmittedTemplate varchar(255) default NULL,
ADD COLUMN l1_Translated tinyint(4) NOT NULL default '0',
ADD COLUMN l2_Translated tinyint(4) NOT NULL default '0',
ADD COLUMN l3_Translated tinyint(4) NOT NULL default '0',
ADD COLUMN l4_Translated tinyint(4) NOT NULL default '0',
ADD COLUMN l5_Translated tinyint(4) NOT NULL default '0',
ADD COLUMN FriendlyURL varchar(255) NOT NULL default '',
ADD INDEX IsIndex (IsIndex),
ADD INDEX l1_Translated (l1_Translated),
ADD INDEX l2_Translated (l2_Translated),
ADD INDEX l3_Translated (l3_Translated),
ADD INDEX l4_Translated (l4_Translated),
ADD INDEX l5_Translated (l5_Translated)";
$this->Conn->Query($sql);
}
if (array_key_exists('Path', $structure)) {
$sql = 'ALTER TABLE ' . TABLE_PREFIX . 'Category
DROP Path';
$this->Conn->Query($sql);
}
// 2. process "PageContent" table
if ($this->Conn->TableFound(TABLE_PREFIX . 'PageContent', true)) {
$structure = $this->Conn->Query('DESCRIBE ' . TABLE_PREFIX . 'PageContent', 'Field');
if (!array_key_exists('l1_Translated', $structure)) {
$sql = "ALTER TABLE " . TABLE_PREFIX . "PageContent
ADD COLUMN l1_Translated tinyint(4) NOT NULL default '0',
ADD COLUMN l2_Translated tinyint(4) NOT NULL default '0',
ADD COLUMN l3_Translated tinyint(4) NOT NULL default '0',
ADD COLUMN l4_Translated tinyint(4) NOT NULL default '0',
ADD COLUMN l5_Translated tinyint(4) NOT NULL default '0'";
$this->Conn->Query($sql);
}
}
// 3. process "FormFields" table
if ($this->Conn->TableFound(TABLE_PREFIX . 'FormFields', true)) {
$structure = $this->Conn->Query('DESCRIBE ' . TABLE_PREFIX . 'FormFields', 'Field');
if (!$structure['FormId']['Key']) {
$sql = "ALTER TABLE " . TABLE_PREFIX . "FormFields
CHANGE Validation Validation TINYINT NOT NULL DEFAULT '0',
ADD INDEX FormId (FormId),
ADD INDEX Priority (Priority),
ADD INDEX IsSystem (IsSystem),
ADD INDEX DisplayInGrid (DisplayInGrid)";
$this->Conn->Query($sql);
}
}
else {
$this->Conn->Query("INSERT INTO " . TABLE_PREFIX . "Permissions VALUES (DEFAULT, 'in-portal:forms.view', 11, 1, 1, 0)");
$this->Conn->Query("INSERT INTO " . TABLE_PREFIX . "Permissions VALUES (DEFAULT, 'in-portal:forms.add', 11, 1, 1, 0)");
$this->Conn->Query("INSERT INTO " . TABLE_PREFIX . "Permissions VALUES (DEFAULT, 'in-portal:forms.edit', 11, 1, 1, 0)");
$this->Conn->Query("INSERT INTO " . TABLE_PREFIX . "Permissions VALUES (DEFAULT, 'in-portal:forms.delete', 11, 1, 1, 0)");
}
// 4. process "FormSubmissions" table
if ($this->Conn->TableFound(TABLE_PREFIX . 'FormSubmissions', true)) {
$structure = $this->Conn->Query('DESCRIBE ' . TABLE_PREFIX . 'FormSubmissions', 'Field');
if (!$structure['SubmissionTime']['Key']) {
$sql = "ALTER TABLE " . TABLE_PREFIX . "FormSubmissions
ADD INDEX SubmissionTime (SubmissionTime)";
$this->Conn->Query($sql);
}
}
else {
$this->Conn->Query("INSERT INTO " . TABLE_PREFIX . "Permissions VALUES (DEFAULT, 'in-portal:submissions.view', 11, 1, 1, 0)");
}
// 5. add missing event
$sql = 'SELECT EventId
FROM ' . TABLE_PREFIX . 'Events
WHERE (Event = "FORM.SUBMITTED") AND (Type = 1)';
$event_id = $this->Conn->GetOne($sql);
if (!$event_id) {
$sql = "INSERT INTO " . TABLE_PREFIX . "Events VALUES (DEFAULT, 'FORM.SUBMITTED', NULL, 1, 0, 'Core:Category', 'la_event_FormSubmitted', 1)";
$this->Conn->Query($sql);
}
$sql = 'SELECT EventId
FROM ' . TABLE_PREFIX . 'Events
WHERE (Event = "FORM.SUBMITTED") AND (Type = 0)';
$event_id = $this->Conn->GetOne($sql);
if (!$event_id) {
$sql = "INSERT INTO " . TABLE_PREFIX . "Events VALUES (DEFAULT, 'FORM.SUBMITTED', NULL, 1, 0, 'Core:Category', 'la_event_FormSubmitted', 0)";
$this->Conn->Query($sql);
}
}
function _addMissingConfigurationVariables()
{
$variables = Array (
'cms_DefaultDesign' => Array (
"INSERT INTO " . TABLE_PREFIX . "ConfigurationAdmin VALUES ('cms_DefaultDesign', 'la_Text_General', 'la_prompt_DefaultDesignTemplate', 'text', NULL, NULL, 10.15, 0, 0)",
"INSERT INTO " . TABLE_PREFIX . "ConfigurationValues VALUES (DEFAULT, 'cms_DefaultDesign', '/platform/designs/general', 'In-Portal', 'in-portal:configure_categories')",
),
'Require_AdminSSL' => Array (
"INSERT INTO " . TABLE_PREFIX . "ConfigurationAdmin VALUES ('Require_AdminSSL', 'la_Text_Website', 'la_config_RequireSSLAdmin', 'checkbox', '', '', 10.105, 0, 1)",
"INSERT INTO " . TABLE_PREFIX . "ConfigurationValues VALUES (DEFAULT, 'Require_AdminSSL', '', 'In-Portal', 'in-portal:configure_advanced')",
),
'UsePopups' => Array (
"INSERT INTO " . TABLE_PREFIX . "ConfigurationAdmin VALUES ('UsePopups', 'la_Text_Website', 'la_config_UsePopups', 'radio', '', '1=la_Yes,0=la_No', 10.221, 0, 0)",
"INSERT INTO " . TABLE_PREFIX . "ConfigurationValues VALUES (DEFAULT, 'UsePopups', '1', 'In-Portal', 'in-portal:configure_advanced')",
),
'UseDoubleSorting' => Array (
"INSERT INTO " . TABLE_PREFIX . "ConfigurationAdmin VALUES ('UseDoubleSorting', 'la_Text_Website', 'la_config_UseDoubleSorting', 'radio', '', '1=la_Yes,0=la_No', 10.222, 0, 0)",
"INSERT INTO " . TABLE_PREFIX . "ConfigurationValues VALUES (DEFAULT, 'UseDoubleSorting', '0', 'In-Portal', 'in-portal:configure_advanced')",
),
'MenuFrameWidth' => Array (
"INSERT INTO " . TABLE_PREFIX . "ConfigurationAdmin VALUES ('MenuFrameWidth', 'la_title_General', 'la_prompt_MenuFrameWidth', 'text', NULL, NULL, 10.31, 0, 0)",
"INSERT INTO " . TABLE_PREFIX . "ConfigurationValues VALUES (DEFAULT, 'MenuFrameWidth', 200, 'In-Portal', 'in-portal:configure_advanced')",
),
'DefaultSettingsUserId' => Array (
"INSERT INTO " . TABLE_PREFIX . "ConfigurationAdmin VALUES ('DefaultSettingsUserId', 'la_title_General', 'la_prompt_DefaultUserId', 'text', NULL, NULL, '10.06', '0', '0')",
"INSERT INTO " . TABLE_PREFIX . "ConfigurationValues VALUES (DEFAULT, 'DefaultSettingsUserId', -1, 'In-Portal:Users', 'in-portal:configure_users')",
),
);
foreach ($variables as $variable_name => $variable_sqls) {
$sql = 'SELECT VariableId
FROM ' . TABLE_PREFIX . 'ConfigurationValues
WHERE VariableName = ' . $this->Conn->qstr($variable_name);
$variable_id = $this->Conn->GetOne($sql);
if ($variable_id) {
continue;
}
foreach ($variable_sqls as $variable_sql) {
$this->Conn->Query($variable_sql);
}
}
}
/**
* Sort images in database (update Priority field)
*
*/
function _sortImages()
{
$sql = 'SELECT *
FROM ' . TABLE_PREFIX . 'Images
ORDER BY ResourceId ASC , DefaultImg DESC , ImageId ASC';
$images = $this->Conn->Query($sql);
$priority = 0;
$last_resource_id = false;
foreach ($images as $image) {
if ($image['ResourceId'] != $last_resource_id) {
// each item have own priorities among it's images
$priority = 0;
$last_resource_id = $image['ResourceId'];
}
if (!$image['DefaultImg']) {
$priority--;
}
$sql = 'UPDATE ' . TABLE_PREFIX . 'Images
SET Priority = ' . $priority . '
WHERE ImageId = ' . $image['ImageId'];
$this->Conn->Query($sql);
}
}
/**
* Update to 5.0.1
*
* @param string $mode when called mode {before, after)
*/
function Upgrade_5_0_1($mode)
{
if ($mode == 'after') {
// delete old events
$events_to_delete = Array ('CATEGORY.MODIFY', 'CATEGORY.DELETE');
$sql = 'SELECT EventId
FROM ' . TABLE_PREFIX . 'Events
WHERE Event IN ("' . implode('","', $events_to_delete) . '")';
$event_ids = $this->Conn->GetCol($sql);
if ($event_ids) {
$this->_deleteEvents($event_ids);
$sql = 'DELETE FROM ' . TABLE_PREFIX . 'Phrase
WHERE Phrase IN ("la_event_category.modify", "la_event_category.delete")';
$this->Conn->Query($sql);
}
// partially delete events
$sql = 'SELECT EventId
FROM ' . TABLE_PREFIX . 'Events
WHERE (Event IN ("CATEGORY.APPROVE", "CATEGORY.DENY")) AND (Type = ' . EmailTemplate::TEMPLATE_TYPE_ADMIN . ')';
$event_ids = $this->Conn->GetCol($sql);
if ($event_ids) {
$this->_deleteEvents($event_ids);
}
}
}
function _deleteEvents($ids)
{
$sql = 'DELETE FROM ' . TABLE_PREFIX . 'EmailMessage
WHERE EventId IN (' . implode(',', $ids) . ')';
$this->Conn->Query($sql);
$sql = 'DELETE FROM ' . TABLE_PREFIX . 'Events
WHERE EventId IN (' . implode(',', $ids) . ')';
$this->Conn->Query($sql);
}
/**
* Update to 5.0.2-B2; Transforms IsIndex field values to SymLinkCategoryId field
*
* @param string $mode when called mode {before, after)
*/
function Upgrade_5_0_2_B2($mode)
{
// 0 - Regular, 1 - Category Index, 2 - Container
if ($mode == 'before') {
// fix "Content" category
$fields_hash = Array (
'CreatedById' => USER_ROOT,
'CreatedOn' => time(),
'ResourceId' => $this->Application->NextResourceId(),
);
$category_id = $this->Application->findModule('Name', 'Core', 'RootCat');
$this->Conn->doUpdate($fields_hash, TABLE_PREFIX . 'Category', 'CategoryId = ' . $category_id);
// get all categories, marked as category index
$sql = 'SELECT ParentPath, CategoryId
FROM ' . TABLE_PREFIX . 'Category
WHERE IsIndex = 1';
$category_indexes = $this->Conn->GetCol($sql, 'CategoryId');
foreach ($category_indexes as $category_id => $parent_path) {
$parent_path = explode('|', substr($parent_path, 1, -1));
// set symlink to $category_id for each category, marked as container in given category path
$sql = 'SELECT CategoryId
FROM ' . TABLE_PREFIX . 'Category
WHERE CategoryId IN (' . implode(',', $parent_path) . ') AND (IsIndex = 2)';
$category_containers = $this->Conn->GetCol($sql);
if ($category_containers) {
$sql = 'UPDATE ' . TABLE_PREFIX . 'Category
SET SymLinkCategoryId = ' . $category_id . '
WHERE CategoryId IN (' . implode(',', $category_containers) . ')';
$this->Conn->Query($sql);
}
}
}
if ($mode == 'after') {
// scan theme to fill Theme.TemplateAliases and ThemeFiles.TemplateAlias fields
$this->_toolkit->rebuildThemes();
$sql = 'SELECT TemplateAliases, ThemeId
FROM ' . TABLE_PREFIX . 'Theme
WHERE (Enabled = 1) AND (TemplateAliases <> "")';
$template_aliases = $this->Conn->GetCol($sql, 'ThemeId');
$all_template_aliases = Array (); // reversed alias (from real template to alias)
foreach ($template_aliases as $theme_id => $theme_template_aliases) {
$theme_template_aliases = unserialize($theme_template_aliases);
if (!$theme_template_aliases) {
continue;
}
$all_template_aliases = array_merge($all_template_aliases, array_flip($theme_template_aliases));
}
$default_design_replaced = false;
$default_design = trim($this->Application->ConfigValue('cms_DefaultDesign'), '/');
foreach ($all_template_aliases as $from_template => $to_alias) {
// replace default design in configuration variable (when matches alias)
if ($from_template == $default_design) {
// specific alias matched
$sql = 'UPDATE ' . TABLE_PREFIX . 'ConfigurationValues
SET VariableValue = ' . $this->Conn->qstr($to_alias) . '
WHERE VariableName = "cms_DefaultDesign"';
$this->Conn->Query($sql);
$default_design_replaced = true;
}
// replace Category.Template and Category.CachedTemplate fields (when matches alias)
$sql = 'UPDATE ' . TABLE_PREFIX . 'Category
SET Template = ' . $this->Conn->qstr($to_alias) . '
WHERE Template IN (' . $this->Conn->qstr('/' . $from_template) . ',' . $this->Conn->qstr($from_template) . ')';
$this->Conn->Query($sql);
$sql = 'UPDATE ' . TABLE_PREFIX . 'Category
SET CachedTemplate = ' . $this->Conn->qstr($to_alias) . '
WHERE CachedTemplate IN (' . $this->Conn->qstr('/' . $from_template) . ',' . $this->Conn->qstr($from_template) . ')';
$this->Conn->Query($sql);
}
if (!$default_design_replaced) {
// in case if current default design template doesn't
// match any of aliases, then set it to #default_design#
$sql = 'UPDATE ' . TABLE_PREFIX . 'ConfigurationValues
SET VariableValue = "#default_design#"
WHERE VariableName = "cms_DefaultDesign"';
$this->Conn->Query($sql);
}
// replace data in category custom fields used for category item template storage
/** @var kRewriteUrlProcessor $rewrite_processor */
$rewrite_processor = $this->Application->recallObject('kRewriteUrlProcessor');
foreach ($this->Application->ModuleInfo as $module_name => $module_info) {
$custom_field_id = $rewrite_processor->getItemTemplateCustomField($module_info['Var']);
if (!$custom_field_id) {
continue;
}
foreach ($all_template_aliases as $from_template => $to_alias) {
$sql = 'UPDATE ' . TABLE_PREFIX . 'CategoryCustomData
SET l1_cust_' . $custom_field_id . ' = ' . $this->Conn->qstr($to_alias) . '
WHERE l1_cust_' . $custom_field_id . ' = ' . $this->Conn->qstr($from_template);
$this->Conn->Query($sql);
}
}
}
}
/**
* Update to 5.0.3-B2; Moves CATEGORY.* permission from module root categories to Content category
*
* @param string $mode when called mode {before, after)
*/
function Upgrade_5_0_3_B2($mode)
{
if ($mode == 'before') {
// get permissions
$sql = 'SELECT PermissionName
FROM ' . TABLE_PREFIX . 'PermissionConfig
WHERE PermissionName LIKE "CATEGORY.%"';
$permission_names = $this->Conn->GetCol($sql);
// get groups
$sql = 'SELECT GroupId
FROM ' . TABLE_PREFIX . 'PortalGroup';
$user_groups = $this->Conn->GetCol($sql);
$user_group_count = count($user_groups);
// get module root categories
$sql = 'SELECT RootCat
FROM ' . TABLE_PREFIX . 'Modules';
$module_categories = $this->Conn->GetCol($sql);
$module_categories[] = 0;
$module_categories = implode(',', array_unique($module_categories));
$permissions = $delete_permission_ids = Array ();
foreach ($permission_names as $permission_name) {
foreach ($user_groups as $group_id) {
$sql = 'SELECT PermissionId
FROM ' . TABLE_PREFIX . 'Permissions
WHERE (Permission = ' . $this->Conn->qstr($permission_name) . ') AND (PermissionValue = 1) AND (GroupId = ' . $group_id . ') AND (`Type` = 0) AND (CatId IN (' . $module_categories . '))';
$permission_ids = $this->Conn->GetCol($sql);
if ($permission_ids) {
if (!array_key_exists($permission_name, $permissions)) {
$permissions[$permission_name] = Array ();
}
$permissions[$permission_name][] = $group_id;
$delete_permission_ids = array_merge($delete_permission_ids, $permission_ids);
}
}
}
if ($delete_permission_ids) {
// here we can delete some of permissions that will be added later
$sql = 'DELETE FROM ' . TABLE_PREFIX . 'Permissions
WHERE PermissionId IN (' . implode(',', $delete_permission_ids) . ')';
$this->Conn->Query($sql);
}
$home_category = $this->Application->findModule('Name', 'Core', 'RootCat');
foreach ($permissions as $permission_name => $permission_groups) {
// optimize a bit
$has_everyone = in_array(15, $permission_groups);
if ($has_everyone || (!$has_everyone && count($permission_groups) == $user_group_count - 1)) {
// has permission for "Everyone" group OR allowed in all groups except "Everyone" group
// so remove all other explicitly allowed permissions
$permission_groups = Array (15);
}
foreach ($permission_groups as $group_id) {
$fields_hash = Array (
'Permission' => $permission_name,
'GroupId' => $group_id,
'PermissionValue' => 1,
'Type' => 0, // category-based permission,
'CatId' => $home_category,
);
$this->Conn->doInsert($fields_hash, TABLE_PREFIX . 'Permissions');
}
}
/** @var kPermCacheUpdater $updater */
$updater = $this->Application->makeClass('kPermCacheUpdater');
$updater->OneStepRun();
}
}
/**
* Update to 5.1.0-B1; Makes email message fields multilingual
*
* @param string $mode when called mode {before, after)
*/
function Upgrade_5_1_0_B1($mode)
{
if ( $mode == 'before' ) {
$this->_renameTables('from');
// migrate email events
$table_structure = $this->Conn->Query('DESCRIBE ' . TABLE_PREFIX . 'Events', 'Field');
if (!array_key_exists('Headers', $table_structure)) {
$sql = 'ALTER TABLE ' . TABLE_PREFIX . 'Events
ADD `Headers` TEXT NULL AFTER `ReplacementTags`,
ADD `MessageType` VARCHAR(4) NOT NULL default "text" AFTER `Headers`';
$this->Conn->Query($sql);
}
// alter here, because kMultiLanguageHelper::createFields
// method, called after will expect that to be in database
$sql = 'ALTER TABLE ' . TABLE_PREFIX . 'Events
ADD AllowChangingSender TINYINT NOT NULL DEFAULT "0" AFTER MessageType ,
ADD CustomSender TINYINT NOT NULL DEFAULT "0" AFTER AllowChangingSender ,
ADD SenderName VARCHAR(255) NOT NULL DEFAULT "" AFTER CustomSender ,
ADD SenderAddressType TINYINT NOT NULL DEFAULT "0" AFTER SenderName ,
ADD SenderAddress VARCHAR(255) NOT NULL DEFAULT "" AFTER SenderAddressType ,
ADD AllowChangingRecipient TINYINT NOT NULL DEFAULT "0" AFTER SenderAddress ,
ADD CustomRecipient TINYINT NOT NULL DEFAULT "0" AFTER AllowChangingRecipient ,
ADD Recipients TEXT AFTER CustomRecipient,
ADD INDEX (AllowChangingSender),
ADD INDEX (CustomSender),
ADD INDEX (SenderAddressType),
ADD INDEX (AllowChangingRecipient),
ADD INDEX (CustomRecipient)';
$this->Conn->Query($sql);
// create multilingual fields for phrases and email events
/** @var kMultiLanguageHelper $ml_helper */
$ml_helper = $this->Application->recallObject('kMultiLanguageHelper');
$ml_helper->createFields('phrases');
$ml_helper->createFields('email-template');
$languages = $ml_helper->getLanguages();
if ($this->Conn->TableFound(TABLE_PREFIX . 'EmailMessage', true)) {
/** @var kEmailTemplateHelper $email_template_helper */
$email_template_helper = $this->Application->recallObject('kEmailTemplateHelper');
foreach ($languages as $language_id) {
$sql = 'SELECT EmailMessageId, Template, EventId
FROM ' . TABLE_PREFIX . 'EmailMessage
WHERE LanguageId = ' . $language_id;
$translations = $this->Conn->Query($sql, 'EventId');
foreach ($translations as $event_id => $translation_data) {
$parsed = $email_template_helper->parseTemplate($translation_data['Template'], 'html');
$fields_hash = Array (
'l' . $language_id . '_Subject' => $parsed['Subject'],
'l' . $language_id . '_Body' => $parsed['HtmlBody'],
);
if ( $parsed['Headers'] ) {
$fields_hash['Headers'] = $parsed['Headers'];
}
$this->Conn->doUpdate($fields_hash, TABLE_PREFIX . 'Events', 'EventId = ' . $event_id);
$sql = 'DELETE FROM ' . TABLE_PREFIX . 'EmailMessage
WHERE EmailMessageId = ' . $translation_data['EmailMessageId'];
$this->Conn->Query($sql);
}
}
}
// migrate phrases
$temp_table = $this->Application->GetTempName(TABLE_PREFIX . 'Phrase');
$sqls = Array (
'DROP TABLE IF EXISTS ' . $temp_table,
'CREATE TABLE ' . $temp_table . ' LIKE ' . TABLE_PREFIX . 'Phrase',
'ALTER TABLE ' . $temp_table . ' DROP LanguageId, DROP Translation',
'ALTER IGNORE TABLE ' . $temp_table . ' DROP INDEX LanguageId_2',
'ALTER TABLE ' . $temp_table . ' DROP PhraseId',
'ALTER TABLE ' . $temp_table . ' ADD PhraseId INT NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST',
);
foreach ($sqls as $sql) {
$this->Conn->Query($sql);
}
$already_added = Array ();
$primary_language_id = $this->Application->GetDefaultLanguageId();
foreach ($languages as $language_id) {
$sql = 'SELECT Phrase, PhraseKey, Translation AS l' . $language_id . '_Translation, PhraseType, LastChanged, LastChangeIP, Module
FROM ' . TABLE_PREFIX . 'Phrase
WHERE LanguageId = ' . $language_id;
$phrases = $this->Conn->Query($sql, 'Phrase');
foreach ($phrases as $phrase => $fields_hash) {
if (array_key_exists($phrase, $already_added)) {
$this->Conn->doUpdate($fields_hash, $temp_table, 'PhraseId = ' . $already_added[$phrase]);
}
else {
$this->Conn->doInsert($fields_hash, $temp_table);
$already_added[$phrase] = $this->Conn->getInsertID();
}
}
// in case some phrases were found in this language, but not in primary language -> copy them
if ($language_id != $primary_language_id) {
$sql = 'UPDATE ' . $temp_table . '
SET l' . $primary_language_id . '_Translation = l' . $language_id . '_Translation
WHERE l' . $primary_language_id . '_Translation IS NULL';
$this->Conn->Query($sql);
}
}
$this->Conn->Query('DROP TABLE IF EXISTS ' . TABLE_PREFIX . 'Phrase');
$this->Conn->Query('RENAME TABLE ' . $temp_table . ' TO ' . TABLE_PREFIX . 'Phrase');
$this->_updateCountryStatesTable();
$this->_replaceConfigurationValueSeparator();
// save "config.php" in php format, not ini format as before
$this->_toolkit->SaveConfig();
}
if ($mode == 'after') {
$this->_transformEmailRecipients();
$this->_fixSkinColors();
}
}
/**
* Makes sure we rename tables to legacy names before doing other upgrades before 5.2.0-B1 upgrade
*
* @param string $name
* @param Array $arguments
*/
public function __call($name, $arguments)
{
if ( substr($name, 0, 12) == 'Upgrade_5_1_' && $arguments[0] == 'before' ) {
$this->_renameTables('from');
}
if ( substr($name, 0, 13) == 'Upgrade_5_2_0' && $arguments[0] == 'before' ) {
$this->_renameTables('to');
}
}
/**
* Move country/state translations from Phrase to CountryStates table
*
*/
function _updateCountryStatesTable()
{
// refactor StdDestinations table
$sql = 'RENAME TABLE ' . TABLE_PREFIX . 'StdDestinations TO ' . TABLE_PREFIX . 'CountryStates';
$this->Conn->Query($sql);
$sql = 'ALTER TABLE ' . TABLE_PREFIX . 'CountryStates
CHANGE DestId CountryStateId INT(11) NOT NULL AUTO_INCREMENT,
CHANGE DestType Type INT(11) NOT NULL DEFAULT \'1\',
CHANGE DestParentId StateCountryId INT(11) NULL DEFAULT NULL,
CHANGE DestAbbr IsoCode CHAR(3) NOT NULL DEFAULT \'\',
CHANGE DestAbbr2 ShortIsoCode CHAR(2) NULL DEFAULT NULL,
DROP INDEX DestType,
DROP INDEX DestParentId,
ADD INDEX (`Type`),
ADD INDEX (StateCountryId)';
$this->Conn->Query($sql);
/** @var kMultiLanguageHelper $ml_helper */
$ml_helper = $this->Application->recallObject('kMultiLanguageHelper');
$ml_helper->createFields('country-state');
$languages = $ml_helper->getLanguages();
foreach ($languages as $language_id) {
$sub_select = ' SELECT l' . $language_id . '_Translation
FROM ' . TABLE_PREFIX . 'Phrase
WHERE Phrase = DestName';
$sql = 'UPDATE ' . TABLE_PREFIX . 'CountryStates
SET l' . $language_id . '_Name = (' . $sub_select . ')';
$this->Conn->Query($sql);
}
$sql = 'ALTER TABLE ' . TABLE_PREFIX . 'CountryStates
DROP DestName';
$this->Conn->Query($sql);
$sql = 'DELETE FROM ' . TABLE_PREFIX . 'Phrase
WHERE Phrase LIKE ' . $this->Conn->qstr('la_country_%') . ' OR Phrase LIKE ' . $this->Conn->qstr('la_state_%');
$this->Conn->Query($sql);
}
/**
* Makes configuration values dropdowns use "||" as separator
*
*/
function _replaceConfigurationValueSeparator()
{
/** @var InpCustomFieldsHelper $custom_field_helper */
$custom_field_helper = $this->Application->recallObject('InpCustomFieldsHelper');
$sql = 'SELECT ValueList, VariableName
FROM ' . TABLE_PREFIX . 'ConfigurationAdmin
WHERE ValueList LIKE "%,%"';
$variables = $this->Conn->GetCol($sql, 'VariableName');
foreach ($variables as $variable_name => $value_list) {
$ret = Array ();
$options = $custom_field_helper->GetValuesHash($value_list, ',', false);
foreach ($options as $option_key => $option_title) {
if (substr($option_key, 0, 3) == 'SQL') {
$ret[] = $option_title;
}
else {
$ret[] = $option_key . '=' . $option_title;
}
}
$fields_hash = Array (
'ValueList' => implode(VALUE_LIST_SEPARATOR, $ret),
);
$this->Conn->doUpdate($fields_hash, TABLE_PREFIX . 'ConfigurationAdmin', 'VariableName = ' . $this->Conn->qstr($variable_name));
}
}
/**
* Transforms "FromUserId" into Sender* and Recipients columns
*
*/
function _transformEmailRecipients()
{
$sql = 'SELECT FromUserId, Type, EventId
FROM ' . TABLE_PREFIX . 'Events
WHERE FromUserId IS NOT NULL AND (FromUserId <> ' . USER_ROOT . ')';
$events = $this->Conn->Query($sql, 'EventId');
/** @var MInputHelper $minput_helper */
$minput_helper = $this->Application->recallObject('MInputHelper');
foreach ($events as $event_id => $event_data) {
$sql = 'SELECT Login
FROM ' . TABLE_PREFIX . 'PortalUser
WHERE PortalUserId = ' . $event_data['FromUserId'];
$username = $this->Conn->GetOne($sql);
if (!$username) {
continue;
}
if ($event_data['Type'] == EmailTemplate::TEMPLATE_TYPE_FRONTEND) {
// from user
$fields_hash = Array (
'CustomSender' => 1,
'SenderAddressType' => EmailTemplate::ADDRESS_TYPE_USER,
'SenderAddress' => $username
);
}
if ($event_data['Type'] == EmailTemplate::TEMPLATE_TYPE_ADMIN) {
// to user
$records = Array (
Array (
'RecipientType' => EmailTemplate::RECIPIENT_TYPE_TO,
'RecipientName' => '',
'RecipientAddressType' => EmailTemplate::ADDRESS_TYPE_USER,
'RecipientAddress' => $username
)
);
$fields_hash = Array (
'CustomRecipient' => 1,
'Recipients' => $minput_helper->prepareMInputXML($records, array_keys( reset($records) ))
);
}
$this->Conn->doUpdate($fields_hash, TABLE_PREFIX . 'Events', 'EventId = ' . $event_id);
}
$this->Conn->Query('ALTER TABLE ' . TABLE_PREFIX . 'Events DROP FromUserId');
}
/**
* Update to 5.1.0; Fixes refferer of form submissions
*
* @param string $mode when called mode {before, after)
*/
function Upgrade_5_1_0($mode)
{
if ( $mode == 'before' ) {
$this->_renameTables('from');
}
if ( $mode == 'after' ) {
$base_url = $this->Application->BaseURL();
$sql = 'UPDATE ' . TABLE_PREFIX . 'FormSubmissions
SET ReferrerURL = REPLACE(ReferrerURL, ' . $this->Conn->qstr($base_url) . ', "/")';
$this->Conn->Query($sql);
}
}
/**
* Update to 5.1.1-B1; Transforms DisplayToPublic logic
*
* @param string $mode when called mode {before, after)
*/
function Upgrade_5_1_1_B1($mode)
{
if ( $mode == 'before' ) {
$this->_renameTables('from');
}
if ($mode == 'after') {
$this->processDisplayToPublic();
}
}
function processDisplayToPublic()
{
$profile_mapping = Array (
'pp_firstname' => 'FirstName',
'pp_lastname' => 'LastName',
'pp_dob' => 'dob',
'pp_email' => 'Email',
'pp_phone' => 'Phone',
'pp_street' => 'Street',
'pp_city' => 'City',
'pp_state' => 'State',
'pp_zip' => 'Zip',
'pp_country' => 'Country',
);
$fields = array_keys($profile_mapping);
$fields = $this->Conn->qstrArray($fields);
$where_clause = 'VariableName IN (' . implode(',', $fields) . ')';
// 1. get user, that have saved their profile at least once
$sql = 'SELECT DISTINCT PortalUserId
FROM ' . TABLE_PREFIX . 'PersistantSessionData
WHERE ' . $where_clause;
$users = $this->Conn->GetCol($sql);
foreach ($users as $user_id) {
// 2. convert to new format
$sql = 'SELECT VariableValue, VariableName
FROM ' . TABLE_PREFIX . 'PersistantSessionData
WHERE (PortalUserId = ' . $user_id . ') AND ' . $where_clause;
$user_variables = $this->Conn->GetCol($sql, 'VariableName');
// go through mapping to preserve variable order
$value = Array ();
foreach ($profile_mapping as $from_name => $to_name) {
if (array_key_exists($from_name, $user_variables) && $user_variables[$from_name]) {
$value[] = $to_name;
}
}
if ($value) {
$fields_hash = Array (
'DisplayToPublic' => '|' . implode('|', $value) . '|',
);
$this->Conn->doUpdate($fields_hash, TABLE_PREFIX . 'PortalUser', 'PortalUserId = ' . $user_id);
}
// 3. delete old style variables
$sql = 'DELETE FROM ' . TABLE_PREFIX . 'PersistantSessionData
WHERE (PortalUserId = ' . $user_id . ') AND ' . $where_clause;
$this->Conn->Query($sql);
}
}
/**
* Update to 5.1.3; Merges column and field phrases
*
* @param string $mode when called mode {before, after)
*/
function Upgrade_5_1_3($mode)
{
if ( $mode == 'before' ) {
$this->_renameTables('from');
}
if ( $mode == 'after' ) {
$this->moveTranslation('LA_COL_', 'LA_FLD_', 'ColumnTranslation');
}
}
/**
* Makes sure table names match upgrade script
*
* @param string $key
* @return void
* @access private
*/
private function _renameTables($key)
{
foreach ($this->renamedTables as $prefix => $table_info) {
$this->Application->setUnitOption($prefix, 'TableName', TABLE_PREFIX . $table_info[$key]);
}
}
/**
* Update to 5.2.0-B1; Transform list sortings storage
*
* @param string $mode when called mode {before, after)
*/
public function Upgrade_5_2_0_B1($mode)
{
if ( $mode == 'before' ) {
$this->_renameTables('to');
}
if ( $mode == 'after' ) {
$this->transformSortings();
$this->moveTranslation('LA_COL_', 'LA_FLD_', 'ColumnTranslation'); // because of "la_col_ItemPrefix" phrase
$this->moveTranslation('LA_HINT_', 'LA_FLD_', 'HintTranslation');
$this->moveTranslation('LA_HINT_', 'LA_CONFIG_', 'HintTranslation');
$this->moveTranslation('LA_HINT_', 'LA_TITLE_', 'HintTranslation');
$this->createPageRevisions();
}
}
/**
* Transforms a way, how list sortings are stored
*
* @return void
*/
function transformSortings()
{
$sql = 'SELECT VariableName, PortalUserId
FROM ' . TABLE_PREFIX . 'UserPersistentSessionData
WHERE VariableName LIKE "%_Sort1.%"';
$sortings = $this->Conn->Query($sql);
foreach ($sortings AS $sorting) {
if ( !preg_match('/^(.*)_Sort1.(.*)$/', $sorting['VariableName'], $regs) ) {
continue;
}
$user_id = $sorting['PortalUserId'];
$prefix_special = $regs[1] . '_';
$view_name = '.' . $regs[2];
$old_variable_names = Array (
$prefix_special . 'Sort1' . $view_name, $prefix_special . 'Sort1_Dir' . $view_name,
$prefix_special . 'Sort2' . $view_name, $prefix_special . 'Sort2_Dir' . $view_name,
);
$old_variable_names = $this->Conn->qstrArray($old_variable_names);
$sql = 'SELECT VariableValue, VariableName
FROM ' . TABLE_PREFIX . 'UserPersistentSessionData
WHERE PortalUserId = ' . $user_id . ' AND VariableName IN (' . implode(',', $old_variable_names) . ')';
$sorting_data = $this->Conn->GetCol($sql, 'VariableName');
// prepare & save new sortings
$new_sorting = Array (
'Sort1' => $sorting_data[$prefix_special . 'Sort1' . $view_name],
'Sort1_Dir' => $sorting_data[$prefix_special . 'Sort1_Dir' . $view_name],
);
if ( isset($sorting_data[$prefix_special . 'Sort2' . $view_name]) ) {
$new_sorting['Sort2'] = $sorting_data[$prefix_special . 'Sort2' . $view_name];
$new_sorting['Sort2_Dir'] = $sorting_data[$prefix_special . 'Sort2_Dir' . $view_name];
}
$fields_hash = Array (
'PortalUserId' => $user_id,
'VariableName' => $prefix_special . 'Sortings' . $view_name,
'VariableValue' => serialize($new_sorting),
);
$this->Conn->doInsert($fields_hash, TABLE_PREFIX . 'UserPersistentSessionData');
// delete sortings, that were already processed
$sql = 'DELETE FROM ' . TABLE_PREFIX . 'UserPersistentSessionData
WHERE PortalUserId = ' . $user_id . ' AND VariableName IN (' . implode(',', $old_variable_names) . ')';
$this->Conn->Query($sql);
}
}
/**
* Merges several phrases into one (e.g. la_col_ + la_hint_ into designated columns of la_fld_ phrases)
*
* @param string $source_prefix
* @param string $target_prefix
* @param string $db_column
* @return void
* @access protected
*/
public function moveTranslation($source_prefix, $target_prefix, $db_column)
{
$source_phrases = $this->getPhrasesByMask($source_prefix . '%');
$target_phrases = $this->getPhrasesByMask($target_prefix . '%');
/** @var kMultiLanguageHelper $ml_helper */
$ml_helper = $this->Application->recallObject('kMultiLanguageHelper');
$delete_ids = Array ();
$ml_helper->createFields('phrases');
$languages = $ml_helper->getLanguages();
$phrase_table = $this->Application->getUnitOption('phrases', 'TableName');
foreach ($source_phrases as $phrase_key => $phrase_info) {
$target_phrase_key = $target_prefix . substr($phrase_key, strlen($source_prefix));
if ( !isset($target_phrases[$target_phrase_key]) ) {
continue;
}
$fields_hash = Array ();
// copy column phrase main translation into field phrase column translation
foreach ($languages as $language_id) {
$fields_hash['l' . $language_id . '_' . $db_column] = $phrase_info['l' . $language_id . '_Translation'];
}
$delete_ids[] = $phrase_info['PhraseId'];
$this->Conn->doUpdate($fields_hash, $phrase_table, 'PhraseId = ' . $target_phrases[$target_phrase_key]['PhraseId']);
}
// delete all column phrases, that were absorbed by field phrases
if ( $delete_ids ) {
$sql = 'DELETE FROM ' . $phrase_table . '
WHERE PhraseId IN (' . implode(',', $delete_ids) . ')';
$this->Conn->Query($sql);
$sql = 'DELETE FROM ' . TABLE_PREFIX . 'PhraseCache';
$this->Conn->Query($sql);
}
}
/**
* Returns phrases by mask
*
* @param string $mask
* @return Array
* @access protected
*/
protected function getPhrasesByMask($mask)
{
$sql = 'SELECT *
FROM ' . $this->Application->getUnitOption('phrases', 'TableName') . '
WHERE PhraseKey LIKE ' . $this->Conn->qstr($mask);
return $this->Conn->Query($sql, 'PhraseKey');
}
protected function createPageRevisions()
{
$sql = 'SELECT DISTINCT PageId
FROM ' . TABLE_PREFIX . 'PageContent';
$page_ids = $this->Conn->GetCol($sql);
foreach ($page_ids as $page_id) {
$fields_hash = Array (
'PageId' => $page_id,
'RevisionNumber' => 1,
'IsDraft' => 0,
'FromRevisionId' => 0,
'CreatedById' => USER_ROOT,
'CreatedOn' => adodb_mktime(),
'Status' => STATUS_ACTIVE,
);
$this->Conn->doInsert($fields_hash, TABLE_PREFIX . 'PageRevisions');
$fields_hash = Array (
'RevisionId' => $this->Conn->getInsertID(),
);
$this->Conn->doUpdate($fields_hash, TABLE_PREFIX . 'PageContent', 'PageId = ' . $page_id);
}
}
/**
* Update to 5.2.0-B3; Introduces separate field for plain-text e-mail event translations
*
* @param string $mode when called mode {before, after)
*/
public function Upgrade_5_2_0_B3($mode)
{
if ( $mode == 'before' ) {
$this->_renameTables('to');
}
if ( $mode == 'after' ) {
$this->_splitEmailBody();
$this->_migrateCommonFooter();
}
}
/**
* Splits e-mail body into HTML and Text fields
*
* @return void
* @access private
*/
private function _splitEmailBody()
{
$id_field = $this->Application->getUnitOption('email-template', 'IDField');
$table_name = $this->Application->getUnitOption('email-template', 'TableName');
$fields = $this->Conn->Query('DESCRIBE ' . $table_name, 'Field');
// The "_renameTables" method doesn't rename IDField, so find real one in DESCRIBE result.
if ( !isset($fields[$id_field]) ) {
$id_field = 'EventId';
}
if ( !isset($fields['l1_Body']) ) {
// column dropped - nothing to convert anymore
return;
}
/** @var kMultiLanguageHelper $ml_helper */
$ml_helper = $this->Application->recallObject('kMultiLanguageHelper');
$languages = $ml_helper->getLanguages();
$ml_helper->createFields('email-template');
$sql = 'SELECT *
FROM ' . $table_name;
$email_events = $this->Conn->Query($sql);
// 1. move data to new columns
foreach ($email_events as $email_event) {
$fields_hash = Array ();
$translation_field = $email_event['MessageType'] == 'html' ? 'HtmlBody' : 'PlainTextBody';
foreach ($languages as $language_id) {
$fields_hash['l' . $language_id . '_' . $translation_field] = $email_event['l' . $language_id . '_Body'];
}
if ( $fields_hash ) {
$this->Conn->doUpdate($fields_hash, $table_name, $id_field . ' = ' . $email_event[$id_field]);
}
}
// 2. drop old columns
$drops = Array ('DROP COLUMN MessageType');
foreach ($languages as $language_id) {
$lang_field = 'l' . $language_id . '_Body';
if ( isset($fields[$lang_field]) ) {
$drops[] = 'DROP COLUMN ' . $lang_field;
}
}
$this->Conn->Query('ALTER TABLE ' . $table_name . ' ' . implode(', ', $drops));
}
/**
* Transforms COMMON.FOOTER e-mail event into new field in Languages table
*/
private function _migrateCommonFooter()
{
/** @var kMultiLanguageHelper $ml_helper */
$ml_helper = $this->Application->recallObject('kMultiLanguageHelper');
$languages = $ml_helper->getLanguages();
$event_table = $this->Application->getUnitOption('email-template', 'TableName');
$sql = 'SELECT *
FROM ' . $event_table . '
WHERE Event = "COMMON.FOOTER"';
$footer_data = $this->Conn->GetRow($sql);
if ( !$footer_data ) {
return;
}
$primary_language_id = $this->Application->GetDefaultLanguageId();
$table_name = $this->Application->getUnitOption('lang', 'TableName');
foreach ($languages as $language_id) {
$is_primary = $language_id == $primary_language_id;
$fields_hash = Array (
'HtmlEmailTemplate' => $this->_appendEmailDesignBody($footer_data['l' . $language_id . '_HtmlBody'], $is_primary),
'TextEmailTemplate' => $this->_appendEmailDesignBody($footer_data['l' . $language_id . '_PlainTextBody'], $is_primary),
);
$this->Conn->doUpdate($fields_hash, $table_name, 'LanguageId = ' . $language_id);
}
$sql = 'DELETE FROM ' . $event_table . '
WHERE EventId = ' . $footer_data['EventId'];
$this->Conn->Query($sql);
}
/**
* Adds "$body" to given string
*
* @param string $string
* @param bool $is_primary for primary language
* @return string
* @access private
*/
private function _appendEmailDesignBody($string, $is_primary)
{
if ( !$string ) {
return $is_primary ? '$body' : $string;
}
return '$body' . "\n" . str_replace(Array ("\r\n", "\r"), "\n", $string);
}
/**
* Update to 5.2.0-RC1
*
* @param string $mode when called mode {before, after)
*/
public function Upgrade_5_2_0_RC1($mode)
{
if ( $mode != 'before' ) {
return;
}
/** @var kMultiLanguageHelper $ml_helper */
$ml_helper = $this->Application->recallObject('kMultiLanguageHelper');
// make some promo block fields translatable
$ml_helper->createFields('promo-block');
$table_name = $this->Application->getUnitOption('promo-block', 'TableName');
$table_structure = $this->Conn->Query('DESCRIBE ' . $table_name, 'Field');
if ( isset($table_structure['Title']) ) {
$sql = 'UPDATE ' . $table_name . '
SET l' . $this->Application->GetDefaultLanguageId() . '_Title = Title';
$this->Conn->Query($sql);
$sql = 'ALTER TABLE ' . $table_name . ' DROP Title';
$this->Conn->Query($sql);
}
// fix e-mail event translations
$languages = $ml_helper->getLanguages();
$table_name = $this->Application->getUnitOption('email-template', 'TableName');
$change_fields = Array ('Subject', 'HtmlBody', 'PlainTextBody');
foreach ($languages as $language_id) {
foreach ($change_fields as $change_field) {
$change_field = 'l' . $language_id . '_' . $change_field;
$sql = "UPDATE " . $table_name . "
SET {$change_field} = REPLACE({$change_field}, '<inp2:m_BaseUrl/>', '<inp2:m_Link template=\"index\"/>')
WHERE {$change_field} LIKE '%m_BaseURL%'";
$this->Conn->Query($sql);
}
}
// add new ml columns to phrases/e-mail events
$ml_helper->createFields('phrases');
$ml_helper->createFields('email-template');
}
/**
* Update to 5.2.0
*
* @param string $mode when called mode {before, after)
*/
public function Upgrade_5_2_0($mode)
{
if ( $mode != 'after' ) {
return;
}
$table_name = $this->Application->getUnitOption('c', 'TableName');
$sql = 'SELECT NamedParentPath, CachedTemplate, CategoryId
FROM ' . $table_name;
$categories = $this->Conn->GetIterator($sql);
foreach ($categories as $category_data) {
$fields_hash = Array (
'NamedParentPathHash' => kUtil::crc32(mb_strtolower(preg_replace('/^Content\//i', '', $category_data['NamedParentPath']))),
'CachedTemplateHash' => kUtil::crc32(mb_strtolower($category_data['CachedTemplate'])),
);
$this->Conn->doUpdate($fields_hash, $table_name, 'CategoryId = ' . $category_data['CategoryId']);
}
$rebuild_mode = $this->Application->ConfigValue('QuickCategoryPermissionRebuild') ? CategoryPermissionRebuild::SILENT : CategoryPermissionRebuild::AUTOMATIC;
$this->Application->SetConfigValue('CategoryPermissionRebuildMode', $rebuild_mode);
$sql = 'DELETE FROM ' . TABLE_PREFIX . 'SystemSettings WHERE VariableName = "QuickCategoryPermissionRebuild"';
$this->Conn->Query($sql);
$this->_updateScheduledTaskRunSchedule();
}
/**
* Transforms RunInterval into RunSchedule column for Scheduled Tasks
*
* @return void
* @access protected
*/
protected function _updateScheduledTaskRunSchedule()
{
// minute hour day_of_month month day_of_week
$id_field = $this->Application->getUnitOption('scheduled-task', 'IDField');
$table_name = $this->Application->getUnitOption('scheduled-task', 'TableName');
$sql = 'SELECT RunInterval, ' . $id_field . '
FROM ' . $table_name;
$run_intervals = $this->Conn->GetCol($sql, $id_field);
$ranges = Array (0 => 'min', 1 => 'hour', 2 => 'day', 3 => 'month');
$range_values = Array ('min' => 60, 'hour' => 60, 'day' => 24, 'month' => 30);
$range_masks = Array ('min' => '*/%s * * * *', 'hour' => '0 */%s * * *', 'day' => '0 0 */%s * *', 'month' => '0 0 1 */%s *');
foreach ($run_intervals as $scheduled_task_id => $interval) {
$mask_index = 'month';
foreach ($ranges as $range_index => $range_name) {
$range_value = $range_values[$range_name];
if ( $interval >= $range_value ) {
$interval = ceil($interval / $range_value);
}
else {
$mask_index = $ranges[$range_index - 1];
break;
}
}
$run_schedule = sprintf($range_masks[$mask_index], $interval);
if ( $run_schedule == '0 0 */7 * *' ) {
// once in 7 days = once in a week
$run_schedule = '0 0 * * 0';
}
$run_schedule = preg_replace('/(\*\/1( |$))/', '*\\2', $run_schedule);
$fields_hash = Array ('RunSchedule' => $run_schedule);
$this->Conn->doUpdate($fields_hash, $table_name, $id_field . ' = ' . $scheduled_task_id);
}
// drop RunInterval column
$this->Conn->Query('ALTER TABLE ' . $table_name . ' DROP RunInterval');
}
/**
* Update to 5.2.1-B1
*
* @param string $mode when called mode {before, after)
*/
public function Upgrade_5_2_1_B1($mode)
{
if ( $mode != 'after' ) {
return;
}
$this->_updateUserPasswords();
}
protected function _updateUserPasswords()
{
$user_table = $this->Application->getUnitOption('u', 'TableName');
$sql = 'SELECT Password, PortalUserId
FROM ' . $user_table . '
WHERE PasswordHashingMethod = ' . PasswordHashingMethod::MD5;
$user_passwords = $this->Conn->GetColIterator($sql, 'PortalUserId');
if ( !count($user_passwords) ) {
// no users at all or existing users have converted passwords already
return;
}
kUtil::setResourceLimit();
/** @var kPasswordFormatter $password_formatter */
$password_formatter = $this->Application->recallObject('kPasswordFormatter');
foreach ($user_passwords as $user_id => $user_password) {
$fields_hash = Array (
'Password' => $password_formatter->hashPassword($user_password, '', PasswordHashingMethod::MD5_AND_PHPPASS),
'PasswordHashingMethod' => PasswordHashingMethod::MD5_AND_PHPPASS,
);
$this->Conn->doUpdate($fields_hash, TABLE_PREFIX . 'Users', 'PortalUserId = ' . $user_id);
}
}
/**
* Update to 5.2.2-B1
*
* @param string $mode when called mode {before, after)
*/
public function Upgrade_5_2_2_B1($mode)
{
if ( $mode != 'after' ) {
return;
}
$this->deleteThumbnails();
}
/**
* Update to 5.2.2-B3
*
* @param string $mode When called mode {before, after).
*
* @return void
*/
public function Upgrade_5_2_2_B3($mode)
{
if ( $mode === 'after' ) {
$this->migrateExportUserPresets();
+ $this->changeSessionKeyFormat();
}
if ( $mode != 'before' ) {
return;
}
/** @var kMultiLanguageHelper $ml_helper */
$ml_helper = $this->Application->recallObject('kMultiLanguageHelper');
$ml_helper->createFields('page-revision');
/** @var PageHelper $page_helper */
$page_helper = $this->Application->recallObject('PageHelper');
$table_name = TABLE_PREFIX . 'PageRevisions';
$sql = 'SELECT RevisionId
FROM ' . $table_name;
$ids = $this->Conn->GetColIterator($sql);
foreach ( $ids as $id ) {
$this->Conn->doUpdate($page_helper->getRevisionContent($id), $table_name, 'RevisionId = ' . $id);
}
}
/**
* Deletes folders, containing thumbnails recursively.
*
* @param string $folder Folder.
*
* @return void
*/
protected function deleteThumbnails($folder = WRITEABLE)
{
foreach ( glob($folder . '/*', GLOB_ONLYDIR) as $sub_folder ) {
if ( $sub_folder === WRITEABLE . '/cache' ) {
continue;
}
if ( basename($sub_folder) === 'resized' ) {
$files = glob($sub_folder . '/*');
array_map('unlink', $files);
rmdir($sub_folder);
}
else {
$this->deleteThumbnails($sub_folder);
}
}
}
/**
* Transforms "export_settings" persistent session variable into "ExportUserPresets" database table.
*
* @return void
*/
protected function migrateExportUserPresets()
{
$sql = 'SELECT VariableValue, PortalUserId
FROM ' . TABLE_PREFIX . 'UserPersistentSessionData
WHERE VariableName = "export_settings"';
$variable_values = $this->Conn->GetColIterator($sql, 'PortalUserId');
foreach ( $variable_values as $user_id => $variable_value ) {
if ( !kUtil::IsSerialized($variable_value) ) {
continue;
}
$variable_value = unserialize($variable_value);
foreach ( $variable_value as $prefix => $prefix_export_settings ) {
foreach ( $prefix_export_settings as $name => $export_settings ) {
$fields_hash = array(
'PortalUserId' => $user_id,
'ItemPrefix' => $prefix,
'PresetName' => $name,
'PresetData' => json_encode($export_settings),
);
$this->Conn->doInsert($fields_hash, TABLE_PREFIX . 'ExportUserPresets', 'REPLACE');
}
}
}
$sql = 'DELETE
FROM ' . TABLE_PREFIX . 'UserPersistentSessionData
WHERE VariableName = "export_settings"';
$this->Conn->Query($sql);
}
+ /**
+ * Transforms the way, how "SessionKey" is stored in the database.
+ *
+ * @return void
+ */
+ protected function changeSessionKeyFormat()
+ {
+ $sql = 'SELECT SessionId, SessionKey
+ FROM ' . TABLE_PREFIX . 'UserSessions';
+ $session_mapping = $this->Conn->GetCol($sql, 'SessionKey');
+
+ // 1. Replace session key with session id.
+ foreach ( $session_mapping as $session_key => $session_id ) {
+ // Ignore already converted data.
+ if ( !is_numeric($session_key) ) {
+ continue;
+ }
+
+ $this->Conn->doUpdate(
+ array('SessionId' => $session_id),
+ TABLE_PREFIX . 'UserSessionData',
+ 'SessionId = ' . $session_key
+ );
+
+ $this->Conn->doUpdate(
+ array('SessionId' => $session_id),
+ TABLE_PREFIX . 'UserSessionLogs',
+ 'SessionId = ' . $session_key
+ );
+ }
+
+ // 2. Rename temporary tables.
+ $tables = $this->Conn->GetCol('SHOW TABLES LIKE "%' . TABLE_PREFIX . 'ses_%"');
+ $mask_edit_table = '/' . TABLE_PREFIX . 'ses_(.*)_edit_(.*)/';
+ $mask_search_table = '/' . TABLE_PREFIX . 'ses_(.*?)_(.*)/';
+
+ foreach ( $tables as $table ) {
+ if ( preg_match($mask_edit_table, $table, $rets) || preg_match($mask_search_table, $table, $rets) ) {
+ $old_table_name_fragment = $rets[1];
+ $new_table_name_fragment = $this->replaceSessionKeyWithSessionId(
+ $old_table_name_fragment,
+ $session_mapping
+ );
+
+ if ( $old_table_name_fragment === $new_table_name_fragment ) {
+ continue;
+ }
+
+ $new_table = str_replace(
+ '_' . $old_table_name_fragment . '_',
+ '_' . $new_table_name_fragment . '_',
+ $table
+ );
+
+ $this->Conn->Query('RENAME TABLE `' . $table . '` TO `' . $new_table . '`');
+ }
+ }
+
+ // 3. Replace plain-text session key storage with hashed one.
+ /** @var SecurityEncrypter $encrypter */
+ $encrypter = $this->Application->recallObject('SecurityEncrypter');
+
+ $tables_with_session_keys = array(
+ TABLE_PREFIX . 'UserSessions' => array('SessionKey', 'SessionId'),
+ TABLE_PREFIX . 'Semaphores' => array('SessionKey', 'SemaphoreId'),
+ TABLE_PREFIX . 'UserSessionLogs' => array('SessionKey', 'SessionLogId'),
+ TABLE_PREFIX . 'CurlLog' => array('SessionKey', 'LogId'),
+ TABLE_PREFIX . 'SystemLog' => array('LogSessionKey', 'LogId'),
+ );
+
+ foreach ( $tables_with_session_keys as $table => $fields ) {
+ list($session_key_field, $id_field) = $fields;
+
+ $sql = 'SELECT ' . $session_key_field . ', ' . $id_field . '
+ FROM ' . $table;
+ $table_records = $this->Conn->GetCol($sql, $id_field);
+
+ foreach ( $table_records as $record_id => $session_key ) {
+ // Ignore already converted data.
+ if ( !is_numeric($session_key) ) {
+ continue;
+ }
+
+ $this->Conn->doUpdate(
+ array($session_key_field => $encrypter->createSignature($session_key)),
+ $table,
+ $id_field . ' = ' . $record_id
+ );
+ }
+ }
+ }
+
+ /**
+ * Replaces session key with session id in the given table name fragment.
+ *
+ * @param string $table_name_fragment Table name fragment.
+ * @param array $session_mapping Session mapping.
+ *
+ * @return string
+ */
+ protected function replaceSessionKeyWithSessionId($table_name_fragment, array $session_mapping)
+ {
+ $table_name_fragment_parts = explode('_', $table_name_fragment);
+ $session_key = $table_name_fragment_parts[0];
+
+ if ( array_key_exists($session_key, $session_mapping) ) {
+ $table_name_fragment_parts[0] = $session_mapping[$session_key];
+ }
+
+ return implode('_', $table_name_fragment_parts);
+ }
+
}
Index: branches/5.2.x/core/install/upgrades.sql
===================================================================
--- branches/5.2.x/core/install/upgrades.sql (revision 16796)
+++ branches/5.2.x/core/install/upgrades.sql (revision 16797)
@@ -1,2982 +1,2988 @@
# ===== 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;
INSERT 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);
INSERT INTO ConfigurationAdmin VALUES ('CSVExportEnclosure', 'la_Text_CSV_Export', 'la_config_CSVExportEnclosure', 'radio', NULL, '0=la_Doublequotes,1=la_Quotes', 40.2, 0, 1);
INSERT INTO ConfigurationAdmin VALUES ('CSVExportSeparator', 'la_Text_CSV_Export', 'la_config_CSVExportSeparator', 'radio', NULL, '0=la_Linux,1=la_Windows', 40.3, 0, 1);
INSERT INTO ConfigurationAdmin VALUES ('CSVExportEncoding', 'la_Text_CSV_Export', 'la_config_CSVExportEncoding', 'radio', NULL, '0=la_Unicode,1=la_Regular', 40.4, 0, 1);
INSERT INTO ConfigurationValues VALUES (DEFAULT, 'CSVExportDelimiter', '0', 'In-Portal', 'in-portal:configure_general');
INSERT INTO ConfigurationValues VALUES (DEFAULT, 'CSVExportEnclosure', '0', 'In-Portal', 'in-portal:configure_general');
INSERT INTO ConfigurationValues VALUES (DEFAULT, 'CSVExportSeparator', '0', 'In-Portal', 'in-portal:configure_general');
INSERT 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, 'In-Portal', '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, 'In-Portal', '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, 'In-Portal', 'in-portal:configure_general');
ALTER TABLE PersistantSessionData ADD VariableId BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST;
# ===== v 4.3.0 =====
INSERT INTO ConfigurationAdmin VALUES ('u_MaxImageCount', 'la_section_ImageSettings', 'la_config_MaxImageCount', 'text', '', '', 30.01, 0, 0);
INSERT INTO ConfigurationAdmin VALUES ('u_ThumbnailImageWidth', 'la_section_ImageSettings', 'la_config_ThumbnailImageWidth', 'text', '', '', 30.02, 0, 0);
INSERT INTO ConfigurationAdmin VALUES ('u_ThumbnailImageHeight', 'la_section_ImageSettings', 'la_config_ThumbnailImageHeight', 'text', '', '', 30.03, 0, 0);
INSERT INTO ConfigurationAdmin VALUES ('u_FullImageWidth', 'la_section_ImageSettings', 'la_config_FullImageWidth', 'text', '', '', 30.04, 0, 0);
INSERT INTO ConfigurationAdmin VALUES ('u_FullImageHeight', 'la_section_ImageSettings', 'la_config_FullImageHeight', 'text', '', '', 30.05, 0, 0);
INSERT INTO ConfigurationValues VALUES (DEFAULT, 'u_MaxImageCount', 5, 'In-Portal:Users', 'in-portal:configure_users');
INSERT INTO ConfigurationValues VALUES (DEFAULT, 'u_ThumbnailImageWidth', 120, 'In-Portal:Users', 'in-portal:configure_users');
INSERT INTO ConfigurationValues VALUES (DEFAULT, 'u_ThumbnailImageHeight', 120, 'In-Portal:Users', 'in-portal:configure_users');
INSERT INTO ConfigurationValues VALUES (DEFAULT, 'u_FullImageWidth', 450, 'In-Portal:Users', 'in-portal:configure_users');
INSERT INTO ConfigurationValues VALUES (DEFAULT, 'u_FullImageHeight', 450, 'In-Portal:Users', 'in-portal:configure_users');
CREATE TABLE ChangeLogs (
ChangeLogId bigint(20) NOT NULL auto_increment,
PortalUserId int(11) NOT NULL default '0',
SessionLogId int(11) NOT NULL default '0',
`Action` tinyint(4) NOT NULL default '0',
OccuredOn int(11) NOT NULL default '0',
Prefix varchar(255) NOT NULL default '',
ItemId bigint(20) NOT NULL default '0',
Changes text NOT NULL,
MasterPrefix varchar(255) NOT NULL default '',
MasterId bigint(20) NOT NULL default '0',
PRIMARY KEY (ChangeLogId),
KEY PortalUserId (PortalUserId),
KEY SessionLogId (SessionLogId),
KEY `Action` (`Action`),
KEY OccuredOn (OccuredOn),
KEY Prefix (Prefix),
KEY MasterPrefix (MasterPrefix)
);
CREATE TABLE SessionLogs (
SessionLogId bigint(20) NOT NULL auto_increment,
PortalUserId int(11) NOT NULL default '0',
SessionId int(10) NOT NULL default '0',
`Status` tinyint(4) NOT NULL default '1',
SessionStart int(11) NOT NULL default '0',
SessionEnd int(11) default NULL,
IP varchar(15) NOT NULL default '',
AffectedItems int(11) NOT NULL default '0',
PRIMARY KEY (SessionLogId),
KEY SessionId (SessionId),
KEY `Status` (`Status`),
KEY PortalUserId (PortalUserId)
);
ALTER TABLE CustomField ADD INDEX (MultiLingual), ADD INDEX (DisplayOrder), ADD INDEX (OnGeneralTab), ADD INDEX (IsSystem);
ALTER TABLE ConfigurationAdmin ADD INDEX (DisplayOrder), ADD INDEX (GroupDisplayOrder), ADD INDEX (Install);
ALTER TABLE EmailSubscribers ADD INDEX (EmailMessageId), ADD INDEX (PortalUserId);
ALTER TABLE Events ADD INDEX (`Type`), ADD INDEX (Enabled);
ALTER TABLE Language ADD INDEX (Enabled), ADD INDEX (PrimaryLang), ADD INDEX (AdminInterfaceLang), ADD INDEX (Priority);
ALTER TABLE Modules ADD INDEX (Loaded), ADD INDEX (LoadOrder);
ALTER TABLE PhraseCache ADD INDEX (CacheDate), ADD INDEX (ThemeId), ADD INDEX (StylesheetId);
ALTER TABLE PortalGroup ADD INDEX (CreatedOn);
ALTER TABLE PortalUser ADD INDEX (Status), ADD INDEX (Modified), ADD INDEX (dob), ADD INDEX (IsBanned);
ALTER TABLE Theme ADD INDEX (Enabled), ADD INDEX (StylesheetId), ADD INDEX (PrimaryTheme);
ALTER TABLE UserGroup ADD INDEX (MembershipExpires), ADD INDEX (ExpirationReminderSent);
ALTER TABLE EmailLog ADD INDEX (`timestamp`);
ALTER TABLE StdDestinations ADD INDEX (DestType), ADD INDEX (DestParentId);
ALTER TABLE Category ADD INDEX (Status), ADD INDEX (CreatedOn), ADD INDEX (EditorsPick);
ALTER TABLE Stylesheets ADD INDEX (Enabled), ADD INDEX (LastCompiled);
ALTER TABLE Counters ADD INDEX (IsClone), ADD INDEX (LifeTime), ADD INDEX (LastCounted);
ALTER TABLE Skins ADD INDEX (IsPrimary), ADD INDEX (LastCompiled);
INSERT INTO ConfigurationAdmin VALUES ('UseChangeLog', 'la_Text_Website', 'la_config_UseChangeLog', 'checkbox', '', '', 10.25, 0, 0);
INSERT INTO ConfigurationValues VALUES (DEFAULT, 'UseChangeLog', '0', 'In-Portal', 'in-portal:configure_general');
INSERT INTO ConfigurationAdmin VALUES ('AutoRefreshIntervals', 'la_Text_Website', 'la_config_AutoRefreshIntervals', 'text', '', '', 10.26, 0, 0);
INSERT INTO ConfigurationValues VALUES (DEFAULT, 'AutoRefreshIntervals', '1,5,15,30,60,120,240', 'In-Portal', 'in-portal:configure_general');
DELETE FROM Cache WHERE SUBSTRING(VarName, 1, 7) = 'mod_rw_';
ALTER TABLE Category CHANGE `Status` `Status` TINYINT(4) NOT NULL DEFAULT '2';
# ===== v 4.3.1 =====
INSERT INTO ConfigurationAdmin VALUES ('RememberLastAdminTemplate', 'la_Text_General', 'la_config_RememberLastAdminTemplate', 'checkbox', '', '', 10.13, 0, 0);
INSERT INTO ConfigurationValues VALUES (DEFAULT, 'RememberLastAdminTemplate', '', 'In-Portal:Users', 'in-portal:configure_users');
INSERT INTO ConfigurationAdmin VALUES ('AllowSelectGroupOnFront', 'la_Text_General', 'la_config_AllowSelectGroupOnFront', 'checkbox', NULL, NULL, 10.13, 0, 0);
INSERT INTO ConfigurationValues VALUES (DEFAULT, 'AllowSelectGroupOnFront', '0', 'In-Portal:Users', 'in-portal:configure_users');
CREATE TABLE StatisticsCapture (
StatisticsId int(10) unsigned NOT NULL auto_increment,
TemplateName varchar(255) NOT NULL default '',
Hits int(10) unsigned NOT NULL default '0',
LastHit int(11) NOT NULL default '0',
ScriptTimeMin decimal(40,20) unsigned NOT NULL default '0.00000000000000000000',
ScriptTimeAvg decimal(40,20) unsigned NOT NULL default '0.00000000000000000000',
ScriptTimeMax decimal(40,20) unsigned NOT NULL default '0.00000000000000000000',
SqlTimeMin decimal(40,20) unsigned NOT NULL default '0.00000000000000000000',
SqlTimeAvg decimal(40,20) unsigned NOT NULL default '0.00000000000000000000',
SqlTimeMax decimal(40,20) unsigned NOT NULL default '0.00000000000000000000',
SqlCountMin decimal(40,20) unsigned NOT NULL default '0.00000000000000000000',
SqlCountAvg decimal(40,20) unsigned NOT NULL default '0.00000000000000000000',
SqlCountMax decimal(40,20) unsigned NOT NULL default '0.00000000000000000000',
PRIMARY KEY (StatisticsId),
KEY TemplateName (TemplateName),
KEY Hits (Hits),
KEY LastHit (LastHit),
KEY ScriptTimeMin (ScriptTimeMin),
KEY ScriptTimeAvg (ScriptTimeAvg),
KEY ScriptTimeMax (ScriptTimeMax),
KEY SqlTimeMin (SqlTimeMin),
KEY SqlTimeAvg (SqlTimeAvg),
KEY SqlTimeMax (SqlTimeMax),
KEY SqlCountMin (SqlCountMin),
KEY SqlCountAvg (SqlCountAvg),
KEY SqlCountMax (SqlCountMax)
);
CREATE TABLE SlowSqlCapture (
CaptureId int(10) unsigned NOT NULL auto_increment,
TemplateNames text,
Hits int(10) unsigned NOT NULL default '0',
LastHit int(11) NOT NULL default '0',
SqlQuery text,
TimeMin decimal(40,20) unsigned NOT NULL default '0.00000000000000000000',
TimeAvg decimal(40,20) unsigned NOT NULL default '0.00000000000000000000',
TimeMax decimal(40,20) unsigned NOT NULL default '0.00000000000000000000',
QueryCrc int(11) NOT NULL default '0',
PRIMARY KEY (CaptureId),
KEY Hits (Hits),
KEY LastHit (LastHit),
KEY TimeMin (TimeMin),
KEY TimeAvg (TimeAvg),
KEY TimeMax (TimeMax),
KEY QueryCrc (QueryCrc)
);
ALTER TABLE PortalGroup ADD FrontRegistration TINYINT UNSIGNED NOT NULL;
UPDATE PortalGroup SET FrontRegistration = 1 WHERE GroupId = 13;
INSERT INTO ConfigurationAdmin VALUES ('ForceImageMagickResize', 'la_Text_Website', 'la_config_ForceImageMagickResize', 'checkbox', '', '', 10.28, 0, 0);
INSERT INTO ConfigurationValues VALUES (DEFAULT, 'ForceImageMagickResize', '0', 'In-Portal', 'in-portal:configure_general');
INSERT INTO ConfigurationAdmin VALUES ('AdminSSL_URL', 'la_Text_Website', 'la_config_AdminSSL_URL', 'text', '', '', 10.091, 0, 0);
INSERT INTO ConfigurationValues VALUES (DEFAULT, 'AdminSSL_URL', '', 'In-Portal', 'in-portal:configure_general');
# ===== v 4.3.9 =====
ALTER TABLE CustomField
CHANGE ValueList ValueList TEXT NULL DEFAULT NULL,
ADD DefaultValue VARCHAR(255) NOT NULL AFTER ValueList,
ADD INDEX (DefaultValue);
UPDATE CustomField SET ValueList = REPLACE(ValueList, ',', '||');
CREATE TABLE Agents (
AgentId int(11) NOT NULL auto_increment,
AgentName varchar(255) NOT NULL default '',
AgentType tinyint(3) unsigned NOT NULL default '1',
Status tinyint(3) unsigned NOT NULL default '1',
Event varchar(255) NOT NULL default '',
RunInterval int(10) unsigned NOT NULL default '0',
RunMode tinyint(3) unsigned NOT NULL default '2',
LastRunOn int(10) unsigned default NULL,
LastRunStatus tinyint(3) unsigned NOT NULL default '1',
NextRunOn int(11) default NULL,
RunTime int(10) unsigned NOT NULL default '0',
PRIMARY KEY (AgentId),
KEY Status (Status),
KEY RunInterval (RunInterval),
KEY RunMode (RunMode),
KEY AgentType (AgentType),
KEY LastRunOn (LastRunOn),
KEY LastRunStatus (LastRunStatus),
KEY RunTime (RunTime),
KEY NextRunOn (NextRunOn)
);
INSERT INTO Permissions VALUES(DEFAULT, 'in-portal:agents.delete', 11, 1, 1, 0);
INSERT INTO Permissions VALUES(DEFAULT, 'in-portal:agents.edit', 11, 1, 1, 0);
INSERT INTO Permissions VALUES(DEFAULT, 'in-portal:agents.add', 11, 1, 1, 0);
INSERT INTO Permissions VALUES(DEFAULT, 'in-portal:agents.view', 11, 1, 1, 0);
INSERT INTO ConfigurationAdmin VALUES ('FilenameSpecialCharReplacement', 'la_Text_General', 'la_config_FilenameSpecialCharReplacement', 'select', NULL, '_=+_,-=+-', 10.16, 0, 0);
INSERT INTO ConfigurationValues VALUES (DEFAULT, 'FilenameSpecialCharReplacement', '_', 'In-Portal', 'in-portal:configure_categories');
CREATE TABLE SpellingDictionary (
SpellingDictionaryId int(11) NOT NULL auto_increment,
MisspelledWord varchar(255) NOT NULL default '',
SuggestedCorrection varchar(255) NOT NULL default '',
PRIMARY KEY (SpellingDictionaryId),
KEY MisspelledWord (MisspelledWord),
KEY SuggestedCorrection (SuggestedCorrection)
);
INSERT INTO ConfigurationValues VALUES(NULL, 'YahooApplicationId', '', 'In-Portal', 'in-portal:configure_categories');
INSERT INTO ConfigurationAdmin VALUES('YahooApplicationId', 'la_Text_General', 'la_config_YahooApplicationId', 'text', NULL, NULL, 10.15, 0, 0);
CREATE TABLE Thesaurus (
ThesaurusId int(11) NOT NULL auto_increment,
SearchTerm varchar(255) NOT NULL default '',
ThesaurusTerm varchar(255) NOT NULL default '',
ThesaurusType tinyint(3) unsigned NOT NULL default '0',
PRIMARY KEY (ThesaurusId),
KEY ThesaurusType (ThesaurusType),
KEY SearchTerm (SearchTerm)
);
INSERT INTO Permissions VALUES (DEFAULT, 'in-portal:ban_rulelist.delete', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-portal:ban_rulelist.edit', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-portal:ban_rulelist.add', 11, 1, 1, 0);
ALTER TABLE Language ADD FilenameReplacements TEXT NULL AFTER UnitSystem;
ALTER TABLE Language ADD Locale varchar(10) NOT NULL default 'en-US' AFTER FilenameReplacements;
CREATE TABLE LocalesList (
LocaleId int(11) NOT NULL auto_increment,
LocaleIdentifier varchar(6) NOT NULL default '',
LocaleName varchar(255) NOT NULL default '',
Locale varchar(20) NOT NULL default '',
ScriptTag varchar(255) NOT NULL default '',
ANSICodePage varchar(10) NOT NULL default '',
PRIMARY KEY (LocaleId)
);
INSERT INTO LocalesList VALUES
(1, '0x0436', 'Afrikaans (South Africa)', 'af-ZA', 'Latn', '1252'),
(2, '0x041c', 'Albanian (Albania)', 'sq-AL', 'Latn', '1252'),
(3, '0x0484', 'Alsatian (France)', 'gsw-FR', '', ''),
(4, '0x045e', 'Amharic (Ethiopia)', 'am-ET', '', 'UTF-8'),
(5, '0x1401', 'Arabic (Algeria)', 'ar-DZ', 'Arab', '1256'),
(6, '0x3c01', 'Arabic (Bahrain)', 'ar-BH', 'Arab', '1256'),
(7, '0x0c01', 'Arabic (Egypt)', 'ar-EG', 'Arab', '1256'),
(8, '0x0801', 'Arabic (Iraq)', 'ar-IQ', 'Arab', '1256'),
(9, '0x2c01', 'Arabic (Jordan)', 'ar-JO', 'Arab', '1256'),
(10, '0x3401', 'Arabic (Kuwait)', 'ar-KW', 'Arab', '1256'),
(11, '0x3001', 'Arabic (Lebanon)', 'ar-LB', 'Arab', '1256'),
(12, '0x1001', 'Arabic (Libya)', 'ar-LY', 'Arab', '1256'),
(13, '0x1801', 'Arabic (Morocco)', 'ar-MA', 'Arab', '1256'),
(14, '0x2001', 'Arabic (Oman)', 'ar-OM', 'Arab', '1256'),
(15, '0x4001', 'Arabic (Qatar)', 'ar-QA', 'Arab', '1256'),
(16, '0x0401', 'Arabic (Saudi Arabia)', 'ar-SA', 'Arab', '1256'),
(17, '0x2801', 'Arabic (Syria)', 'ar-SY', 'Arab', '1256'),
(18, '0x1c01', 'Arabic (Tunisia)', 'ar-TN', 'Arab', '1256'),
(19, '0x3801', 'Arabic (U.A.E.)', 'ar-AE', 'Arab', '1256'),
(20, '0x2401', 'Arabic (Yemen)', 'ar-YE', 'Arab', '1256'),
(21, '0x042b', 'Armenian (Armenia)', 'hy-AM', 'Armn', 'UTF-8'),
(22, '0x044d', 'Assamese (India)', 'as-IN', '', 'UTF-8'),
(23, '0x082c', 'Azeri (Azerbaijan, Cyrillic)', 'az-Cyrl-AZ', 'Cyrl', '1251'),
(24, '0x042c', 'Azeri (Azerbaijan, Latin)', 'az-Latn-AZ', 'Latn', '1254'),
(25, '0x046d', 'Bashkir (Russia)', 'ba-RU', '', ''),
(26, '0x042d', 'Basque (Basque)', 'eu-ES', 'Latn', '1252'),
(27, '0x0423', 'Belarusian (Belarus)', 'be-BY', 'Cyrl', '1251'),
(28, '0x0445', 'Bengali (India)', 'bn-IN', 'Beng', 'UTF-8'),
(29, '0x201a', 'Bosnian (Bosnia and Herzegovina, Cyrillic)', 'bs-Cyrl-BA', 'Cyrl', '1251'),
(30, '0x141a', 'Bosnian (Bosnia and Herzegovina, Latin)', 'bs-Latn-BA', 'Latn', '1250'),
(31, '0x047e', 'Breton (France)', 'br-FR', 'Latn', '1252'),
(32, '0x0402', 'Bulgarian (Bulgaria)', 'bg-BG', 'Cyrl', '1251'),
(33, '0x0403', 'Catalan (Catalan)', 'ca-ES', 'Latn', '1252'),
(34, '0x0c04', 'Chinese (Hong Kong SAR, PRC)', 'zh-HK', 'Hant', '950'),
(35, '0x1404', 'Chinese (Macao SAR)', 'zh-MO', 'Hant', '950'),
(36, '0x0804', 'Chinese (PRC)', 'zh-CN', 'Hans', '936'),
(37, '0x1004', 'Chinese (Singapore)', 'zh-SG', 'Hans', '936'),
(38, '0x0404', 'Chinese (Taiwan)', 'zh-TW', 'Hant', '950'),
(39, '0x101a', 'Croatian (Bosnia and Herzegovina, Latin)', 'hr-BA', 'Latn', '1250'),
(40, '0x041a', 'Croatian (Croatia)', 'hr-HR', 'Latn', '1250'),
(41, '0x0405', 'Czech (Czech Republic)', 'cs-CZ', 'Latn', '1250'),
(42, '0x0406', 'Danish (Denmark)', 'da-DK', 'Latn', '1252'),
(43, '0x048c', 'Dari (Afghanistan)', 'prs-AF', 'Arab', '1256'),
(44, '0x0465', 'Divehi (Maldives)', 'dv-MV', 'Thaa', 'UTF-8'),
(45, '0x0813', 'Dutch (Belgium)', 'nl-BE', 'Latn', '1252'),
(46, '0x0413', 'Dutch (Netherlands)', 'nl-NL', 'Latn', '1252'),
(47, '0x0c09', 'English (Australia)', 'en-AU', 'Latn', '1252'),
(48, '0x2809', 'English (Belize)', 'en-BZ', 'Latn', '1252'),
(49, '0x1009', 'English (Canada)', 'en-CA', 'Latn', '1252'),
(50, '0x2409', 'English (Caribbean)', 'en-029', 'Latn', '1252'),
(51, '0x4009', 'English (India)', 'en-IN', 'Latn', '1252'),
(52, '0x1809', 'English (Ireland)', 'en-IE', 'Latn', '1252'),
(53, '0x2009', 'English (Jamaica)', 'en-JM', 'Latn', '1252'),
(54, '0x4409', 'English (Malaysia)', 'en-MY', 'Latn', '1252'),
(55, '0x1409', 'English (New Zealand)', 'en-NZ', 'Latn', '1252'),
(56, '0x3409', 'English (Philippines)', 'en-PH', 'Latn', '1252'),
(57, '0x4809', 'English (Singapore)', 'en-SG', 'Latn', '1252'),
(58, '0x1c09', 'English (South Africa)', 'en-ZA', 'Latn', '1252'),
(59, '0x2c09', 'English (Trinidad and Tobago)', 'en-TT', 'Latn', '1252'),
(60, '0x0809', 'English (United Kingdom)', 'en-GB', 'Latn', '1252'),
(61, '0x0409', 'English (United States)', 'en-US', 'Latn', '1252'),
(62, '0x3009', 'English (Zimbabwe)', 'en-ZW', 'Latn', '1252'),
(63, '0x0425', 'Estonian (Estonia)', 'et-EE', 'Latn', '1257'),
(64, '0x0438', 'Faroese (Faroe Islands)', 'fo-FO', 'Latn', '1252'),
(65, '0x0464', 'Filipino (Philippines)', 'fil-PH', 'Latn', '1252'),
(66, '0x040b', 'Finnish (Finland)', 'fi-FI', 'Latn', '1252'),
(67, '0x080c', 'French (Belgium)', 'fr-BE', 'Latn', '1252'),
(68, '0x0c0c', 'French (Canada)', 'fr-CA', 'Latn', '1252'),
(69, '0x040c', 'French (France)', 'fr-FR', 'Latn', '1252'),
(70, '0x140c', 'French (Luxembourg)', 'fr-LU', 'Latn', '1252'),
(71, '0x180c', 'French (Monaco)', 'fr-MC', 'Latn', '1252'),
(72, '0x100c', 'French (Switzerland)', 'fr-CH', 'Latn', '1252'),
(73, '0x0462', 'Frisian (Netherlands)', 'fy-NL', 'Latn', '1252'),
(74, '0x0456', 'Galician (Spain)', 'gl-ES', 'Latn', '1252'),
(75, '0x0437', 'Georgian (Georgia)', 'ka-GE', 'Geor', 'UTF-8'),
(76, '0x0c07', 'German (Austria)', 'de-AT', 'Latn', '1252'),
(77, '0x0407', 'German (Germany)', 'de-DE', 'Latn', '1252'),
(78, '0x1407', 'German (Liechtenstein)', 'de-LI', 'Latn', '1252'),
(79, '0x1007', 'German (Luxembourg)', 'de-LU', 'Latn', '1252'),
(80, '0x0807', 'German (Switzerland)', 'de-CH', 'Latn', '1252'),
(81, '0x0408', 'Greek (Greece)', 'el-GR', 'Grek', '1253'),
(82, '0x046f', 'Greenlandic (Greenland)', 'kl-GL', 'Latn', '1252'),
(83, '0x0447', 'Gujarati (India)', 'gu-IN', 'Gujr', 'UTF-8'),
(84, '0x0468', 'Hausa (Nigeria, Latin)', 'ha-Latn-NG', 'Latn', '1252'),
(85, '0x040d', 'Hebrew (Israel)', 'he-IL', 'Hebr', '1255'),
(86, '0x0439', 'Hindi (India)', 'hi-IN', 'Deva', 'UTF-8'),
(87, '0x040e', 'Hungarian (Hungary)', 'hu-HU', 'Latn', '1250'),
(88, '0x040f', 'Icelandic (Iceland)', 'is-IS', 'Latn', '1252'),
(89, '0x0470', 'Igbo (Nigeria)', 'ig-NG', '', ''),
(90, '0x0421', 'Indonesian (Indonesia)', 'id-ID', 'Latn', '1252'),
(91, '0x085d', 'Inuktitut (Canada, Latin)', 'iu-Latn-CA', 'Latn', '1252'),
(92, '0x045d', 'Inuktitut (Canada, Syllabics)', 'iu-Cans-CA', 'Cans', 'UTF-8'),
(93, '0x083c', 'Irish (Ireland)', 'ga-IE', 'Latn', '1252'),
(94, '0x0410', 'Italian (Italy)', 'it-IT', 'Latn', '1252'),
(95, '0x0810', 'Italian (Switzerland)', 'it-CH', 'Latn', '1252'),
(96, '0x0411', 'Japanese (Japan)', 'ja-JP', 'Hani;Hira;Kana', '932'),
(97, '0x044b', 'Kannada (India)', 'kn-IN', 'Knda', 'UTF-8'),
(98, '0x043f', 'Kazakh (Kazakhstan)', 'kk-KZ', 'Cyrl', '1251'),
(99, '0x0453', 'Khmer (Cambodia)', 'kh-KH', 'Khmr', 'UTF-8'),
(100, '0x0486', 'K''iche (Guatemala)', 'qut-GT', 'Latn', '1252'),
(101, '0x0487', 'Kinyarwanda (Rwanda)', 'rw-RW', 'Latn', '1252'),
(102, '0x0457', 'Konkani (India)', 'kok-IN', 'Deva', 'UTF-8'),
(103, '0x0812', 'Windows 95, Windows NT 4.0 only: Korean (Johab)', '', '', ''),
(104, '0x0412', 'Korean (Korea)', 'ko-KR', 'Hang;Hani', '949'),
(105, '0x0440', 'Kyrgyz (Kyrgyzstan)', 'ky-KG', 'Cyrl', '1251'),
(106, '0x0454', 'Lao (Lao PDR)', 'lo-LA', 'Laoo', 'UTF-8'),
(107, '0x0426', 'Latvian (Latvia)', 'lv-LV', 'Latn', '1257'),
(108, '0x0427', 'Lithuanian (Lithuania)', 'lt-LT', 'Latn', '1257'),
(109, '0x082e', 'Lower Sorbian (Germany)', 'dsb-DE', 'Latn', '1252'),
(110, '0x046e', 'Luxembourgish (Luxembourg)', 'lb-LU', 'Latn', '1252'),
(111, '0x042f', 'Macedonian (Macedonia, FYROM)', 'mk-MK', 'Cyrl', '1251'),
(112, '0x083e', 'Malay (Brunei Darussalam)', 'ms-BN', 'Latn', '1252'),
(113, '0x043e', 'Malay (Malaysia)', 'ms-MY', 'Latn', '1252'),
(114, '0x044c', 'Malayalam (India)', 'ml-IN', 'Mlym', 'UTF-8'),
(115, '0x043a', 'Maltese (Malta)', 'mt-MT', 'Latn', '1252'),
(116, '0x0481', 'Maori (New Zealand)', 'mi-NZ', 'Latn', '1252'),
(117, '0x047a', 'Mapudungun (Chile)', 'arn-CL', 'Latn', '1252'),
(118, '0x044e', 'Marathi (India)', 'mr-IN', 'Deva', 'UTF-8'),
(119, '0x047c', 'Mohawk (Canada)', 'moh-CA', 'Latn', '1252'),
(120, '0x0450', 'Mongolian (Mongolia)', 'mn-Cyrl-MN', 'Cyrl', '1251'),
(121, '0x0850', 'Mongolian (PRC)', 'mn-Mong-CN', 'Mong', 'UTF-8'),
(122, '0x0850', 'Nepali (India)', 'ne-IN', '__', 'UTF-8'),
(123, '0x0461', 'Nepali (Nepal)', 'ne-NP', 'Deva', 'UTF-8'),
(124, '0x0414', 'Norwegian (Bokmål, Norway)', 'nb-NO', 'Latn', '1252'),
(125, '0x0814', 'Norwegian (Nynorsk, Norway)', 'nn-NO', 'Latn', '1252'),
(126, '0x0482', 'Occitan (France)', 'oc-FR', 'Latn', '1252'),
(127, '0x0448', 'Oriya (India)', 'or-IN', 'Orya', 'UTF-8'),
(128, '0x0463', 'Pashto (Afghanistan)', 'ps-AF', '', ''),
(129, '0x0429', 'Persian (Iran)', 'fa-IR', 'Arab', '1256'),
(130, '0x0415', 'Polish (Poland)', 'pl-PL', 'Latn', '1250'),
(131, '0x0416', 'Portuguese (Brazil)', 'pt-BR', 'Latn', '1252'),
(132, '0x0816', 'Portuguese (Portugal)', 'pt-PT', 'Latn', '1252'),
(133, '0x0446', 'Punjabi (India)', 'pa-IN', 'Guru', 'UTF-8'),
(134, '0x046b', 'Quechua (Bolivia)', 'quz-BO', 'Latn', '1252'),
(135, '0x086b', 'Quechua (Ecuador)', 'quz-EC', 'Latn', '1252'),
(136, '0x0c6b', 'Quechua (Peru)', 'quz-PE', 'Latn', '1252'),
(137, '0x0418', 'Romanian (Romania)', 'ro-RO', 'Latn', '1250'),
(138, '0x0417', 'Romansh (Switzerland)', 'rm-CH', 'Latn', '1252'),
(139, '0x0419', 'Russian (Russia)', 'ru-RU', 'Cyrl', '1251'),
(140, '0x243b', 'Sami (Inari, Finland)', 'smn-FI', 'Latn', '1252'),
(141, '0x103b', 'Sami (Lule, Norway)', 'smj-NO', 'Latn', '1252'),
(142, '0x143b', 'Sami (Lule, Sweden)', 'smj-SE', 'Latn', '1252'),
(143, '0x0c3b', 'Sami (Northern, Finland)', 'se-FI', 'Latn', '1252'),
(144, '0x043b', 'Sami (Northern, Norway)', 'se-NO', 'Latn', '1252'),
(145, '0x083b', 'Sami (Northern, Sweden)', 'se-SE', 'Latn', '1252'),
(146, '0x203b', 'Sami (Skolt, Finland)', 'sms-FI', 'Latn', '1252'),
(147, '0x183b', 'Sami (Southern, Norway)', 'sma-NO', 'Latn', '1252'),
(148, '0x1c3b', 'Sami (Southern, Sweden)', 'sma-SE', 'Latn', '1252'),
(149, '0x044f', 'Sanskrit (India)', 'sa-IN', 'Deva', 'UTF-8'),
(150, '0x1c1a', 'Serbian (Bosnia and Herzegovina, Cyrillic)', 'sr-Cyrl-BA', 'Cyrl', '1251'),
(151, '0x181a', 'Serbian (Bosnia and Herzegovina, Latin)', 'sr-Latn-BA', 'Latn', '1250'),
(152, '0x0c1a', 'Serbian (Serbia, Cyrillic)', 'sr-Cyrl-CS', 'Cyrl', '1251'),
(153, '0x081a', 'Serbian (Serbia, Latin)', 'sr-Latn-CS', 'Latn', '1250'),
(154, '0x046c', 'Sesotho sa Leboa/Northern Sotho (South Africa)', 'ns-ZA', 'Latn', '1252'),
(155, '0x0432', 'Setswana/Tswana (South Africa)', 'tn-ZA', 'Latn', '1252'),
(156, '0x045b', 'Sinhala (Sri Lanka)', 'si-LK', 'Sinh', 'UTF-8'),
(157, '0x041b', 'Slovak (Slovakia)', 'sk-SK', 'Latn', '1250'),
(158, '0x0424', 'Slovenian (Slovenia)', 'sl-SI', 'Latn', '1250'),
(159, '0x2c0a', 'Spanish (Argentina)', 'es-AR', 'Latn', '1252'),
(160, '0x400a', 'Spanish (Bolivia)', 'es-BO', 'Latn', '1252'),
(161, '0x340a', 'Spanish (Chile)', 'es-CL', 'Latn', '1252'),
(162, '0x240a', 'Spanish (Colombia)', 'es-CO', 'Latn', '1252'),
(163, '0x140a', 'Spanish (Costa Rica)', 'es-CR', 'Latn', '1252'),
(164, '0x1c0a', 'Spanish (Dominican Republic)', 'es-DO', 'Latn', '1252'),
(165, '0x300a', 'Spanish (Ecuador)', 'es-EC', 'Latn', '1252'),
(166, '0x440a', 'Spanish (El Salvador)', 'es-SV', 'Latn', '1252'),
(167, '0x100a', 'Spanish (Guatemala)', 'es-GT', 'Latn', '1252'),
(168, '0x480a', 'Spanish (Honduras)', 'es-HN', 'Latn', '1252'),
(169, '0x080a', 'Spanish (Mexico)', 'es-MX', 'Latn', '1252'),
(170, '0x4c0a', 'Spanish (Nicaragua)', 'es-NI', 'Latn', '1252'),
(171, '0x180a', 'Spanish (Panama)', 'es-PA', 'Latn', '1252'),
(172, '0x3c0a', 'Spanish (Paraguay)', 'es-PY', 'Latn', '1252'),
(173, '0x280a', 'Spanish (Peru)', 'es-PE', 'Latn', '1252'),
(174, '0x500a', 'Spanish (Puerto Rico)', 'es-PR', 'Latn', '1252'),
(175, '0x0c0a', 'Spanish (Spain)', 'es-ES', 'Latn', '1252'),
(176, '0x040a', 'Spanish (Spain, Traditional Sort)', 'es-ES_tradnl', 'Latn', '1252'),
(177, '0x540a', 'Spanish (United States)', 'es-US', '', ''),
(178, '0x380a', 'Spanish (Uruguay)', 'es-UY', 'Latn', '1252'),
(179, '0x200a', 'Spanish (Venezuela)', 'es-VE', 'Latn', '1252'),
(180, '0x0441', 'Swahili (Kenya)', 'sw-KE', 'Latn', '1252'),
(181, '0x081d', 'Swedish (Finland)', 'sv-FI', 'Latn', '1252'),
(182, '0x041d', 'Swedish (Sweden)', 'sv-SE', 'Latn', '1252'),
(183, '0x045a', 'Syriac (Syria)', 'syr-SY', 'Syrc', 'UTF-8'),
(184, '0x0428', 'Tajik (Tajikistan)', 'tg-Cyrl-TJ', 'Cyrl', '1251'),
(185, '0x085f', 'Tamazight (Algeria, Latin)', 'tzm-Latn-DZ', 'Latn', '1252'),
(186, '0x0449', 'Tamil (India)', 'ta-IN', 'Taml', 'UTF-8'),
(187, '0x0444', 'Tatar (Russia)', 'tt-RU', 'Cyrl', '1251'),
(188, '0x044a', 'Telugu (India)', 'te-IN', 'Telu', 'UTF-8'),
(189, '0x041e', 'Thai (Thailand)', 'th-TH', 'Thai', '874'),
(190, '0x0851', 'Tibetan (Bhutan)', 'bo-BT', 'Tibt', 'UTF-8'),
(191, '0x0451', 'Tibetan (PRC)', 'bo-CN', 'Tibt', 'UTF-8'),
(192, '0x041f', 'Turkish (Turkey)', 'tr-TR', 'Latn', '1254'),
(193, '0x0442', 'Turkmen (Turkmenistan)', 'tk-TM', 'Cyrl', '1251'),
(194, '0x0480', 'Uighur (PRC)', 'ug-CN', 'Arab', '1256'),
(195, '0x0422', 'Ukrainian (Ukraine)', 'uk-UA', 'Cyrl', '1251'),
(196, '0x042e', 'Upper Sorbian (Germany)', 'wen-DE', 'Latn', '1252'),
(197, '0x0820', 'Urdu (India)', 'tr-IN', '', ''),
(198, '0x0420', 'Urdu (Pakistan)', 'ur-PK', 'Arab', '1256'),
(199, '0x0843', 'Uzbek (Uzbekistan, Cyrillic)', 'uz-Cyrl-UZ', 'Cyrl', '1251'),
(200, '0x0443', 'Uzbek (Uzbekistan, Latin)', 'uz-Latn-UZ', 'Latn', '1254'),
(201, '0x042a', 'Vietnamese (Vietnam)', 'vi-VN', 'Latn', '1258'),
(202, '0x0452', 'Welsh (United Kingdom)', 'cy-GB', 'Latn', '1252'),
(203, '0x0488', 'Wolof (Senegal)', 'wo-SN', 'Latn', '1252'),
(204, '0x0434', 'Xhosa/isiXhosa (South Africa)', 'xh-ZA', 'Latn', '1252'),
(205, '0x0485', 'Yakut (Russia)', 'sah-RU', 'Cyrl', '1251'),
(206, '0x0478', 'Yi (PRC)', 'ii-CN', 'Yiii', 'UTF-8'),
(207, '0x046a', 'Yoruba (Nigeria)', 'yo-NG', '', ''),
(208, '0x0435', 'Zulu/isiZulu (South Africa)', 'zu-ZA', 'Latn', '1252');
UPDATE Phrase SET Module = 'Core' WHERE Module IN ('Proj-Base', 'In-Portal');
UPDATE Phrase SET Module = 'Core' WHERE Phrase IN ('la_fld_Phone', 'la_fld_City', 'la_fld_State', 'la_fld_Zip');
UPDATE Phrase SET Module = 'Core' WHERE Phrase IN ('la_col_Image', 'la_col_Username', 'la_fld_AddressLine1', 'la_fld_AddressLine2', 'la_fld_Comments', 'la_fld_Country', 'la_fld_Email', 'la_fld_Language', 'la_fld_Login', 'la_fld_MessageText', 'la_fld_MetaDescription', 'la_fld_MetaKeywords', 'la_fld_Password', 'la_fld_Username', 'la_fld_Type');
UPDATE Phrase SET Phrase = 'la_Add' WHERE Phrase = 'LA_ADD';
UPDATE Phrase SET Phrase = 'la_col_MembershipExpires' WHERE Phrase = 'la_col_membershipexpires';
UPDATE Phrase SET Phrase = 'la_ShortToolTip_Clone' WHERE Phrase = 'la_shorttooltip_clone';
UPDATE Phrase SET Phrase = 'la_ShortToolTip_Edit' WHERE Phrase = 'LA_SHORTTOOLTIP_EDIT';
UPDATE Phrase SET Phrase = 'la_ShortToolTip_Export' WHERE Phrase = 'LA_SHORTTOOLTIP_EXPORT';
UPDATE Phrase SET Phrase = 'la_ShortToolTip_GoUp' WHERE Phrase = 'LA_SHORTTOOLTIP_GOUP';
UPDATE Phrase SET Phrase = 'la_ShortToolTip_Import' WHERE Phrase = 'LA_SHORTTOOLTIP_IMPORT';
UPDATE Phrase SET Phrase = 'la_ShortToolTip_MoveUp' WHERE Phrase = 'la_shorttooltip_moveup';
UPDATE Phrase SET Phrase = 'la_ShortToolTip_MoveDown' WHERE Phrase = 'la_shorttooltip_movedown';
UPDATE Phrase SET Phrase = 'la_ShortToolTip_RescanThemes' WHERE Phrase = 'la_shorttooltip_rescanthemes';
UPDATE Phrase SET Phrase = 'la_ShortToolTip_SetPrimary' WHERE Phrase = 'LA_SHORTTOOLTIP_SETPRIMARY';
UPDATE Phrase SET Phrase = 'la_ShortToolTip_Rebuild' WHERE Phrase = 'LA_SHORTTOOLTIP_REBUILD';
UPDATE Phrase SET Phrase = 'la_Tab_Service' WHERE Phrase = 'la_tab_service';
UPDATE Phrase SET Phrase = 'la_tab_Files' WHERE Phrase = 'la_tab_files';
UPDATE Phrase SET Phrase = 'la_ToolTipShort_Edit_Current_Category' WHERE Phrase = 'LA_TOOLTIPSHORT_EDIT_CURRENT_CATEGORY';
UPDATE Phrase SET Phrase = 'la_ToolTip_Add' WHERE Phrase = 'LA_TOOLTIP_ADD';
UPDATE Phrase SET Phrase = 'la_ToolTip_Add_Product' WHERE Phrase = 'LA_TOOLTIP_ADD_PRODUCT';
UPDATE Phrase SET Phrase = 'la_ToolTip_NewSearchConfig' WHERE Phrase = 'LA_TOOLTIP_NEWSEARCHCONFIG';
UPDATE Phrase SET Phrase = 'la_ToolTip_Prev' WHERE Phrase = 'la_tooltip_prev';
UPDATE Phrase SET Phrase = 'la_Invalid_Password' WHERE Phrase = 'la_invalid_password';
UPDATE Events SET Module = REPLACE(Module, 'In-Portal', 'Core');
DROP TABLE ImportScripts;
CREATE TABLE BanRules (
RuleId int(11) NOT NULL auto_increment,
RuleType tinyint(4) NOT NULL default '0',
ItemField varchar(255) default NULL,
ItemVerb tinyint(4) NOT NULL default '0',
ItemValue varchar(255) NOT NULL default '',
ItemType int(11) NOT NULL default '0',
Priority int(11) NOT NULL default '0',
Status tinyint(4) NOT NULL default '1',
ErrorTag varchar(255) default NULL,
PRIMARY KEY (RuleId),
KEY Status (Status),
KEY Priority (Priority),
KEY ItemType (ItemType)
);
CREATE TABLE CountCache (
ListType int(11) NOT NULL default '0',
ItemType int(11) NOT NULL default '-1',
Value int(11) NOT NULL default '0',
CountCacheId int(11) NOT NULL auto_increment,
LastUpdate int(11) NOT NULL default '0',
ExtraId varchar(50) default NULL,
TodayOnly tinyint(4) NOT NULL default '0',
PRIMARY KEY (CountCacheId)
);
CREATE TABLE Favorites (
FavoriteId int(11) NOT NULL auto_increment,
PortalUserId int(11) NOT NULL default '0',
ResourceId int(11) NOT NULL default '0',
ItemTypeId int(11) NOT NULL default '0',
Modified int(11) NOT NULL default '0',
PRIMARY KEY (FavoriteId),
UNIQUE KEY main (PortalUserId,ResourceId),
KEY Modified (Modified),
KEY ItemTypeId (ItemTypeId)
);
CREATE TABLE Images (
ImageId int(11) NOT NULL auto_increment,
ResourceId int(11) NOT NULL default '0',
Url varchar(255) NOT NULL default '',
Name varchar(255) NOT NULL default '',
AltName VARCHAR(255) NOT NULL DEFAULT '',
ImageIndex int(11) NOT NULL default '0',
LocalImage tinyint(4) NOT NULL default '1',
LocalPath varchar(240) NOT NULL default '',
Enabled int(11) NOT NULL default '1',
DefaultImg int(11) NOT NULL default '0',
ThumbUrl varchar(255) default NULL,
Priority int(11) NOT NULL default '0',
ThumbPath varchar(255) default NULL,
LocalThumb tinyint(4) NOT NULL default '1',
SameImages tinyint(4) NOT NULL default '1',
PRIMARY KEY (ImageId),
KEY ResourceId (ResourceId),
KEY Enabled (Enabled),
KEY Priority (Priority)
);
CREATE TABLE ItemRating (
RatingId int(11) NOT NULL auto_increment,
IPAddress varchar(255) NOT NULL default '',
CreatedOn INT UNSIGNED NULL DEFAULT NULL,
RatingValue int(11) NOT NULL default '0',
ItemId int(11) NOT NULL default '0',
PRIMARY KEY (RatingId),
KEY CreatedOn (CreatedOn),
KEY ItemId (ItemId),
KEY RatingValue (RatingValue)
);
CREATE TABLE ItemReview (
ReviewId int(11) NOT NULL auto_increment,
CreatedOn INT UNSIGNED NULL DEFAULT NULL,
ReviewText longtext NOT NULL,
Rating tinyint(3) unsigned default NULL,
IPAddress varchar(255) NOT NULL default '',
ItemId int(11) NOT NULL default '0',
CreatedById int(11) NOT NULL default '-1',
ItemType tinyint(4) NOT NULL default '0',
Priority int(11) NOT NULL default '0',
Status tinyint(4) NOT NULL default '2',
TextFormat int(11) NOT NULL default '0',
Module varchar(255) NOT NULL default '',
PRIMARY KEY (ReviewId),
KEY CreatedOn (CreatedOn),
KEY ItemId (ItemId),
KEY ItemType (ItemType),
KEY Priority (Priority),
KEY Status (Status)
);
CREATE TABLE ItemTypes (
ItemType int(11) NOT NULL default '0',
Module varchar(50) NOT NULL default '',
Prefix varchar(20) NOT NULL default '',
SourceTable varchar(100) NOT NULL default '',
TitleField varchar(50) default NULL,
CreatorField varchar(255) NOT NULL default '',
PopField varchar(255) default NULL,
RateField varchar(255) default NULL,
LangVar varchar(255) NOT NULL default '',
PrimaryItem int(11) NOT NULL default '0',
EditUrl varchar(255) NOT NULL default '',
ClassName varchar(40) NOT NULL default '',
ItemName varchar(50) NOT NULL default '',
PRIMARY KEY (ItemType),
KEY Module (Module)
);
CREATE TABLE ItemFiles (
FileId int(11) NOT NULL auto_increment,
ResourceId int(11) unsigned NOT NULL default '0',
FileName varchar(255) NOT NULL default '',
FilePath varchar(255) NOT NULL default '',
Size int(11) NOT NULL default '0',
`Status` tinyint(4) NOT NULL default '1',
CreatedOn int(11) unsigned NOT NULL default '0',
CreatedById int(11) NOT NULL default '-1',
MimeType varchar(255) NOT NULL default '',
PRIMARY KEY (FileId),
KEY ResourceId (ResourceId),
KEY CreatedOn (CreatedOn),
KEY Status (Status)
);
CREATE TABLE Relationship (
RelationshipId int(11) NOT NULL auto_increment,
SourceId int(11) default NULL,
TargetId int(11) default NULL,
SourceType tinyint(4) NOT NULL default '0',
TargetType tinyint(4) NOT NULL default '0',
Type int(11) NOT NULL default '0',
Enabled int(11) NOT NULL default '1',
Priority int(11) NOT NULL default '0',
PRIMARY KEY (RelationshipId),
KEY RelSource (SourceId),
KEY RelTarget (TargetId),
KEY `Type` (`Type`),
KEY Enabled (Enabled),
KEY Priority (Priority),
KEY SourceType (SourceType),
KEY TargetType (TargetType)
);
CREATE TABLE SearchConfig (
TableName varchar(40) NOT NULL default '',
FieldName varchar(40) NOT NULL default '',
SimpleSearch tinyint(4) NOT NULL default '1',
AdvancedSearch tinyint(4) NOT NULL default '1',
Description varchar(255) default NULL,
DisplayName varchar(80) default NULL,
ModuleName VARCHAR(20) NOT NULL DEFAULT 'In-Portal',
ConfigHeader varchar(255) default NULL,
DisplayOrder int(11) NOT NULL default '0',
SearchConfigId int(11) NOT NULL auto_increment,
Priority int(11) NOT NULL default '0',
FieldType varchar(20) NOT NULL default 'text',
ForeignField TEXT,
JoinClause TEXT,
IsWhere text,
IsNotWhere text,
ContainsWhere text,
NotContainsWhere text,
CustomFieldId int(11) default NULL,
PRIMARY KEY (SearchConfigId),
KEY SimpleSearch (SimpleSearch),
KEY AdvancedSearch (AdvancedSearch),
KEY DisplayOrder (DisplayOrder),
KEY Priority (Priority),
KEY CustomFieldId (CustomFieldId)
);
CREATE TABLE SearchLog (
SearchLogId int(11) NOT NULL auto_increment,
Keyword varchar(255) NOT NULL default '',
Indices bigint(20) NOT NULL default '0',
SearchType int(11) NOT NULL default '0',
PRIMARY KEY (SearchLogId),
KEY SearchType (SearchType)
);
CREATE TABLE IgnoreKeywords (
keyword varchar(20) NOT NULL default '',
PRIMARY KEY (keyword)
);
CREATE TABLE SpamControl (
ItemResourceId int(11) NOT NULL default '0',
IPaddress varchar(20) NOT NULL default '',
Expire INT UNSIGNED NULL DEFAULT NULL,
PortalUserId int(11) NOT NULL default '0',
DataType varchar(20) default NULL,
KEY PortalUserId (PortalUserId),
KEY Expire (Expire),
KEY ItemResourceId (ItemResourceId)
);
CREATE TABLE StatItem (
StatItemId int(11) NOT NULL auto_increment,
Module varchar(20) NOT NULL default '',
ValueSQL varchar(255) default NULL,
ResetSQL varchar(255) default NULL,
ListLabel varchar(255) NOT NULL default '',
Priority int(11) NOT NULL default '0',
AdminSummary int(11) NOT NULL default '0',
PRIMARY KEY (StatItemId),
KEY AdminSummary (AdminSummary),
KEY Priority (Priority)
);
CREATE TABLE SuggestMail (
email varchar(255) NOT NULL default '',
sent INT UNSIGNED NULL DEFAULT NULL,
PRIMARY KEY (email),
KEY sent (sent)
);
CREATE TABLE SysCache (
SysCacheId int(11) NOT NULL auto_increment,
Name varchar(255) NOT NULL default '',
Value mediumtext,
Expire INT UNSIGNED NULL DEFAULT NULL,
Module varchar(20) default NULL,
Context varchar(255) default NULL,
GroupList varchar(255) NOT NULL default '',
PRIMARY KEY (SysCacheId),
KEY Name (Name)
);
CREATE TABLE TagLibrary (
TagId int(11) NOT NULL auto_increment,
name varchar(255) NOT NULL default '',
description text,
example text,
scope varchar(20) NOT NULL default 'global',
PRIMARY KEY (TagId)
);
CREATE TABLE TagAttributes (
AttrId int(11) NOT NULL auto_increment,
TagId int(11) NOT NULL default '0',
Name varchar(255) NOT NULL default '',
AttrType varchar(20) default NULL,
DefValue varchar(255) default NULL,
Description TEXT,
Required int(11) NOT NULL default '0',
PRIMARY KEY (AttrId),
KEY TagId (TagId)
);
CREATE TABLE ImportScripts (
ImportId INT(11) NOT NULL auto_increment,
Name VARCHAR(255) NOT NULL DEFAULT '',
Description TEXT NOT NULL,
Prefix VARCHAR(10) NOT NULL DEFAULT '',
Module VARCHAR(50) NOT NULL DEFAULT '',
ExtraFields VARCHAR(255) NOT NULL DEFAULT '',
Type VARCHAR(10) NOT NULL DEFAULT '',
Status TINYINT NOT NULL,
PRIMARY KEY (ImportId),
KEY Module (Module),
KEY Status (Status)
);
CREATE TABLE StylesheetSelectors (
SelectorId int(11) NOT NULL auto_increment,
StylesheetId int(11) NOT NULL default '0',
Name varchar(255) NOT NULL default '',
SelectorName varchar(255) NOT NULL default '',
SelectorData text NOT NULL,
Description text NOT NULL,
Type tinyint(4) NOT NULL default '0',
AdvancedCSS text NOT NULL,
ParentId int(11) NOT NULL default '0',
PRIMARY KEY (SelectorId),
KEY StylesheetId (StylesheetId),
KEY ParentId (ParentId),
KEY `Type` (`Type`)
);
CREATE TABLE Visits (
VisitId int(11) NOT NULL auto_increment,
VisitDate int(10) unsigned NOT NULL default '0',
Referer varchar(255) NOT NULL default '',
IPAddress varchar(15) NOT NULL default '',
AffiliateId int(10) unsigned NOT NULL default '0',
PortalUserId int(11) NOT NULL default '-2',
PRIMARY KEY (VisitId),
KEY PortalUserId (PortalUserId),
KEY AffiliateId (AffiliateId),
KEY VisitDate (VisitDate)
);
CREATE TABLE ImportCache (
CacheId int(11) NOT NULL auto_increment,
CacheName varchar(255) NOT NULL default '',
VarName int(11) NOT NULL default '0',
VarValue text NOT NULL,
PRIMARY KEY (CacheId),
KEY CacheName (CacheName),
KEY VarName (VarName)
);
CREATE TABLE RelatedSearches (
RelatedSearchId int(11) NOT NULL auto_increment,
ResourceId int(11) NOT NULL default '0',
Keyword varchar(255) NOT NULL default '',
ItemType tinyint(4) NOT NULL default '0',
Enabled tinyint(4) NOT NULL default '1',
Priority int(11) NOT NULL default '0',
PRIMARY KEY (RelatedSearchId),
KEY Enabled (Enabled),
KEY ItemType (ItemType),
KEY ResourceId (ResourceId)
);
UPDATE Modules SET Path = 'core/', Version='4.3.9' WHERE Name = 'In-Portal';
UPDATE Skins SET Logo = 'just_logo.gif' WHERE Logo = 'just_logo_1.gif';
UPDATE ConfigurationAdmin SET prompt = 'la_config_PathToWebsite' WHERE VariableName = 'Site_Path';
# ===== v 5.0.0 =====
CREATE TABLE StopWords (
StopWordId int(11) NOT NULL auto_increment,
StopWord varchar(255) NOT NULL default '',
PRIMARY KEY (StopWordId),
KEY StopWord (StopWord)
);
INSERT INTO StopWords VALUES (90, '~'),(152, 'on'),(157, 'see'),(156, 'put'),(128, 'and'),(154, 'or'),(155, 'other'),(153, 'one'),(126, 'as'),(127, 'at'),(125, 'are'),(91, '!'),(92, '@'),(93, '#'),(94, '$'),(95, '%'),(96, '^'),(97, '&'),(98, '*'),(99, '('),(100, ')'),(101, '-'),(102, '_'),(103, '='),(104, '+'),(105, '['),(106, '{'),(107, ']'),(108, '}'),(109, '\\'),(110, '|'),(111, ';'),(112, ':'),(113, ''''),(114, '"'),(115, '<'),(116, '.'),(117, '>'),(118, '/'),(119, '?'),(120, 'ah'),(121, 'all'),(122, 'also'),(123, 'am'),(124, 'an'),(151, 'of'),(150, 'note'),(149, 'not'),(148, 'no'),(147, 'may'),(146, 'its'),(145, 'it'),(144, 'is'),(143, 'into'),(142, 'in'),(141, 'had'),(140, 'has'),(139, 'have'),(138, 'from'),(137, 'form'),(136, 'for'),(135, 'end'),(134, 'each'),(133, 'can'),(132, 'by'),(130, 'be'),(131, 'but'),(129, 'any'),(158, 'that'),(159, 'the'),(160, 'their'),(161, 'there'),(162, 'these'),(163, 'they'),(164, 'this'),(165, 'through'),(166, 'thus'),(167, 'to'),(168, 'two'),(169, 'too'),(170, 'up'),(171, 'where'),(172, 'which'),(173, 'with'),(174, 'were'),(175, 'was'),(176, 'you'),(177, 'yet');
INSERT INTO Permissions VALUES (DEFAULT, 'in-portal:stop_words.view', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-portal:stop_words.add', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-portal:stop_words.edit', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-portal:stop_words.delete', 11, 1, 1, 0);
INSERT INTO ConfigurationAdmin VALUES ('CheckStopWords', 'la_Text_Website', 'la_config_CheckStopWords', 'checkbox', '', '', 10.29, 0, 0);
INSERT INTO ConfigurationValues VALUES (DEFAULT, 'CheckStopWords', '0', 'In-Portal', 'in-portal:configure_general');
ALTER TABLE SpamControl ADD INDEX (DataType);
CREATE TABLE MailingLists (
MailingId int(10) unsigned NOT NULL auto_increment,
PortalUserId int(11) NOT NULL default '-1',
`To` longtext,
ToParsed longtext,
Attachments text,
`Subject` varchar(255) NOT NULL,
MessageText longtext,
MessageHtml longtext,
`Status` tinyint(3) unsigned NOT NULL default '1',
EmailsQueued int(10) unsigned NOT NULL,
EmailsSent int(10) unsigned NOT NULL,
EmailsTotal int(10) unsigned NOT NULL,
PRIMARY KEY (MailingId),
KEY EmailsTotal (EmailsTotal),
KEY EmailsSent (EmailsSent),
KEY EmailsQueued (EmailsQueued),
KEY `Status` (`Status`),
KEY PortalUserId (PortalUserId)
);
INSERT INTO Permissions VALUES (DEFAULT, 'in-portal:mailing_lists.view', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-portal:mailing_lists.add', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-portal:mailing_lists.edit', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-portal:mailing_lists.delete', 11, 1, 1, 0);
ALTER TABLE EmailQueue
ADD MailingId INT UNSIGNED NOT NULL,
ADD INDEX (MailingId);
INSERT INTO ConfigurationAdmin VALUES ('MailingListQueuePerStep', 'la_Text_smtp_server', 'la_config_MailingListQueuePerStep', 'text', NULL, NULL, 30.09, 0, 0);
INSERT INTO ConfigurationValues VALUES (DEFAULT, 'MailingListQueuePerStep', 10, 'In-Portal', 'in-portal:configure_general');
INSERT INTO ConfigurationAdmin VALUES ('MailingListSendPerStep', 'la_Text_smtp_server', 'la_config_MailingListSendPerStep', 'text', NULL, NULL, 30.10, 0, 0);
INSERT INTO ConfigurationValues VALUES (DEFAULT, 'MailingListSendPerStep', 10, 'In-Portal', 'in-portal:configure_general');
ALTER TABLE Events ADD INDEX (Event);
ALTER TABLE SearchLog ADD INDEX (Keyword);
ALTER TABLE Skins
ADD LogoBottom VARCHAR(255) NOT NULL AFTER Logo,
ADD LogoLogin VARCHAR(255) NOT NULL AFTER LogoBottom;
UPDATE Skins
SET Logo = 'in-portal_logo_img.jpg', LogoBottom = 'in-portal_logo_img2.jpg', LogoLogin = 'in-portal_logo_login.gif'
WHERE Logo = 'just_logo_1.gif' OR Logo = 'just_logo.gif';
INSERT INTO ConfigurationValues VALUES (DEFAULT, 'SiteNameSubTitle', '', 'In-Portal', 'in-portal:configure_general');
INSERT INTO ConfigurationAdmin VALUES ('SiteNameSubTitle', 'la_Text_Website', 'la_config_SiteNameSubTitle', 'text', '', '', 10.021, 0, 0);
INSERT INTO ConfigurationAdmin VALUES ('ResizableFrames', 'la_Text_Website', 'la_config_ResizableFrames', 'checkbox', '', '', 10.30, 0, 0);
INSERT INTO ConfigurationValues VALUES (DEFAULT, 'ResizableFrames', '0', 'In-Portal', 'in-portal:configure_general');
INSERT INTO ConfigurationAdmin VALUES ('QuickCategoryPermissionRebuild', 'la_Text_General', 'la_config_QuickCategoryPermissionRebuild', 'checkbox', NULL , NULL , 10.12, 0, 0);
INSERT INTO ConfigurationValues VALUES (DEFAULT, 'QuickCategoryPermissionRebuild', '1', 'In-Portal', 'in-portal:configure_categories');
ALTER TABLE Language ADD UserDocsUrl VARCHAR(255) NOT NULL;
UPDATE Category SET Template = CategoryTemplate WHERE CategoryTemplate <> '';
ALTER TABLE Category
ADD ThemeId INT UNSIGNED NOT NULL,
ADD INDEX (ThemeId),
ADD COLUMN UseExternalUrl tinyint(3) unsigned NOT NULL default '0' AFTER Template,
ADD COLUMN ExternalUrl varchar(255) NOT NULL default '' AFTER UseExternalUrl,
ADD COLUMN UseMenuIconUrl tinyint(3) unsigned NOT NULL default '0' AFTER ExternalUrl,
ADD COLUMN MenuIconUrl varchar(255) NOT NULL default '' AFTER UseMenuIconUrl,
CHANGE MetaKeywords MetaKeywords TEXT,
CHANGE MetaDescription MetaDescription TEXT,
CHANGE CachedCategoryTemplate CachedTemplate VARCHAR(255) NOT NULL,
DROP CategoryTemplate;
UPDATE Category SET l1_MenuTitle = l1_Name WHERE l1_MenuTitle = '' OR l1_MenuTitle LIKE '_Auto: %';
UPDATE Category SET l2_MenuTitle = l2_Name WHERE l2_MenuTitle = '' OR l2_MenuTitle LIKE '_Auto: %';
UPDATE Category SET l3_MenuTitle = l3_Name WHERE l3_MenuTitle = '' OR l3_MenuTitle LIKE '_Auto: %';
UPDATE Category SET l4_MenuTitle = l4_Name WHERE l4_MenuTitle = '' OR l4_MenuTitle LIKE '_Auto: %';
UPDATE Category SET l5_MenuTitle = l5_Name WHERE l5_MenuTitle = '' OR l5_MenuTitle LIKE '_Auto: %';
UPDATE Category SET Template = '/platform/designs/general' WHERE Template = '/in-edit/designs/general';
UPDATE Category SET CachedTemplate = '/platform/designs/general' WHERE CachedTemplate = '/in-edit/designs/general';
UPDATE Category SET CachedTemplate = Template WHERE Template <> '';
CREATE TABLE PageContent (
PageContentId int(11) NOT NULL auto_increment,
ContentNum int(11) NOT NULL default '0',
PageId int(11) NOT NULL default '0',
l1_Content text,
l2_Content text,
l3_Content text,
l4_Content text,
l5_Content text,
l1_Translated tinyint(4) NOT NULL default '0',
l2_Translated tinyint(4) NOT NULL default '0',
l3_Translated tinyint(4) NOT NULL default '0',
l4_Translated tinyint(4) NOT NULL default '0',
l5_Translated tinyint(4) NOT NULL default '0',
PRIMARY KEY (PageContentId),
KEY ContentNum (ContentNum,PageId)
);
CREATE TABLE FormFields (
FormFieldId int(11) NOT NULL auto_increment,
FormId int(11) NOT NULL default '0',
Type int(11) NOT NULL default '0',
FieldName varchar(255) NOT NULL default '',
FieldLabel varchar(255) default NULL,
Heading varchar(255) default NULL,
Prompt varchar(255) default NULL,
ElementType varchar(50) NOT NULL default '',
ValueList varchar(255) default NULL,
Priority int(11) NOT NULL default '0',
IsSystem tinyint(3) unsigned NOT NULL default '0',
Required tinyint(1) NOT NULL default '0',
DisplayInGrid tinyint(1) NOT NULL default '1',
DefaultValue text NOT NULL,
Validation TINYINT NOT NULL DEFAULT '0',
PRIMARY KEY (FormFieldId),
KEY `Type` (`Type`),
KEY FormId (FormId),
KEY Priority (Priority),
KEY IsSystem (IsSystem),
KEY DisplayInGrid (DisplayInGrid)
);
CREATE TABLE FormSubmissions (
FormSubmissionId int(11) NOT NULL auto_increment,
FormId int(11) NOT NULL default '0',
SubmissionTime int(11) NOT NULL default '0',
PRIMARY KEY (FormSubmissionId),
KEY FormId (FormId),
KEY SubmissionTime (SubmissionTime)
);
CREATE TABLE Forms (
FormId int(11) NOT NULL auto_increment,
Title VARCHAR(255) NOT NULL DEFAULT '',
Description text,
PRIMARY KEY (FormId)
);
UPDATE Events SET Module = 'Core:Category', Description = 'la_event_FormSubmitted' WHERE Event = 'FORM.SUBMITTED';
DELETE FROM PersistantSessionData WHERE VariableName LIKE '%img%';
UPDATE Modules SET TemplatePath = Path WHERE TemplatePath <> '';
UPDATE ConfigurationValues SET VariableValue = '/platform/designs/general' WHERE VariableName = 'cms_DefaultDesign';
UPDATE ConfigurationValues SET ModuleOwner = 'In-Portal', Section = 'in-portal:configure_categories' WHERE VariableName = 'cms_DefaultDesign';
UPDATE ConfigurationAdmin SET DisplayOrder = 10.15 WHERE VariableName = 'cms_DefaultDesign';
UPDATE Phrase SET Phrase = 'la_Regular' WHERE Phrase = 'la_regular';
UPDATE Phrase SET Module = 'Core' WHERE Phrase IN ('la_Hide', 'la_Show', 'la_fld_Requied', 'la_col_Modified', 'la_col_Referer', 'la_Regular');
UPDATE Phrase SET Phrase = 'la_title_Editing_E-mail' WHERE Phrase = 'la_title_editing_e-mail';
ALTER TABLE Phrase ADD UNIQUE (LanguageId, Phrase);
ALTER TABLE CustomField ADD IsRequired tinyint(3) unsigned NOT NULL default '0';
DELETE FROM Permissions
WHERE
(Permission LIKE 'proj-cms:structure%') OR
(Permission LIKE 'proj-cms:submissions%') OR
(Permission LIKE 'proj-base:users%') OR
(Permission LIKE 'proj-base:system_variables%') OR
(Permission LIKE 'proj-base:email_settings%') OR
(Permission LIKE 'proj-base:other_settings%') OR
(Permission LIKE 'proj-base:sysconfig%');
UPDATE Permissions SET Permission = REPLACE(Permission, 'proj-cms:browse', 'in-portal:browse_site');
UPDATE Permissions SET Permission = REPLACE(Permission, 'proj-cms:', 'in-portal:');
UPDATE Permissions SET Permission = REPLACE(Permission, 'proj-base:', 'in-portal:');
ALTER TABLE CategoryItems ADD INDEX (ItemResourceId);
ALTER TABLE CategoryItems DROP INDEX Filename;
ALTER TABLE CategoryItems ADD INDEX Filename(Filename);
DROP TABLE Pages;
DELETE FROM PermissionConfig WHERE PermissionName LIKE 'PAGE.%';
DELETE FROM Permissions WHERE Permission LIKE 'PAGE.%';
DELETE FROM SearchConfig WHERE TableName = 'Pages';
DELETE FROM ConfigurationAdmin WHERE VariableName LIKE '%_pages';
DELETE FROM ConfigurationValues WHERE VariableName LIKE '%_pages';
DELETE FROM ConfigurationAdmin WHERE VariableName LIKE 'PerPage_Pages%';
DELETE FROM ConfigurationValues WHERE VariableName LIKE 'PerPage_Pages%';
INSERT INTO Permissions VALUES (DEFAULT, 'in-portal:website_setting_folder.view', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-portal:user_setting_folder.view', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-portal:configure_advanced.view', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-portal:configure_advanced.edit', 11, 1, 1, 0);
#INSERT INTO Permissions VALUES (DEFAULT, 'in-portal:spelling_dictionary.delete', 11, 1, 1, 0);
#INSERT INTO Permissions VALUES (DEFAULT, 'in-portal:spelling_dictionary.edit', 11, 1, 1, 0);
#INSERT INTO Permissions VALUES (DEFAULT, 'in-portal:spelling_dictionary.add', 11, 1, 1, 0);
#INSERT INTO Permissions VALUES (DEFAULT, 'in-portal:spelling_dictionary.view', 11, 1, 1, 0);
UPDATE ConfigurationValues
SET ModuleOwner = 'In-Portal', Section = 'in-portal:configure_general'
WHERE ModuleOwner = 'Proj-Base' AND Section IN ('proj-base:system_variables', 'proj-base:email_settings');
UPDATE ConfigurationValues
SET ModuleOwner = 'In-Portal', Section = 'in-portal:configure_advanced'
WHERE ModuleOwner = 'Proj-Base' AND Section IN ('proj-base:other_settings', 'proj-base:sysconfig');
UPDATE ConfigurationAdmin SET heading = 'la_Text_General' WHERE VariableName IN ('AdvancedUserManagement', 'RememberLastAdminTemplate', 'DefaultSettingsUserId');
UPDATE ConfigurationAdmin SET DisplayOrder = 10.011 WHERE VariableName = 'AdvancedUserManagement';
UPDATE ConfigurationAdmin SET DisplayOrder = 10.14 WHERE VariableName = 'RememberLastAdminTemplate';
UPDATE ConfigurationAdmin SET DisplayOrder = 10.15 WHERE VariableName = 'DefaultSettingsUserId';
UPDATE ConfigurationAdmin SET DisplayOrder = 10.13 WHERE VariableName = 'FilenameSpecialCharReplacement';
UPDATE ConfigurationAdmin SET DisplayOrder = 10.14 WHERE VariableName = 'YahooApplicationId';
UPDATE ConfigurationAdmin SET heading = 'la_section_SettingsMailling', prompt = 'la_prompt_AdminMailFrom', ValueList = 'size="40"', DisplayOrder = 30.07 WHERE VariableName = 'Smtp_AdminMailFrom';
UPDATE ConfigurationAdmin SET heading = 'la_section_SettingsWebsite' WHERE VariableName IN ('Site_Path','SiteNameSubTitle','UseModRewrite','Config_Server_Time','Config_Site_Time','ErrorTemplate','NoPermissionTemplate','UsePageHitCounter','ForceImageMagickResize','CheckStopWords','Site_Name');
UPDATE ConfigurationAdmin SET heading = 'la_section_SettingsSession' WHERE VariableName IN ('CookieSessions','SessionCookieName','SessionTimeout','KeepSessionOnBrowserClose','SessionReferrerCheck','UseJSRedirect');
UPDATE ConfigurationAdmin SET heading = 'la_section_SettingsSSL' WHERE VariableName IN ('SSL_URL','AdminSSL_URL','Require_SSL','Require_AdminSSL','Force_HTTP_When_SSL_Not_Required','UseModRewriteWithSSL');
UPDATE ConfigurationAdmin SET heading = 'la_section_SettingsAdmin' WHERE VariableName IN ('UseToolbarLabels','UseSmallHeader','UseColumnFreezer','UsePopups','UseDoubleSorting','MenuFrameWidth','ResizableFrames','AutoRefreshIntervals');
UPDATE ConfigurationAdmin SET heading = 'la_section_SettingsMailling' WHERE VariableName IN ('Smtp_Server','Smtp_Port','Smtp_Authenticate','Smtp_User','Smtp_Pass','Smtp_DefaultHeaders','MailFunctionHeaderSeparator','MailingListQueuePerStep','MailingListSendPerStep');
UPDATE ConfigurationAdmin SET heading = 'la_section_SettingsSystem' WHERE VariableName IN ('UseOutputCompression','OutputCompressionLevel','TrimRequiredFields','UseCronForRegularEvent','UseChangeLog','Backup_Path','SystemTagCache','SocketBlockingMode');
UPDATE ConfigurationAdmin SET heading = 'la_section_SettingsCSVExport' WHERE VariableName IN ('CSVExportDelimiter','CSVExportEnclosure','CSVExportSeparator','CSVExportEncoding');
UPDATE ConfigurationAdmin SET DisplayOrder = 10.01 WHERE VariableName = 'Site_Path';
UPDATE ConfigurationAdmin SET DisplayOrder = 10.02 WHERE VariableName = 'SiteNameSubTitle';
UPDATE ConfigurationAdmin SET DisplayOrder = 10.03 WHERE VariableName = 'UseModRewrite';
UPDATE ConfigurationAdmin SET DisplayOrder = 10.04 WHERE VariableName = 'Config_Server_Time';
UPDATE ConfigurationAdmin SET DisplayOrder = 10.05 WHERE VariableName = 'Config_Site_Time';
UPDATE ConfigurationAdmin SET DisplayOrder = 10.06 WHERE VariableName = 'ErrorTemplate';
UPDATE ConfigurationAdmin SET DisplayOrder = 10.07 WHERE VariableName = 'NoPermissionTemplate';
UPDATE ConfigurationAdmin SET DisplayOrder = 10.08 WHERE VariableName = 'UsePageHitCounter';
UPDATE ConfigurationAdmin SET DisplayOrder = 10.09 WHERE VariableName = 'ForceImageMagickResize';
UPDATE ConfigurationAdmin SET DisplayOrder = 10.10 WHERE VariableName = 'CheckStopWords';
UPDATE ConfigurationAdmin SET DisplayOrder = 20.01 WHERE VariableName = 'CookieSessions';
UPDATE ConfigurationAdmin SET DisplayOrder = 20.02 WHERE VariableName = 'SessionCookieName';
UPDATE ConfigurationAdmin SET DisplayOrder = 20.03 WHERE VariableName = 'SessionTimeout';
UPDATE ConfigurationAdmin SET DisplayOrder = 20.04 WHERE VariableName = 'KeepSessionOnBrowserClose';
UPDATE ConfigurationAdmin SET DisplayOrder = 20.05 WHERE VariableName = 'SessionReferrerCheck';
UPDATE ConfigurationAdmin SET DisplayOrder = 20.06 WHERE VariableName = 'UseJSRedirect';
UPDATE ConfigurationAdmin SET DisplayOrder = 30.01 WHERE VariableName = 'SSL_URL';
UPDATE ConfigurationAdmin SET DisplayOrder = 30.02 WHERE VariableName = 'AdminSSL_URL';
UPDATE ConfigurationAdmin SET DisplayOrder = 30.03 WHERE VariableName = 'Require_SSL';
UPDATE ConfigurationAdmin SET DisplayOrder = 30.04 WHERE VariableName = 'Require_AdminSSL';
UPDATE ConfigurationAdmin SET DisplayOrder = 30.05 WHERE VariableName = 'Force_HTTP_When_SSL_Not_Required';
UPDATE ConfigurationAdmin SET DisplayOrder = 30.06 WHERE VariableName = 'UseModRewriteWithSSL';
UPDATE ConfigurationAdmin SET DisplayOrder = 40.01 WHERE VariableName = 'UseToolbarLabels';
UPDATE ConfigurationAdmin SET DisplayOrder = 40.02 WHERE VariableName = 'UseSmallHeader';
UPDATE ConfigurationAdmin SET DisplayOrder = 40.03 WHERE VariableName = 'UseColumnFreezer';
UPDATE ConfigurationAdmin SET DisplayOrder = 40.04 WHERE VariableName = 'UsePopups';
UPDATE ConfigurationAdmin SET DisplayOrder = 40.05 WHERE VariableName = 'UseDoubleSorting';
UPDATE ConfigurationAdmin SET DisplayOrder = 40.06 WHERE VariableName = 'MenuFrameWidth';
UPDATE ConfigurationAdmin SET DisplayOrder = 40.07 WHERE VariableName = 'ResizableFrames';
UPDATE ConfigurationAdmin SET DisplayOrder = 40.08 WHERE VariableName = 'AutoRefreshIntervals';
UPDATE ConfigurationAdmin SET DisplayOrder = 50.01 WHERE VariableName = 'Smtp_Server';
UPDATE ConfigurationAdmin SET DisplayOrder = 50.02 WHERE VariableName = 'Smtp_Port';
UPDATE ConfigurationAdmin SET DisplayOrder = 50.03 WHERE VariableName = 'Smtp_Authenticate';
UPDATE ConfigurationAdmin SET DisplayOrder = 50.04 WHERE VariableName = 'Smtp_User';
UPDATE ConfigurationAdmin SET DisplayOrder = 50.05 WHERE VariableName = 'Smtp_Pass';
UPDATE ConfigurationAdmin SET DisplayOrder = 50.06 WHERE VariableName = 'Smtp_DefaultHeaders';
UPDATE ConfigurationAdmin SET DisplayOrder = 50.07 WHERE VariableName = 'MailFunctionHeaderSeparator';
UPDATE ConfigurationAdmin SET DisplayOrder = 50.08 WHERE VariableName = 'MailingListQueuePerStep';
UPDATE ConfigurationAdmin SET DisplayOrder = 50.09 WHERE VariableName = 'MailingListSendPerStep';
UPDATE ConfigurationAdmin SET DisplayOrder = 60.01 WHERE VariableName = 'UseOutputCompression';
UPDATE ConfigurationAdmin SET DisplayOrder = 60.02 WHERE VariableName = 'OutputCompressionLevel';
UPDATE ConfigurationAdmin SET DisplayOrder = 60.03 WHERE VariableName = 'TrimRequiredFields';
UPDATE ConfigurationAdmin SET DisplayOrder = 60.04 WHERE VariableName = 'UseCronForRegularEvent';
UPDATE ConfigurationAdmin SET DisplayOrder = 60.05 WHERE VariableName = 'UseChangeLog';
UPDATE ConfigurationAdmin SET DisplayOrder = 60.06 WHERE VariableName = 'Backup_Path';
UPDATE ConfigurationAdmin SET DisplayOrder = 60.07 WHERE VariableName = 'SystemTagCache';
UPDATE ConfigurationAdmin SET DisplayOrder = 60.08 WHERE VariableName = 'SocketBlockingMode';
UPDATE ConfigurationAdmin SET DisplayOrder = 70.01 WHERE VariableName = 'CSVExportDelimiter';
UPDATE ConfigurationAdmin SET DisplayOrder = 70.02 WHERE VariableName = 'CSVExportEnclosure';
UPDATE ConfigurationAdmin SET DisplayOrder = 70.03 WHERE VariableName = 'CSVExportSeparator';
UPDATE ConfigurationAdmin SET DisplayOrder = 70.04 WHERE VariableName = 'CSVExportEncoding';
UPDATE Phrase SET Phrase = 'la_section_SettingsWebsite' WHERE Phrase = 'la_Text_Website';
UPDATE Phrase SET Phrase = 'la_section_SettingsMailling' WHERE Phrase = 'la_Text_smtp_server';
UPDATE Phrase SET Phrase = 'la_section_SettingsCSVExport' WHERE Phrase = 'la_Text_CSV_Export';
DELETE FROM Phrase WHERE Phrase IN (
'la_Text_BackupPath', 'la_config_AllowManualFilenames', 'la_fld_cat_MenuLink', 'la_fld_UseCategoryTitle',
'la_In-Edit', 'la_ItemTab_Pages', 'la_Text_Pages', 'la_title_Pages', 'la_title_Page_Categories', 'lu_Pages',
'lu_page_HtmlTitle', 'lu_page_OnPageTitle', 'la_tab_AllPages', 'la_title_AllPages', 'la_title_ContentManagement',
'la_title_ContentManagment', 'lu_ViewSubPages', 'la_CMS_FormSubmitted'
);
DELETE FROM Phrase WHERE (Phrase LIKE 'la_Description_In-Edit%') OR (Phrase LIKE 'la_Pages_PerPage%') OR (Phrase LIKE 'lu_PermName_Page.%');
UPDATE ConfigurationValues
SET VariableValue = 1, ModuleOwner = 'In-Portal:Users', Section = 'in-portal:configure_users'
WHERE VariableName = 'RememberLastAdminTemplate';
UPDATE ConfigurationValues
SET ModuleOwner = 'In-Portal:Users', Section = 'in-portal:configure_users'
WHERE VariableName IN ('AdvancedUserManagement', 'DefaultSettingsUserId');
INSERT INTO ConfigurationAdmin VALUES ('Search_MinKeyword_Length', 'la_Text_General', 'la_config_Search_MinKeyword_Length', 'text', NULL, NULL, 10.19, 0, 0);
UPDATE ConfigurationValues SET Section = 'in-portal:configure_categories' WHERE VariableName = 'Search_MinKeyword_Length';
UPDATE ConfigurationAdmin
SET ValueList = '=+,<SQL>SELECT DestName AS OptionName, DestId AS OptionValue FROM <PREFIX>StdDestinations WHERE COALESCE(DestParentId, 0) = 0 ORDER BY OptionName</SQL>'
WHERE VariableName = 'User_Default_Registration_Country';
UPDATE ConfigurationValues
SET ModuleOwner = 'In-Portal', Section = 'in-portal:configure_advanced'
WHERE VariableName IN (
'Site_Path', 'SiteNameSubTitle', 'CookieSessions', 'SessionCookieName', 'SessionTimeout', 'SessionReferrerCheck',
'SystemTagCache', 'SocketBlockingMode', 'SSL_URL', 'AdminSSL_URL', 'Require_SSL', 'Force_HTTP_When_SSL_Not_Required',
'UseModRewrite', 'UseModRewriteWithSSL', 'UseJSRedirect', 'UseCronForRegularEvent', 'ErrorTemplate',
'NoPermissionTemplate', 'UseOutputCompression', 'OutputCompressionLevel', 'UseToolbarLabels', 'UseSmallHeader',
'UseColumnFreezer', 'TrimRequiredFields', 'UsePageHitCounter', 'UseChangeLog', 'AutoRefreshIntervals',
'KeepSessionOnBrowserClose', 'ForceImageMagickResize', 'CheckStopWords', 'ResizableFrames', 'Config_Server_Time',
'Config_Site_Time', 'Smtp_Server', 'Smtp_Port', 'Smtp_Authenticate', 'Smtp_User', 'Smtp_Pass', 'Smtp_DefaultHeaders',
'MailFunctionHeaderSeparator', 'MailingListQueuePerStep', 'MailingListSendPerStep', 'Backup_Path',
'CSVExportDelimiter', 'CSVExportEnclosure', 'CSVExportSeparator', 'CSVExportEncoding'
);
DELETE FROM ConfigurationValues WHERE VariableName IN (
'Columns_Category', 'Perpage_Archive', 'debug', 'Perpage_User', 'Perpage_LangEmail', 'Default_FromAddr',
'email_replyto', 'email_footer', 'Default_Theme', 'Default_Language', 'User_SortField', 'User_SortOrder',
'Suggest_MinInterval', 'SubCat_ListCount', 'Timeout_Rating', 'Perpage_Relations', 'Group_SortField',
'Group_SortOrder', 'Default_FromName', 'Relation_LV_Sortfield', 'ampm_time', 'Perpage_Template',
'Perpage_Phrase', 'Perpage_Sessionlist', 'Perpage_Items', 'GuestSessions', 'Perpage_Email',
'LinksValidation_LV_Sortfield', 'CustomConfig_LV_Sortfield', 'Event_LV_SortField', 'Theme_LV_SortField',
'Template_LV_SortField', 'Lang_LV_SortField', 'Phrase_LV_SortField', 'LangEmail_LV_SortField',
'CustomData_LV_SortField', 'Summary_SortField', 'Session_SortField', 'SearchLog_SortField', 'Perpage_StatItem',
'Perpage_Groups', 'Perpage_Event', 'Perpage_BanRules', 'Perpage_SearchLog', 'Perpage_LV_lang',
'Perpage_LV_Themes', 'Perpage_LV_Catlist', 'Perpage_Reviews', 'Perpage_Modules', 'Perpage_Grouplist',
'Perpage_Images', 'EmailsL_SortField', 'Perpage_EmailsL', 'Perpage_CustomData', 'Perpage_Review',
'SearchRel_DefaultIncrease', 'SearchRel_DefaultKeyword', 'SearchRel_DefaultPop', 'SearchRel_DefaultRating',
'Category_Highlight_OpenTag', 'Category_Highlight_CloseTag', 'DomainSelect', 'MetaKeywords', 'MetaDescription',
'Config_Name', 'Config_Company', 'Config_Reg_Number', 'Config_Website_Name', 'Config_Web_Address',
'Smtp_SendHTML', 'ProjCMSAllowManualFilenames'
);
DELETE FROM ConfigurationAdmin WHERE VariableName IN ('Domain_Detect', 'Server_Name', 'ProjCMSAllowManualFilenames');
DROP TABLE SuggestMail;
ALTER TABLE ThemeFiles ADD FileMetaInfo TEXT NULL;
UPDATE SearchConfig
SET SimpleSearch = 0
WHERE FieldType NOT IN ('text', 'range') AND SimpleSearch = 1;
DELETE FROM PersistantSessionData WHERE VariableName IN ('c_columns_.', 'c.showall_columns_.', 'emailevents_columns_.', 'emailmessages_columns_.');
INSERT INTO ConfigurationAdmin VALUES ('DebugOnlyFormConfigurator', 'la_section_SettingsAdmin', 'la_config_DebugOnlyFormConfigurator', 'checkbox', '', '', 40.09, 0, 0);
INSERT INTO ConfigurationValues VALUES (DEFAULT, 'DebugOnlyFormConfigurator', '0', 'In-Portal', 'in-portal:configure_advanced');
CREATE TABLE Semaphores (
SemaphoreId int(11) NOT NULL auto_increment,
SessionKey int(10) unsigned NOT NULL,
Timestamp int(10) unsigned NOT NULL,
MainPrefix varchar(255) NOT NULL,
PRIMARY KEY (SemaphoreId),
KEY SessionKey (SessionKey),
KEY Timestamp (Timestamp),
KEY MainPrefix (MainPrefix)
);
ALTER TABLE Language ADD IconDisabledURL VARCHAR(255) NULL DEFAULT NULL AFTER IconURL;
UPDATE Phrase
SET Translation = REPLACE(Translation, 'category', 'section')
WHERE (Phrase IN (
'la_confirm_maintenance', 'la_error_move_subcategory', 'la_error_RootCategoriesDelete',
'la_error_unknown_category', 'la_fld_IsBaseCategory', 'la_nextcategory', 'la_prevcategory',
'la_prompt_max_import_category_levels', 'la_prompt_root_name', 'la_SeparatedCategoryPath',
'la_title_category_select'
) OR Phrase LIKE 'la_Description_%') AND (PhraseType = 1);
UPDATE Phrase SET Translation = REPLACE(Translation, 'Category', 'Section') WHERE PhraseType = 1;
UPDATE Phrase
SET Translation = REPLACE(Translation, 'categories', 'sections')
WHERE (Phrase IN (
'la_category_perpage_prompt', 'la_category_showpick_prompt', 'la_category_sortfield_prompt',
'la_Description_in-portal:advanced_view', 'la_Description_in-portal:browse', 'la_Description_in-portal:site',
'la_error_copy_subcategory', 'la_Msg_PropagateCategoryStatus', 'la_Text_DataType_1'
)) AND (PhraseType = 1);
UPDATE Phrase SET Translation = REPLACE(Translation, 'Categories', 'Sections') WHERE PhraseType = 1;
UPDATE Phrase
SET Translation = REPLACE(Translation, 'Page', 'Section')
WHERE (Phrase IN ('la_col_PageTitle', 'la_col_System', 'la_fld_IsIndex', 'la_fld_PageTitle', 'la_section_Page')) AND (PhraseType = 1);
DELETE FROM Phrase WHERE Phrase IN ('la_title_Adding_Page', 'la_title_Editing_Page', 'la_title_New_Page', 'la_fld_PageId');
INSERT INTO ConfigurationAdmin VALUES ('UseModalWindows', 'la_section_SettingsAdmin', 'la_config_UseModalWindows', 'checkbox', '', '', 40.10, 0, 0);
INSERT INTO ConfigurationValues VALUES (DEFAULT, 'UseModalWindows', '1', 'In-Portal', 'in-portal:configure_advanced');
UPDATE Language SET UserDocsUrl = 'http://docs.in-portal.org/eng/index.php';
DELETE FROM Modules WHERE Name = 'Proj-Base';
DELETE FROM Phrase WHERE Phrase IN ('la_fld_ImageId', 'la_fld_RelationshipId', 'la_fld_ReviewId', 'la_prompt_CensorhipId', 'my_account_title', 'Next Theme', 'Previous Theme', 'test 1', 'la_article_reviewed', 'la_configerror_review', 'la_link_reviewed', 'la_Prompt_ReviewedBy', 'la_prompt_ReviewId', 'la_prompt_ReviewText', 'la_reviewer', 'la_review_added', 'la_review_alreadyreviewed', 'la_review_error', 'la_tab_Editing_Review', 'la_tab_Review', 'la_ToolTip_New_Review', 'la_topic_reviewed', 'lu_add_review', 'lu_article_reviews', 'lu_ferror_review_duplicate', 'lu_link_addreview_confirm_pending_text', 'lu_link_reviews', 'lu_link_review_confirm', 'lu_link_review_confirm_pending', 'lu_link_addreview_confirm_text', 'lu_news_addreview_confirm_text', 'lu_news_addreview_confirm__pending_text', 'lu_news_review_confirm', 'lu_news_review_confirm_pending', 'lu_prompt_review', 'lu_reviews_updated', 'lu_review_access_denied', 'lu_review_article', 'lu_review_link', 'lu_review_news', 'lu_review_this_article', 'lu_fld_Review', 'lu_product_reviews', 'lu_ReviewProduct', ' lu_resetpw_confirm_text', 'lu_resetpw_confirm_text');
UPDATE Modules SET Version = '5.0.0', Loaded = 1 WHERE Name = 'In-Portal';
# ===== v 5.0.1 =====
UPDATE ConfigurationAdmin
SET ValueList = '1=la_opt_UserInstantRegistration,2=la_opt_UserNotAllowedRegistration,3=la_opt_UserUponApprovalRegistration,4=la_opt_UserEmailActivation'
WHERE VariableName = 'User_Allow_New';
UPDATE ConfigurationValues SET VariableValue = '1' WHERE VariableName = 'ResizableFrames';
UPDATE Phrase
SET Translation = REPLACE(Translation, 'Page', 'Section')
WHERE (Phrase IN ('la_col_PageTitle', 'la_col_System', 'la_fld_IsIndex', 'la_fld_PageTitle', 'la_section_Page')) AND (PhraseType = 1);
DELETE FROM Phrase WHERE Phrase IN ('la_Tab', 'la_Colon', 'la_Semicolon', 'la_Space', 'la_Colon', 'la_User_Instant', 'la_User_Not_Allowed', 'la_User_Upon_Approval', 'lu_title_PrivacyPolicy');
UPDATE ConfigurationAdmin SET ValueList = '0=la_opt_Tab,1=la_opt_Comma,2=la_opt_Semicolon,3=la_opt_Space,4=la_opt_Colon'
WHERE VariableName = 'CSVExportDelimiter';
UPDATE ConfigurationAdmin SET ValueList = '0=lu_opt_QueryString,1=lu_opt_Cookies,2=lu_opt_AutoDetect'
WHERE VariableName = 'CookieSessions';
UPDATE ConfigurationAdmin SET ValueList = 'Name=la_opt_Title,Description=la_opt_Description,CreatedOn=la_opt_CreatedOn,EditorsPick=la_opt_EditorsPick,<SQL>SELECT Prompt AS OptionName, CONCAT("cust_", FieldName) AS OptionValue FROM <PREFIX>CustomField WHERE (Type = 1) AND (IsSystem = 0)</SQL>'
WHERE VariableName = 'Category_Sortfield';
UPDATE ConfigurationAdmin SET ValueList = 'Name=la_opt_Title,Description=la_opt_Description,CreatedOn=la_opt_CreatedOn,EditorsPick=la_opt_EditorsPick,<SQL>SELECT Prompt AS OptionName, CONCAT("cust_", FieldName) AS OptionValue FROM <PREFIX>CustomField WHERE (Type = 1) AND (IsSystem = 0)</SQL>'
WHERE VariableName = 'Category_Sortfield2';
UPDATE Category SET Template = '#inherit#' WHERE COALESCE(Template, '') = '';
ALTER TABLE Category CHANGE Template Template VARCHAR(255) NOT NULL DEFAULT '#inherit#';
UPDATE Phrase SET Phrase = 'la_config_DefaultDesignTemplate' WHERE Phrase = 'la_prompt_DefaultDesignTemplate';
UPDATE ConfigurationAdmin SET heading = 'la_section_SettingsWebsite', prompt = 'la_config_DefaultDesignTemplate', DisplayOrder = 10.06 WHERE VariableName = 'cms_DefaultDesign';
UPDATE ConfigurationValues SET Section = 'in-portal:configure_advanced' WHERE VariableName = 'cms_DefaultDesign';
UPDATE ConfigurationAdmin SET DisplayOrder = DisplayOrder + 0.01 WHERE VariableName IN ('ErrorTemplate', 'NoPermissionTemplate');
UPDATE ConfigurationAdmin SET DisplayOrder = 10.15 WHERE VariableName = 'Search_MinKeyword_Length';
UPDATE ConfigurationAdmin SET DisplayOrder = 10.01 WHERE VariableName = 'Site_Name';
UPDATE ConfigurationAdmin SET DisplayOrder = 20.01 WHERE VariableName = 'FirstDayOfWeek';
UPDATE ConfigurationAdmin SET DisplayOrder = 30.01 WHERE VariableName = 'Smtp_AdminMailFrom';
UPDATE ConfigurationAdmin SET heading = 'la_Text_Date_Time_Settings', DisplayOrder = DisplayOrder + 9.98 WHERE VariableName IN ('Config_Server_Time', 'Config_Site_Time');
UPDATE ConfigurationValues SET Section = 'in-portal:configure_general' WHERE VariableName IN ('Config_Server_Time', 'Config_Site_Time');
UPDATE ConfigurationAdmin SET DisplayOrder = DisplayOrder - 0.02 WHERE VariableName IN ('cms_DefaultDesign', 'ErrorTemplate', 'NoPermissionTemplate', 'UsePageHitCounter', 'ForceImageMagickResize', 'CheckStopWords');
UPDATE ConfigurationAdmin SET DisplayOrder = 40.01 WHERE VariableName = 'SessionTimeout';
UPDATE ConfigurationValues SET Section = 'in-portal:configure_general' WHERE VariableName = 'SessionTimeout';
UPDATE ConfigurationAdmin SET DisplayOrder = DisplayOrder - 0.01 WHERE VariableName IN ('KeepSessionOnBrowserClose', 'SessionReferrerCheck', 'UseJSRedirect');
ALTER TABLE Events
ADD FrontEndOnly TINYINT UNSIGNED NOT NULL DEFAULT '0' AFTER Enabled,
ADD INDEX (FrontEndOnly);
UPDATE Events SET FrontEndOnly = 1 WHERE Enabled = 2;
UPDATE Events SET Enabled = 1 WHERE Enabled = 2;
ALTER TABLE Events CHANGE FromUserId FromUserId INT(11) NULL DEFAULT NULL;
UPDATE Events SET FromUserId = NULL WHERE FromUserId = 0;
DELETE FROM ConfigurationAdmin WHERE VariableName = 'SiteNameSubTitle';
DELETE FROM ConfigurationValues WHERE VariableName = 'SiteNameSubTitle';
UPDATE ConfigurationAdmin SET DisplayOrder = DisplayOrder - 0.01 WHERE VariableName IN ('UseModRewrite', 'cms_DefaultDesign', 'ErrorTemplate' 'NoPermissionTemplate', 'UsePageHitCounter', 'ForceImageMagickResize', 'CheckStopWords');
ALTER TABLE ConfigurationAdmin CHANGE validation Validation TEXT NULL DEFAULT NULL;
UPDATE ConfigurationAdmin SET Validation = 'a:3:{s:4:"type";s:3:"int";s:13:"min_value_inc";i:1;s:8:"required";i:1;}' WHERE VariableName = 'SessionTimeout';
INSERT INTO ConfigurationAdmin VALUES ('AdminConsoleInterface', 'la_section_SettingsAdmin', 'la_config_AdminConsoleInterface', 'select', '', 'simple=+simple,advanced=+advanced,custom=+custom', 50.01, 0, 1);
INSERT INTO ConfigurationValues VALUES (DEFAULT, 'AdminConsoleInterface', 'simple', 'In-Portal', 'in-portal:configure_general');
INSERT INTO ConfigurationAdmin VALUES ('AllowAdminConsoleInterfaceChange', 'la_section_SettingsAdmin', 'la_config_AllowAdminConsoleInterfaceChange', 'checkbox', NULL , NULL , 40.01, 0, 0);
INSERT INTO ConfigurationValues VALUES (DEFAULT, 'AllowAdminConsoleInterfaceChange', '1', 'In-Portal', 'in-portal:configure_advanced');
UPDATE ConfigurationAdmin SET DisplayOrder = DisplayOrder + 0.01 WHERE VariableName IN ('UseToolbarLabels', 'UseSmallHeader', 'UseColumnFreezer', 'UsePopups', 'UseDoubleSorting', 'MenuFrameWidth', 'ResizableFrames', 'AutoRefreshIntervals', 'DebugOnlyFormConfigurator', 'UseModalWindows');
INSERT INTO ConfigurationAdmin VALUES ('UseTemplateCompression', 'la_section_SettingsSystem', 'la_config_UseTemplateCompression', 'checkbox', '', '', 60.03, 0, 1);
INSERT INTO ConfigurationValues VALUES (DEFAULT, 'UseTemplateCompression', '0', 'In-Portal', 'in-portal:configure_advanced');
UPDATE ConfigurationAdmin SET DisplayOrder = DisplayOrder + 0.01 WHERE VariableName IN ('TrimRequiredFields', 'UseCronForRegularEvent', 'UseChangeLog', 'Backup_Path', 'SystemTagCache', 'SocketBlockingMode');
DELETE FROM ConfigurationAdmin WHERE VariableName = 'UseModalWindows';
DELETE FROM ConfigurationValues WHERE VariableName = 'UseModalWindows';
DELETE FROM Phrase WHERE Phrase = 'la_config_UseModalWindows';
UPDATE ConfigurationAdmin SET element_type = 'select', ValueList = '0=la_opt_SameWindow,1=la_opt_PopupWindow,2=la_opt_ModalWindow' WHERE VariableName = 'UsePopups';
UPDATE Phrase SET Translation = 'Editing Window Style' WHERE Phrase = 'la_config_UsePopups';
INSERT INTO ConfigurationAdmin VALUES ('UseVisitorTracking', 'la_section_SettingsWebsite', 'la_config_UseVisitorTracking', 'checkbox', '', '', 10.09, 0, 0);
INSERT INTO ConfigurationValues VALUES (DEFAULT, 'UseVisitorTracking', '0', 'In-Portal', 'in-portal:configure_advanced');
DELETE FROM ConfigurationAdmin WHERE VariableName = 'SessionReferrerCheck';
DELETE FROM ConfigurationValues WHERE VariableName = 'SessionReferrerCheck';
DELETE FROM Phrase WHERE Phrase = 'la_promt_ReferrerCheck';
INSERT INTO ConfigurationAdmin VALUES ('SessionBrowserSignatureCheck', 'la_section_SettingsSession', 'la_config_SessionBrowserSignatureCheck', 'checkbox', NULL, NULL, 20.04, 0, 1);
INSERT INTO ConfigurationValues VALUES (DEFAULT, 'SessionBrowserSignatureCheck', '0', 'In-Portal', 'in-portal:configure_advanced');
INSERT INTO ConfigurationAdmin VALUES ('SessionIPAddressCheck', 'la_section_SettingsSession', 'la_config_SessionIPAddressCheck', 'checkbox', NULL, NULL, 20.05, 0, 1);
INSERT INTO ConfigurationValues VALUES (DEFAULT, 'SessionIPAddressCheck', '0', 'In-Portal', 'in-portal:configure_advanced');
UPDATE ConfigurationAdmin SET DisplayOrder = DisplayOrder + 0.01 WHERE VariableName = 'UseJSRedirect';
ALTER TABLE UserSession
DROP CurrentTempKey,
DROP PrevTempKey,
ADD BrowserSignature VARCHAR(32) NOT NULL,
ADD INDEX (BrowserSignature);
UPDATE ConfigurationAdmin
SET DisplayOrder = DisplayOrder + 0.01
WHERE heading = 'la_section_SettingsAdmin' AND DisplayOrder > 40 AND DisplayOrder < 50;
UPDATE ConfigurationAdmin SET heading = 'la_section_SettingsAdmin', DisplayOrder = 40.01 WHERE VariableName = 'RootPass';
UPDATE ConfigurationValues SET ModuleOwner = 'In-Portal', Section = 'in-portal:configure_advanced' WHERE VariableName = 'RootPass';
UPDATE ConfigurationAdmin SET DisplayOrder = 10.12 WHERE VariableName = 'User_Default_Registration_Country';
UPDATE ConfigurationAdmin SET heading = 'la_section_SettingsAdmin', DisplayOrder = 40.12 WHERE VariableName = 'RememberLastAdminTemplate';
UPDATE ConfigurationValues SET ModuleOwner = 'In-Portal', Section = 'in-portal:configure_advanced' WHERE VariableName = 'RememberLastAdminTemplate';
UPDATE ConfigurationAdmin SET DisplayOrder = 10.14 WHERE VariableName = 'DefaultSettingsUserId';
INSERT INTO ConfigurationAdmin VALUES ('UseHTTPAuth', 'la_section_SettingsAdmin', 'la_config_UseHTTPAuth', 'checkbox', '', '', 40.13, 0, 0);
INSERT INTO ConfigurationValues VALUES (DEFAULT, 'UseHTTPAuth', '0', 'In-Portal', 'in-portal:configure_advanced');
INSERT INTO ConfigurationAdmin VALUES ('HTTPAuthUsername', 'la_section_SettingsAdmin', 'la_config_HTTPAuthUsername', 'text', '', '', 40.14, 0, 0);
INSERT INTO ConfigurationValues VALUES (DEFAULT, 'HTTPAuthUsername', '', 'In-Portal', 'in-portal:configure_advanced');
INSERT INTO ConfigurationAdmin VALUES ('HTTPAuthPassword', 'la_section_SettingsAdmin', 'la_config_HTTPAuthPassword', 'password', NULL, NULL, 40.15, 0, 0);
INSERT INTO ConfigurationValues VALUES (DEFAULT, 'HTTPAuthPassword', '', 'In-Portal', 'in-portal:configure_advanced');
INSERT INTO ConfigurationAdmin VALUES ('HTTPAuthBypassIPs', 'la_section_SettingsAdmin', 'la_config_HTTPAuthBypassIPs', 'text', '', '', 40.15, 0, 0);
INSERT INTO ConfigurationValues VALUES (DEFAULT, 'HTTPAuthBypassIPs', '', 'In-Portal', 'in-portal:configure_advanced');
INSERT INTO Permissions VALUES (DEFAULT, 'in-portal:service.edit', 11, 1, 1, 0);
UPDATE Phrase SET Phrase = 'la_col_Rating' WHERE Phrase = 'la_col_rating';
UPDATE Phrase SET Phrase = 'la_text_Review' WHERE Phrase = 'la_text_review';
UPDATE Phrase SET Phrase = 'la_title_Reviews' WHERE Phrase = 'la_title_reviews';
UPDATE Phrase SET Phrase = 'la_ToolTip_cancel' WHERE Phrase = 'la_tooltip_cancel';
ALTER TABLE Phrase
ADD PhraseKey VARCHAR(255) NOT NULL AFTER Phrase,
ADD INDEX (PhraseKey);
UPDATE Phrase SET PhraseKey = UPPER(Phrase);
UPDATE Modules SET Loaded = 1 WHERE `Name` = 'In-Portal';
# ===== v 5.0.2-B1 =====
ALTER TABLE PortalGroup DROP ResourceId;
ALTER TABLE Category
DROP l1_Translated,
DROP l2_Translated,
DROP l3_Translated,
DROP l4_Translated,
DROP l5_Translated;
ALTER TABLE PageContent
DROP l1_Translated,
DROP l2_Translated,
DROP l3_Translated,
DROP l4_Translated,
DROP l5_Translated;
ALTER TABLE Category
CHANGE CachedTemplate CachedTemplate varchar(255) NOT NULL DEFAULT '',
CHANGE ThemeId ThemeId int(10) unsigned NOT NULL DEFAULT '0';
ALTER TABLE UserSession CHANGE BrowserSignature BrowserSignature varchar(32) NOT NULL DEFAULT '';
ALTER TABLE ChangeLogs
CHANGE Changes Changes text NULL,
CHANGE OccuredOn OccuredOn INT(11) NULL DEFAULT NULL;
ALTER TABLE EmailLog CHANGE EventParams EventParams text NULL;
ALTER TABLE FormFields CHANGE DefaultValue DefaultValue text NULL;
ALTER TABLE ImportCache CHANGE VarValue VarValue text NULL;
ALTER TABLE ImportScripts CHANGE Description Description text NULL;
ALTER TABLE PersistantSessionData CHANGE VariableValue VariableValue text NULL;
ALTER TABLE Phrase
CHANGE `Translation` `Translation` text NULL,
CHANGE PhraseKey PhraseKey VARCHAR(255) NOT NULL DEFAULT '',
CHANGE LastChanged LastChanged INT(10) UNSIGNED NULL DEFAULT NULL;
ALTER TABLE PhraseCache CHANGE PhraseList PhraseList text NULL;
ALTER TABLE Stylesheets
CHANGE AdvancedCSS AdvancedCSS text NULL,
CHANGE LastCompiled LastCompiled INT(10) UNSIGNED NULL DEFAULT NULL;
ALTER TABLE StylesheetSelectors
CHANGE SelectorData SelectorData text NULL,
CHANGE Description Description text NULL,
CHANGE AdvancedCSS AdvancedCSS text NULL;
ALTER TABLE Category
CHANGE `Status` `Status` TINYINT(4) NOT NULL DEFAULT '1',
CHANGE CreatedOn CreatedOn INT(11) NULL DEFAULT NULL,
CHANGE Modified Modified INT(11) NULL DEFAULT NULL;
ALTER TABLE Language CHANGE UserDocsUrl UserDocsUrl VARCHAR(255) NOT NULL DEFAULT '';
ALTER TABLE MailingLists
CHANGE Subject Subject VARCHAR(255) NOT NULL DEFAULT '',
CHANGE EmailsQueued EmailsQueued INT(10) UNSIGNED NOT NULL DEFAULT '0',
CHANGE EmailsSent EmailsSent INT(10) UNSIGNED NOT NULL DEFAULT '0',
CHANGE EmailsTotal EmailsTotal INT(10) UNSIGNED NOT NULL DEFAULT '0';
ALTER TABLE EmailQueue
CHANGE MailingId MailingId INT(10) UNSIGNED NOT NULL DEFAULT '0',
CHANGE Queued Queued INT(10) UNSIGNED NULL DEFAULT NULL,
CHANGE LastSendRetry LastSendRetry INT(10) UNSIGNED NULL DEFAULT NULL;
ALTER TABLE ImportScripts CHANGE `Status` `Status` TINYINT(4) NOT NULL DEFAULT '1';
ALTER TABLE Semaphores
CHANGE SessionKey SessionKey INT(10) UNSIGNED NOT NULL DEFAULT '0',
CHANGE `Timestamp` `Timestamp` INT(10) UNSIGNED NOT NULL DEFAULT '0',
CHANGE MainPrefix MainPrefix VARCHAR(255) NOT NULL DEFAULT '';
ALTER TABLE Skins
CHANGE LogoBottom LogoBottom VARCHAR(255) NOT NULL DEFAULT '',
CHANGE LogoLogin LogoLogin VARCHAR(255) NOT NULL DEFAULT '';
ALTER TABLE ItemReview CHANGE ReviewText ReviewText LONGTEXT NULL;
ALTER TABLE SessionData CHANGE VariableValue VariableValue LONGTEXT NULL;
ALTER TABLE PortalUser
CHANGE `Status` `Status` TINYINT(4) NOT NULL DEFAULT '1',
CHANGE Modified Modified INT(11) NULL DEFAULT NULL;
ALTER TABLE ItemFiles CHANGE CreatedOn CreatedOn INT(11) UNSIGNED NULL DEFAULT NULL;
ALTER TABLE FormSubmissions CHANGE SubmissionTime SubmissionTime INT(11) NULL DEFAULT NULL;
ALTER TABLE SessionLogs CHANGE SessionStart SessionStart INT(11) NULL DEFAULT NULL;
ALTER TABLE Visits CHANGE VisitDate VisitDate INT(10) UNSIGNED NULL DEFAULT NULL;
# ===== v 5.0.2-B2 =====
ALTER TABLE Theme
ADD LanguagePackInstalled TINYINT UNSIGNED NOT NULL DEFAULT '0',
ADD TemplateAliases TEXT,
ADD INDEX (LanguagePackInstalled);
ALTER TABLE ThemeFiles
ADD TemplateAlias VARCHAR(255) NOT NULL DEFAULT '' AFTER FilePath,
ADD INDEX (TemplateAlias);
UPDATE Phrase SET PhraseType = 1 WHERE Phrase IN ('la_ToolTip_MoveUp', 'la_ToolTip_MoveDown', 'la_invalid_state', 'la_Pending', 'la_text_sess_expired', 'la_ToolTip_Export');
DELETE FROM Phrase WHERE Phrase IN ('la_ToolTip_Move_Up', 'la_ToolTip_Move_Down');
UPDATE Phrase SET Phrase = 'lu_btn_SendPassword' WHERE Phrase = 'LU_BTN_SENDPASSWORD';
ALTER TABLE Category DROP IsIndex;
DELETE FROM Phrase WHERE Phrase IN ('la_CategoryIndex', 'la_Container', 'la_fld_IsIndex', 'lu_text_Redirecting', 'lu_title_Redirecting', 'lu_zip_code');
ALTER TABLE PortalUser
ADD AdminLanguage INT(11) NULL DEFAULT NULL,
ADD INDEX (AdminLanguage);
# ===== v 5.0.2-RC1 =====
# ===== v 5.0.2 =====
# ===== v 5.0.3-B1 =====
ALTER TABLE PermCache ADD INDEX (ACL);
INSERT INTO ConfigurationAdmin VALUES ('cms_DefaultTrackingCode', 'la_section_SettingsWebsite', 'la_config_DefaultTrackingCode', 'textarea', NULL, 'COLS=40 ROWS=5', 10.10, 0, 0);
INSERT INTO ConfigurationValues VALUES (DEFAULT, 'cms_DefaultTrackingCode', '', 'In-Portal', 'in-portal:configure_advanced');
UPDATE Phrase
SET Module = 'Core'
WHERE Phrase IN ('la_fld_Image', 'la_fld_Qty');
# ===== v 5.0.3-B2 =====
UPDATE CustomField SET ValueList = REPLACE(ValueList, '=+||', '') WHERE ElementType = 'radio';
# ===== v 5.0.3-RC1 =====
# ===== v 5.0.3 =====
# ===== v 5.0.4-B1 =====
# ===== v 5.0.4-B2 =====
# ===== v 5.0.4 =====
# ===== v 5.1.0-B1 =====
DROP TABLE EmailMessage;
DELETE FROM PersistantSessionData WHERE VariableName = 'emailevents_columns_.';
INSERT INTO Permissions (Permission, GroupId, PermissionValue, Type, CatId)
SELECT 'in-portal:configemail.add' AS Permission, GroupId, PermissionValue, Type, CatId
FROM <%TABLE_PREFIX%>Permissions
WHERE Permission = 'in-portal:configemail.edit';
INSERT INTO Permissions (Permission, GroupId, PermissionValue, Type, CatId)
SELECT 'in-portal:configemail.delete' AS Permission, GroupId, PermissionValue, Type, CatId
FROM <%TABLE_PREFIX%>Permissions
WHERE Permission = 'in-portal:configemail.edit';
ALTER TABLE Events ADD l1_Description text;
UPDATE Events e
SET e.l1_Description = (
SELECT p.l<%PRIMARY_LANGUAGE%>_Translation
FROM <%TABLE_PREFIX%>Phrase p
WHERE p.Phrase = e.Description
);
UPDATE Events SET Description = l1_Description;
ALTER TABLE Events
DROP l1_Description,
CHANGE Description Description TEXT NULL;
DELETE FROM Phrase WHERE Phrase LIKE 'la_event_%';
DELETE FROM PersistantSessionData WHERE VariableName = 'phrases_columns_.';
UPDATE Category SET FormId = NULL WHERE FormId = 0;
INSERT INTO ConfigurationAdmin VALUES ('MemcacheServers', 'la_section_SettingsCaching', 'la_config_MemcacheServers', 'text', '', '', 80.02, 0, 0);
INSERT INTO ConfigurationValues VALUES (DEFAULT, 'MemcacheServers', 'localhost:11211', 'In-Portal', 'in-portal:configure_advanced');
ALTER TABLE Category
ADD EnablePageCache TINYINT NOT NULL DEFAULT '0',
ADD OverridePageCacheKey TINYINT NOT NULL DEFAULT '0',
ADD PageCacheKey VARCHAR(255) NOT NULL DEFAULT '',
ADD PageExpiration INT NULL DEFAULT NULL ,
ADD INDEX (EnablePageCache),
ADD INDEX (OverridePageCacheKey),
ADD INDEX (PageExpiration);
DELETE FROM Cache WHERE VarName LIKE 'mod_rw_%';
CREATE TABLE CachedUrls (
UrlId int(11) NOT NULL AUTO_INCREMENT,
Url varchar(255) NOT NULL DEFAULT '',
DomainId int(11) NOT NULL DEFAULT '0',
`Hash` int(11) NOT NULL DEFAULT '0',
Prefixes varchar(255) NOT NULL DEFAULT '',
ParsedVars text NOT NULL,
Cached int(10) unsigned DEFAULT NULL,
LifeTime int(11) NOT NULL DEFAULT '-1',
PRIMARY KEY (UrlId),
KEY Url (Url),
KEY `Hash` (`Hash`),
KEY Prefixes (Prefixes),
KEY Cached (Cached),
KEY LifeTime (LifeTime),
KEY DomainId (DomainId)
);
INSERT INTO ConfigurationAdmin VALUES ('CacheHandler', 'la_section_SettingsCaching', 'la_config_CacheHandler', 'select', NULL, 'Fake=la_None||Memcache=+Memcached||Apc=+Alternative PHP Cache||XCache=+XCache', 80.01, 0, 0);
INSERT INTO ConfigurationValues VALUES (DEFAULT, 'CacheHandler', 'Fake', 'In-Portal', 'in-portal:configure_advanced');
ALTER TABLE ConfigurationValues
ADD Heading varchar(255) NOT NULL DEFAULT '',
ADD Prompt varchar(255) NOT NULL DEFAULT '',
ADD ElementType varchar(255) NOT NULL DEFAULT '',
ADD Validation text,
ADD ValueList text,
ADD DisplayOrder double NOT NULL DEFAULT '0',
ADD GroupDisplayOrder double NOT NULL DEFAULT '0',
ADD Install int(11) NOT NULL DEFAULT '1',
ADD INDEX (DisplayOrder),
ADD INDEX (GroupDisplayOrder),
ADD INDEX (Install);
UPDATE ConfigurationValues cv
SET
cv.Heading = (SELECT ca1.heading FROM <%TABLE_PREFIX%>ConfigurationAdmin ca1 WHERE ca1.VariableName = cv.VariableName),
cv.Prompt = (SELECT ca2.prompt FROM <%TABLE_PREFIX%>ConfigurationAdmin ca2 WHERE ca2.VariableName = cv.VariableName),
cv.ElementType = (SELECT ca3.element_type FROM <%TABLE_PREFIX%>ConfigurationAdmin ca3 WHERE ca3.VariableName = cv.VariableName),
cv.Validation = (SELECT ca4.Validation FROM <%TABLE_PREFIX%>ConfigurationAdmin ca4 WHERE ca4.VariableName = cv.VariableName),
cv.ValueList = (SELECT ca5.ValueList FROM <%TABLE_PREFIX%>ConfigurationAdmin ca5 WHERE ca5.VariableName = cv.VariableName),
cv.DisplayOrder = (SELECT ca6.DisplayOrder FROM <%TABLE_PREFIX%>ConfigurationAdmin ca6 WHERE ca6.VariableName = cv.VariableName),
cv.GroupDisplayOrder = (SELECT ca7.GroupDisplayOrder FROM <%TABLE_PREFIX%>ConfigurationAdmin ca7 WHERE ca7.VariableName = cv.VariableName),
cv.`Install` = (SELECT ca8.`Install` FROM <%TABLE_PREFIX%>ConfigurationAdmin ca8 WHERE ca8.VariableName = cv.VariableName);
DROP TABLE ConfigurationAdmin;
UPDATE ConfigurationValues
SET ValueList = '=+||<SQL+>SELECT l%3$s_Name AS OptionName, CountryStateId AS OptionValue FROM <PREFIX>CountryStates WHERE Type = 1 ORDER BY OptionName</SQL>'
WHERE ValueList = '=+||<SQL>SELECT DestName AS OptionName, DestId AS OptionValue FROM <PREFIX>StdDestinations WHERE COALESCE(DestParentId, 0) = 0 ORDER BY OptionName</SQL>';
ALTER TABLE Forms
ADD RequireLogin TINYINT NOT NULL DEFAULT '0',
ADD INDEX (RequireLogin),
ADD UseSecurityImage TINYINT NOT NULL DEFAULT '0',
ADD INDEX (UseSecurityImage),
ADD EnableEmailCommunication TINYINT NOT NULL DEFAULT '0',
ADD INDEX (EnableEmailCommunication),
ADD ReplyFromName VARCHAR(255) NOT NULL DEFAULT '',
ADD ReplyFromEmail VARCHAR(255) NOT NULL DEFAULT '',
ADD ReplyCc VARCHAR(255) NOT NULL DEFAULT '',
ADD ReplyBcc VARCHAR(255) NOT NULL DEFAULT '',
ADD ReplyMessageSignature TEXT,
ADD ReplyServer VARCHAR(255) NOT NULL DEFAULT '',
ADD ReplyPort INT(10) NOT NULL DEFAULT '110',
ADD ReplyUsername VARCHAR(255) NOT NULL DEFAULT '',
ADD ReplyPassword VARCHAR(255) NOT NULL DEFAULT '',
ADD BounceEmail VARCHAR(255) NOT NULL DEFAULT '',
ADD BounceServer VARCHAR(255) NOT NULL DEFAULT '',
ADD BouncePort INT(10) NOT NULL DEFAULT '110',
ADD BounceUsername VARCHAR(255) NOT NULL DEFAULT '',
ADD BouncePassword VARCHAR(255) NOT NULL DEFAULT '';
ALTER TABLE FormFields
ADD Visibility TINYINT NOT NULL DEFAULT '1',
ADD INDEX (Visibility),
ADD EmailCommunicationRole TINYINT NOT NULL DEFAULT '0',
ADD INDEX (EmailCommunicationRole);
ALTER TABLE FormSubmissions
ADD IPAddress VARCHAR(15) NOT NULL DEFAULT '' AFTER SubmissionTime,
ADD ReferrerURL VARCHAR(255) NOT NULL DEFAULT '' AFTER IPAddress,
ADD LogStatus TINYINT UNSIGNED NOT NULL DEFAULT '2' AFTER ReferrerURL,
ADD LastUpdatedOn INT UNSIGNED NULL AFTER LogStatus,
ADD Notes TEXT NULL AFTER LastUpdatedOn,
ADD INDEX (LogStatus),
ADD INDEX (LastUpdatedOn);
CREATE TABLE SubmissionLog (
SubmissionLogId int(11) NOT NULL AUTO_INCREMENT,
FormSubmissionId int(10) unsigned NOT NULL,
FromEmail varchar(255) NOT NULL DEFAULT '',
ToEmail varchar(255) NOT NULL DEFAULT '',
Cc text,
Bcc text,
`Subject` varchar(255) NOT NULL DEFAULT '',
Message text,
Attachment text,
ReplyStatus tinyint(3) unsigned NOT NULL DEFAULT '0',
SentStatus tinyint(3) unsigned NOT NULL DEFAULT '0',
SentOn int(10) unsigned DEFAULT NULL,
RepliedOn int(10) unsigned DEFAULT NULL,
VerifyCode varchar(32) NOT NULL DEFAULT '',
DraftId int(10) unsigned NOT NULL DEFAULT '0',
MessageId varchar(255) NOT NULL DEFAULT '',
BounceInfo text,
BounceDate int(11) DEFAULT NULL,
PRIMARY KEY (SubmissionLogId),
KEY FormSubmissionId (FormSubmissionId),
KEY ReplyStatus (ReplyStatus),
KEY SentStatus (SentStatus),
KEY SentOn (SentOn),
KEY RepliedOn (RepliedOn),
KEY VerifyCode (VerifyCode),
KEY DraftId (DraftId),
KEY BounceDate (BounceDate),
KEY MessageId (MessageId)
);
CREATE TABLE Drafts (
DraftId int(11) NOT NULL AUTO_INCREMENT,
FormSubmissionId int(10) unsigned NOT NULL DEFAULT '0',
CreatedOn int(10) unsigned DEFAULT NULL,
CreatedById int(11) NOT NULL,
Message text,
PRIMARY KEY (DraftId),
KEY FormSubmissionId (FormSubmissionId),
KEY CreatedOn (CreatedOn),
KEY CreatedById (CreatedById)
);
INSERT INTO Events (EventId, Event, ReplacementTags, Enabled, FrontEndOnly, FromUserId, Module, Description, Type) VALUES(DEFAULT, 'FORM.SUBMISSION.REPLY.TO.USER', NULL, 1, 0, NULL, 'Core:Category', 'Admin Reply to User Form Submission', 1);
INSERT INTO Events (EventId, Event, ReplacementTags, Enabled, FrontEndOnly, FromUserId, Module, Description, Type) VALUES(DEFAULT, 'FORM.SUBMISSION.REPLY.FROM.USER', NULL, 1, 0, NULL, 'Core:Category', 'User Replied to It\'s Form Submission', 1);
INSERT INTO Events (EventId, Event, ReplacementTags, Enabled, FrontEndOnly, FromUserId, Module, Description, Type) VALUES(DEFAULT, 'FORM.SUBMISSION.REPLY.FROM.USER.BOUNCED', NULL, 1, 0, NULL, 'Core:Category', 'Form Submission Admin Reply Delivery Failure', 1);
ALTER TABLE ConfigurationValues
ADD HintLabel VARCHAR(255) NULL DEFAULT NULL,
ADD INDEX (HintLabel);
UPDATE ConfigurationValues SET HintLabel = 'la_hint_MemcacheServers' WHERE VariableName = 'MemcacheServers';
INSERT INTO ConfigurationValues VALUES(DEFAULT, 'ModRewriteUrlEnding', '.html', 'In-Portal', 'in-portal:configure_advanced', 'la_section_SettingsWebsite', 'la_config_ModRewriteUrlEnding', 'select', '', '=+||/=+/||.html=+.html', 10.021, 0, 0, NULL);
INSERT INTO ConfigurationValues VALUES(DEFAULT, 'ForceModRewriteUrlEnding', '0', 'In-Portal', 'in-portal:configure_advanced', 'la_section_SettingsWebsite', 'la_config_ForceModRewriteUrlEnding', 'checkbox', '', NULL, 10.022, 0, 0, 'la_hint_ForceModRewriteUrlEnding');
UPDATE Phrase
SET l<%PRIMARY_LANGUAGE%>_Translation = 'Enable SEO-friendly URLs mode (MOD-REWRITE)'
WHERE Phrase = 'la_config_use_modrewrite' AND l<%PRIMARY_LANGUAGE%>_Translation = 'Use MOD REWRITE';
INSERT INTO ConfigurationValues VALUES(DEFAULT, 'UseContentLanguageNegotiation', '0', 'In-Portal', 'in-portal:configure_advanced', 'la_section_SettingsWebsite', 'la_config_UseContentLanguageNegotiation', 'checkbox', '', '', 10.023, 0, 0, NULL);
INSERT INTO ConfigurationValues VALUES(DEFAULT, 'SessionCookieDomains', '', 'In-Portal', 'in-portal:configure_advanced', 'la_section_SettingsSession', 'la_config_SessionCookieDomains', 'textarea', '', 'rows="5" cols="40"', 20.021, 0, 0, NULL);
CREATE TABLE SiteDomains (
DomainId int(11) NOT NULL AUTO_INCREMENT,
DomainName varchar(255) NOT NULL DEFAULT '',
DomainNameUsesRegExp tinyint(4) NOT NULL DEFAULT '0',
SSLUrl varchar(255) NOT NULL DEFAULT '',
SSLUrlUsesRegExp tinyint(4) NOT NULL DEFAULT '0',
AdminEmail varchar(255) NOT NULL DEFAULT '',
Country varchar(3) NOT NULL DEFAULT '',
PrimaryLanguageId int(11) NOT NULL DEFAULT '0',
Languages varchar(255) NOT NULL DEFAULT '',
PrimaryThemeId int(11) NOT NULL DEFAULT '0',
Themes varchar(255) NOT NULL DEFAULT '',
DomainIPRange text,
ExternalUrl varchar(255) NOT NULL DEFAULT '',
RedirectOnIPMatch tinyint(4) NOT NULL DEFAULT '0',
Priority int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (DomainId),
KEY DomainName (DomainName),
KEY DomainNameUsesRegExp (DomainNameUsesRegExp),
KEY SSLUrl (SSLUrl),
KEY SSLUrlUsesRegExp (SSLUrlUsesRegExp),
KEY AdminEmail (AdminEmail),
KEY Country (Country),
KEY PrimaryLanguageId (PrimaryLanguageId),
KEY Languages (Languages),
KEY PrimaryThemeId (PrimaryThemeId),
KEY Themes (Themes),
KEY ExternalUrl (ExternalUrl),
KEY RedirectOnIPMatch (RedirectOnIPMatch),
KEY Priority (Priority)
);
DELETE FROM Phrase WHERE Phrase = 'la_config_time_server';
DELETE FROM ConfigurationValues WHERE VariableName = 'Config_Server_Time';
UPDATE ConfigurationValues SET ValueList = NULL, DisplayOrder = 20.02 WHERE VariableName = 'Config_Site_Time';
UPDATE ConfigurationValues SET VariableValue = '' WHERE VariableName = 'Config_Site_Time' AND VariableValue = 14;
UPDATE Events SET AllowChangingSender = 1, AllowChangingRecipient = 1;
UPDATE Events SET Module = 'Core' WHERE Module LIKE 'Core:%';
DELETE FROM Permissions WHERE Permission LIKE 'in-portal:configuration_email%';
DELETE FROM Permissions WHERE Permission LIKE 'in-portal:user_email%';
DELETE FROM Phrase WHERE Phrase IN ('la_fld_FromToUser', 'la_col_FromToUser');
# ===== v 5.1.0-B2 =====
# ===== v 5.1.0-RC1 =====
UPDATE Phrase SET Module = 'Core' WHERE Phrase = 'la_fld_Group';
UPDATE PermissionConfig
SET
Description = REPLACE(Description, 'lu_PermName_', 'la_PermName_'),
ErrorMessage = REPLACE(ErrorMessage, 'lu_PermName_', 'la_PermName_');
UPDATE Phrase
SET
Phrase = REPLACE(Phrase, 'lu_PermName_', 'la_PermName_'),
PhraseKey = REPLACE(PhraseKey, 'LU_PERMNAME_', 'LA_PERMNAME_'),
PhraseType = 1
WHERE PhraseKey LIKE 'LU_PERMNAME_%';
UPDATE Phrase
SET
Phrase = 'la_no_permissions',
PhraseKey = 'LA_NO_PERMISSIONS',
PhraseType = 1
WHERE PhraseKey = 'LU_NO_PERMISSIONS';
UPDATE Phrase
SET PhraseType = 0
WHERE PhraseKey IN (
'LU_FERROR_FORGOTPW_NODATA', 'LU_FERROR_UNKNOWN_USERNAME', 'LU_FERROR_UNKNOWN_EMAIL'
);
DELETE FROM ConfigurationValues WHERE VariableName = 'Root_Name';
DELETE FROM Phrase WHERE PhraseKey = 'LA_PROMPT_ROOT_NAME';
UPDATE ConfigurationValues
SET DisplayOrder = DisplayOrder - 0.01
WHERE ModuleOwner = 'In-Portal' AND `Section` = 'in-portal:configure_categories' AND DisplayOrder > 10.07;
# ===== v 5.1.0 =====
UPDATE Events SET Headers = NULL WHERE Headers = '';
UPDATE Events
SET MessageType = 'text'
WHERE Event = 'FORM.SUBMISSION.REPLY.TO.USER';
ALTER TABLE Forms
ADD ProcessUnmatchedEmails TINYINT NOT NULL DEFAULT '0' AFTER EnableEmailCommunication,
ADD INDEX (ProcessUnmatchedEmails);
ALTER TABLE FormSubmissions
ADD MessageId VARCHAR(255) NULL DEFAULT NULL AFTER Notes,
ADD INDEX (MessageId);
# ===== v 5.1.1-B1 =====
ALTER TABLE PortalUser ADD DisplayToPublic TEXT NULL;
UPDATE Phrase
SET l<%PRIMARY_LANGUAGE%>_Translation = 'Comments'
WHERE PhraseKey = 'LA_FLD_COMMENTS';
ALTER TABLE Category
CHANGE `Type` `Type` INT(11) NOT NULL DEFAULT '1',
CHANGE `IsSystem` `Protected` TINYINT( 4 ) NOT NULL DEFAULT '0',
ADD INDEX ( `Protected` );
UPDATE Category SET `Type` = IF(`Protected` = 1, 2, 1);
UPDATE Category SET `Protected` = 1 WHERE ThemeId > 0;
ALTER TABLE Category CHANGE CachedDescendantCatsQty CachedDescendantCatsQty INT(11) NOT NULL DEFAULT '0';
ALTER TABLE Events CHANGE `Module` `Module` VARCHAR(40) NOT NULL DEFAULT 'Core';
ALTER TABLE Language
CHANGE DateFormat DateFormat VARCHAR(50) NOT NULL DEFAULT 'm/d/Y',
CHANGE TimeFormat TimeFormat VARCHAR(50) NOT NULL DEFAULT 'g:i:s A',
CHANGE DecimalPoint DecimalPoint VARCHAR(10) NOT NULL DEFAULT '.',
CHANGE Charset Charset VARCHAR(20) NOT NULL DEFAULT 'utf-8';
ALTER TABLE ItemReview CHANGE Rating Rating TINYINT(3) UNSIGNED NOT NULL DEFAULT '0';
UPDATE PortalUser SET tz = NULL;
ALTER TABLE Category
CHANGE CreatedById CreatedById INT(11) NULL DEFAULT NULL,
CHANGE ModifiedById ModifiedById INT(11) NULL DEFAULT NULL;
UPDATE Category SET CreatedById = NULL WHERE CreatedById = 0;
UPDATE Category SET ModifiedById = NULL WHERE ModifiedById = 0;
ALTER TABLE ItemFiles CHANGE CreatedById CreatedById INT(11) NULL DEFAULT NULL;
ALTER TABLE Drafts CHANGE CreatedById CreatedById INT(11) NULL DEFAULT NULL;
UPDATE Drafts SET CreatedById = NULL WHERE CreatedById = 0;
ALTER TABLE ItemReview CHANGE CreatedById CreatedById INT(11) NULL DEFAULT NULL;
# ===== v 5.1.1-B2 =====
UPDATE Phrase SET `Module` = 'Core' WHERE PhraseKey = 'LU_SECTION_FILES';
# ===== v 5.1.1-RC1 =====
ALTER TABLE PortalUser
CHANGE Phone Phone VARCHAR(255) NOT NULL DEFAULT '',
CHANGE City City VARCHAR(255) NOT NULL DEFAULT '',
CHANGE Street Street VARCHAR(255) NOT NULL DEFAULT '',
CHANGE Zip Zip VARCHAR(20) NOT NULL DEFAULT '',
CHANGE ip ip VARCHAR(20) NOT NULL DEFAULT '';
UPDATE Phrase
SET l<%PRIMARY_LANGUAGE%>_Translation = 'Use Cron to run Agents'
WHERE PhraseKey = 'LA_USECRONFORREGULAREVENT' AND l<%PRIMARY_LANGUAGE%>_Translation = 'Use Cron for Running Regular Events';
# ===== v 5.1.1 =====
# ===== v 5.1.2-B1 =====
DROP TABLE EmailSubscribers;
DROP TABLE IgnoreKeywords;
DROP TABLE IgnoreKeywords;
ALTER TABLE PermissionConfig DROP ErrorMessage;
# ===== v 5.1.2-B2 =====
# ===== v 5.1.2-RC1 =====
DROP TABLE Stylesheets;
DROP TABLE StylesheetSelectors;
DROP TABLE SysCache;
DROP TABLE TagAttributes;
DROP TABLE TagLibrary;
DELETE FROM Phrase WHERE PhraseKey IN (
'LA_FLD_STYLESHEETID', 'LA_PROMPT_STYLESHEET', 'LA_TAB_STYLESHEETS', 'LA_TITLE_ADDING_STYLESHEET',
'LA_TITLE_EDITING_STYLESHEET', 'LA_TITLE_NEW_STYLESHEET', 'LA_TITLE_STYLESHEETS', 'LA_TOOLTIP_NEWSTYLESHEET',
'LA_COL_SELECTORNAME', 'LA_COL_BASEDON', 'LA_FLD_SELECTORBASE', 'LA_FLD_SELECTORDATA', 'LA_FLD_SELECTORID',
'LA_FLD_SELECTORNAME'
);
# ===== v 5.1.2 =====
# ===== v 5.1.3-B1 =====
ALTER TABLE FormSubmissions CHANGE ReferrerURL ReferrerURL TEXT NULL;
INSERT INTO ConfigurationValues VALUES (DEFAULT, 'UserEmailActivationTimeout', '', 'In-Portal:Users', 'in-portal:configure_users', 'la_title_General', 'la_config_UserEmailActivationTimeout', 'text', NULL, NULL, 10.051, 0, 0, NULL);
# ===== v 5.1.3-B2 =====
ALTER TABLE Modules ADD AppliedDBRevisions TEXT NULL;
# ===== v 5.1.3-RC1 =====
# ===== v 5.1.3-RC2 =====
UPDATE Events
SET l<%PRIMARY_LANGUAGE%>_Subject = 'New User Registration (<inp2:u_Field name="Login"/><inp2:m_if check="m_GetConfig" name="User_Allow_New" equals_to="4"> - Activation Email</inp2:m_if>)'
WHERE Event = 'USER.ADD.PENDING' AND `Type` = 0 AND l<%PRIMARY_LANGUAGE%>_Subject LIKE '%<inp2:m_if check="m_GetConfig" name="User_Allow_New" equals_to="4"> - Activation Email</inp2:m_if>)%';
INSERT INTO ConfigurationValues VALUES(DEFAULT, 'MaxUserName', '', 'In-Portal:Users', 'in-portal:configure_users', 'la_title_General', 'la_text_min_username', 'text', '', 'style="width: 50px;"', 10.03, 2, 0, NULL);
UPDATE ConfigurationValues
SET GroupDisplayOrder = 1, ValueList = 'style="width: 50px;"'
WHERE VariableName = 'Min_UserName';
UPDATE Phrase
SET l<%PRIMARY_LANGUAGE%>_Translation = 'User name length (min - max)'
WHERE PhraseKey = 'LA_TEXT_MIN_USERNAME' AND l<%PRIMARY_LANGUAGE%>_Translation = 'Minimum user name length';
# ===== v 5.1.3 =====
UPDATE PortalUser
SET Modified = NULL;
INSERT INTO Permissions VALUES (DEFAULT, 'in-portal:site_domains.delete', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-portal:site_domains.edit', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-portal:site_domains.add', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-portal:site_domains.view', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-portal:country_states.delete', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-portal:country_states.edit', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-portal:country_states.add', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-portal:country_states.view', 11, 1, 1, 0);
# ===== v 5.2.0-B1 =====
ALTER TABLE PortalUser
ADD UserType TINYINT NOT NULL,
ADD PrimaryGroupId INT NULL,
ADD INDEX (UserType);
UPDATE PortalUser u
SET u.PrimaryGroupId = (SELECT ug.GroupId FROM <%TABLE_PREFIX%>UserGroup ug WHERE ug.PortalUserId = u.PortalUserId AND ug.PrimaryGroup = 1);
UPDATE PortalUser u SET u.UserType = IF(u.PrimaryGroupId = 11, 1, 0);
ALTER TABLE UserGroup DROP PrimaryGroup;
UPDATE ConfigurationValues
SET DisplayOrder = DisplayOrder + 0.01
WHERE `ModuleOwner` = 'In-Portal:Users' AND `Section` = 'in-portal:configure_users' AND DisplayOrder BETWEEN 10.12 AND 20.00;
INSERT INTO ConfigurationValues VALUES(DEFAULT, 'User_AdminGroup', '11', 'In-Portal:Users', 'in-portal:configure_users', 'la_title_General', 'la_users_admin_group', 'select', NULL, '0=lu_none||<SQL+>SELECT GroupId as OptionValue, Name as OptionName FROM <PREFIX>PortalGroup WHERE Enabled=1 AND Personal=0</SQL>', 10.12, 0, 1, NULL);
ALTER TABLE PortalUser
DROP INDEX Login,
ADD INDEX Login (Login);
ALTER TABLE PortalUser CHANGE Login Login VARCHAR(255) NOT NULL;
ALTER TABLE PortalUser ADD OldStyleLogin TINYINT NOT NULL;
UPDATE PortalUser
SET OldStyleLogin = 1
WHERE (Login <> '') AND (Login NOT REGEXP '^[A-Z0-9_\\-\\.]+$');
DELETE FROM Events WHERE Event = 'USER.PSWD';
UPDATE Phrase
SET l<%PRIMARY_LANGUAGE%>_Translation = 'Your password has been reset.'
WHERE PhraseKey = 'LU_TEXT_FORGOTPASSHASBEENRESET' AND l<%PRIMARY_LANGUAGE%>_Translation = 'Your password has been reset. The new password has been sent to your e-mail address. You may now login with the new password.';
ALTER TABLE PortalUser
DROP MinPwResetDelay,
DROP PassResetTime,
CHANGE PwResetConfirm PwResetConfirm VARCHAR(255) NOT NULL;
UPDATE PortalUser SET PwRequestTime = NULL WHERE PwRequestTime = 0;
ALTER TABLE Category
ADD DirectLinkEnabled TINYINT NOT NULL DEFAULT '1',
ADD DirectLinkAuthKey VARCHAR(20) NOT NULL;
UPDATE Category
SET DirectLinkAuthKey = SUBSTRING( MD5( CONCAT(CategoryId, ':', ParentId, ':', l<%PRIMARY_LANGUAGE%>_Name, ':b38') ), 1, 20)
WHERE DirectLinkAuthKey = '';
INSERT INTO ConfigurationValues VALUES(DEFAULT, 'ExcludeTemplateSectionsFromSearch', '0', 'In-Portal', 'in-portal:configure_categories', 'la_title_General', 'la_config_ExcludeTemplateSectionsFromSearch', 'checkbox', '', '', 10.15, 0, 0, NULL);
ALTER TABLE Agents
ADD SiteDomainLimitation VARCHAR(255) NOT NULL,
ADD INDEX (SiteDomainLimitation);
UPDATE ConfigurationValues
SET DisplayOrder = DisplayOrder + 0.01
WHERE VariableName = 'HTTPAuthBypassIPs';
UPDATE ConfigurationValues
SET DisplayOrder = DisplayOrder + 0.01
WHERE ModuleOwner = 'In-Portal' AND `Section` = 'in-portal:configure_advanced' AND Heading = 'la_section_SettingsAdmin' AND DisplayOrder > 40.06;
INSERT INTO ConfigurationValues VALUES (DEFAULT, 'StickyGridSelection', '1', 'In-Portal', 'in-portal:configure_advanced', 'la_section_SettingsAdmin', 'la_config_StickyGridSelection', 'radio', '', '1=la_Yes||0=la_No', 40.07, 0, 0, NULL);
ALTER TABLE Forms
ADD SubmitNotifyEmail VARCHAR(255) NOT NULL DEFAULT '' AFTER UseSecurityImage;
ALTER TABLE FormFields
ADD UploadExtensions VARCHAR(255) NOT NULL DEFAULT '' AFTER Validation,
ADD UploadMaxSize INT NULL AFTER UploadExtensions;
ALTER TABLE Language ADD SynchronizationModes VARCHAR(255) NOT NULL DEFAULT '';
ALTER TABLE PortalUser
CHANGE ip IPAddress VARCHAR(15) NOT NULL,
ADD IPRestrictions TEXT NULL;
ALTER TABLE PortalGroup ADD IPRestrictions TEXT NULL;
INSERT INTO Events (EventId, Event, ReplacementTags, Enabled, FrontEndOnly, Module, Description, Type, AllowChangingSender, AllowChangingRecipient) VALUES(DEFAULT, 'ROOT.RESET.PASSWORD', NULL, 1, 0, 'Core', 'Root Reset Password', 1, 1, 0);
ALTER TABLE Skins ADD DisplaySiteNameInHeader TINYINT(1) NOT NULL DEFAULT '1';
DELETE FROM PersistantSessionData WHERE VariableName LIKE 'formsubs_Sort%' AND VariableValue = 'FormFieldId';
ALTER TABLE ItemReview
ADD HelpfulCount INT NOT NULL ,
ADD NotHelpfulCount INT NOT NULL;
ALTER TABLE PermissionConfig ADD IsSystem TINYINT(1) NOT NULL DEFAULT '0';
UPDATE PermissionConfig SET IsSystem = 1;
INSERT INTO Permissions VALUES (DEFAULT, 'in-portal:permission_types.view', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-portal:permission_types.add', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-portal:permission_types.edit', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-portal:permission_types.delete', 11, 1, 1, 0);
ALTER TABLE Agents
ADD Timeout INT(10) UNSIGNED NULL AFTER RunTime,
ADD LastTimeoutOn int(10) unsigned default NULL AFTER Timeout,
ADD INDEX (Timeout);
CREATE TABLE CurlLog (
LogId int(11) NOT NULL AUTO_INCREMENT,
Message varchar(255) NOT NULL,
PageUrl varchar(255) NOT NULL,
RequestUrl varchar(255) NOT NULL,
PortalUserId int(11) NOT NULL,
SessionKey int(11) NOT NULL,
IsAdmin tinyint(4) NOT NULL,
PageData text,
RequestData text,
ResponseData text,
RequestDate int(11) DEFAULT NULL,
ResponseDate int(11) DEFAULT NULL,
ResponseHttpCode int(11) NOT NULL,
CurlError varchar(255) NOT NULL,
PRIMARY KEY (LogId),
KEY Message (Message),
KEY PageUrl (PageUrl),
KEY RequestUrl (RequestUrl),
KEY PortalUserId (PortalUserId),
KEY SessionKey (SessionKey),
KEY IsAdmin (IsAdmin),
KEY RequestDate (RequestDate),
KEY ResponseDate (ResponseDate),
KEY ResponseHttpCode (ResponseHttpCode),
KEY CurlError (CurlError)
);
DELETE FROM ConfigurationValues WHERE VariableName = 'Site_Path';
UPDATE ConfigurationValues
SET DisplayOrder = DisplayOrder + 0.01
WHERE `Section` = 'in-portal:configure_advanced' AND Heading = 'la_section_SettingsWebsite';
UPDATE ItemTypes
SET TitleField = 'Username'
WHERE SourceTable = 'PortalUser' AND TitleField = 'Login';
UPDATE SearchConfig
SET FieldName = 'Username'
WHERE TableName = 'PortalUser' AND FieldName = 'Login';
ALTER TABLE PortalUser DROP INDEX Login;
ALTER TABLE PortalUser CHANGE Login Username VARCHAR(255) NOT NULL;
ALTER TABLE PortalUser ADD INDEX Username (Username);
UPDATE Events
SET
l<%PRIMARY_LANGUAGE%>_Subject = REPLACE(l<%PRIMARY_LANGUAGE%>_Subject, 'name="Login"', 'name="Username"'),
l<%PRIMARY_LANGUAGE%>_Body = REPLACE(l<%PRIMARY_LANGUAGE%>_Body, 'name="Login"', 'name="Username"');
DELETE FROM PersistantSessionData
WHERE (VariableName LIKE 'u%]columns_.') OR (VariableName LIKE 'u%_sort%');
DELETE FROM Phrase
WHERE Phrase = 'LU_FLD_LOGIN';
UPDATE BanRules
SET ItemField = 'Username'
WHERE ItemField = 'Login';
DELETE FROM Phrase
WHERE PhraseKey IN (
'LU_USERNAME', 'LU_EMAIL', 'LU_PASSWORD', 'LA_TEXT_LOGIN', 'LA_PROMPT_PASSWORD',
'LA_USE_EMAILS_AS_LOGIN', 'LU_USER_AND_EMAIL_ALREADY_EXIST', 'LU_ENTERFORGOTEMAIL'
);
UPDATE ConfigurationValues
SET VariableName = 'RegistrationUsernameRequired', Prompt = 'la_config_RegistrationUsernameRequired'
WHERE VariableName = 'Email_As_Login';
UPDATE ConfigurationValues
SET VariableValue = IF(VariableValue = 1, 0, 1)
WHERE VariableName = 'RegistrationUsernameRequired';
INSERT INTO ConfigurationValues VALUES (DEFAULT, 'PerformExactSearch', '1', 'In-Portal', 'in-portal:configure_advanced', 'la_section_SettingsWebsite', 'la_config_PerformExactSearch', 'checkbox', '', '', '10.10', 0, 0, 'la_hint_PerformExactSearch');
UPDATE Phrase
SET PhraseType = 1
WHERE PhraseKey IN (
'LA_USERS_SUBSCRIBER_GROUP', 'LA_PROMPT_DUPREVIEWS', 'LA_PROMPT_DUPREVIEWS', 'LA_PROMPT_DUPRATING',
'LA_PROMPT_OVERWRITEPHRASES', 'LA_TEXT_BACKUP_ACCESS', 'LA_PHRASETYPE_BOTH', 'LA_TOOLTIP_NEWLISTING'
);
UPDATE Phrase
SET PhraseType = 0
WHERE PhraseKey IN ('LU_TITLE_SHIPPINGINFORMATION', 'LU_COMM_LASTQUATER');
UPDATE Phrase
SET Phrase = REPLACE(Phrase, 'lu_', 'la_'), PhraseKey = UPPER(Phrase)
WHERE PhraseKey IN ('LU_OPT_AUTODETECT', 'LU_OPT_COOKIES', 'LU_OPT_QUERYSTRING');
UPDATE ConfigurationValues
SET ValueList = REPLACE(ValueList, 'lu_', 'la_')
WHERE VariableName = 'CookieSessions';
DELETE FROM Phrase WHERE PhraseKey IN ('LU_INVALID_PASSWORD', 'LA_OF', 'LU_TITLE_REVIEWPRODUCT');
UPDATE Phrase
SET PhraseType = 2
WHERE PhraseType = 1 AND (PhraseKey LIKE 'lu_field_%' OR PhraseKey = 'LA_TEXT_VALID');
UPDATE Phrase
SET Phrase = REPLACE(Phrase, 'la_', 'lc_'), PhraseKey = UPPER(Phrase)
WHERE PhraseType = 2;
UPDATE Phrase
SET Phrase = REPLACE(Phrase, 'lu_', 'lc_'), PhraseKey = UPPER(Phrase)
WHERE PhraseType = 2;
UPDATE SearchConfig
SET DisplayName = REPLACE(DisplayName, 'lu_', 'lc_')
WHERE DisplayName IN (
'lu_field_newitem', 'lu_field_popitem', 'lu_field_hotitem', 'lu_field_resourceid', 'lu_field_createdbyid',
'lu_field_priority', 'lu_field_status', 'lu_field_createdon', 'lu_field_description', 'lu_field_name',
'lu_field_modified', 'lu_field_modifiedbyid', 'lu_field_ParentPath', 'lu_field_ParentId', 'lu_field_MetaKeywords',
'lu_field_MetaDescription', 'lu_field_EditorsPick', 'lu_field_CategoryId', 'lu_field_CachedNavBar',
'lu_field_CachedDescendantCatsQty', 'lu_field_hits', 'lu_field_cachedrating', 'lu_field_cachedvotesqty',
'lu_field_cachedreviewsqty', 'lu_field_orgid'
);
CREATE TABLE SpamReports (
ReportId int(11) NOT NULL AUTO_INCREMENT,
ItemPrefix varchar(255) NOT NULL,
ItemId int(11) NOT NULL,
MessageText text,
ReportedOn int(11) DEFAULT NULL,
ReportedById int(11) DEFAULT NULL,
PRIMARY KEY (ReportId),
KEY ItemPrefix (ItemPrefix),
KEY ItemId (ItemId),
KEY ReportedById (ReportedById)
);
DELETE FROM Phrase
WHERE PhraseKey IN (
'LA_SECTION_SETTINGSCACHING', 'LA_CONFIG_CACHEHANDLER', 'LA_CONFIG_MEMCACHESERVERS', 'LA_HINT_MEMCACHESERVERS'
);
DELETE FROM ConfigurationValues WHERE VariableName IN ('CacheHandler', 'MemcacheServers');
CREATE TABLE PromoBlocks (
BlockId int(11) NOT NULL AUTO_INCREMENT,
Title varchar(50) NOT NULL DEFAULT '',
Priority int(11) NOT NULL DEFAULT '0',
Status tinyint(1) NOT NULL DEFAULT '0',
l1_Image varchar(255) NOT NULL DEFAULT '',
l2_Image varchar(255) NOT NULL DEFAULT '',
l3_Image varchar(255) NOT NULL DEFAULT '',
l4_Image varchar(255) NOT NULL DEFAULT '',
l5_Image varchar(255) NOT NULL DEFAULT '',
CSSClassName varchar(255) NOT NULL DEFAULT '',
LinkType tinyint(1) NOT NULL DEFAULT '1',
CategoryId int(11) NOT NULL DEFAULT '0',
ExternalLink varchar(255) NOT NULL DEFAULT '',
OpenInNewWindow tinyint(3) unsigned NOT NULL DEFAULT '0',
ScheduleFromDate int(11) DEFAULT NULL,
ScheduleToDate int(11) DEFAULT NULL,
NumberOfClicks int(11) NOT NULL DEFAULT '0',
NumberOfViews int(11) NOT NULL DEFAULT '0',
Sticky tinyint(1) NOT NULL DEFAULT '0',
Html text,
l1_Html text,
l2_Html text,
l3_Html text,
l4_Html text,
l5_Html text,
PRIMARY KEY (BlockId),
KEY OpenInNewWindow (OpenInNewWindow)
);
INSERT INTO ConfigurationValues VALUES (DEFAULT, 'PromoRotationDelay', '7', 'In-Portal', 'in-portal:configure_promo_blocks', 'la_Text_PromoSettings', 'la_config_PromoRotationDelay', 'text', '', '', 10.01, 0, 0, NULL);
INSERT INTO ConfigurationValues VALUES (DEFAULT, 'PromoTransitionTime', '0.6', 'In-Portal', 'in-portal:configure_promo_blocks', 'la_Text_PromoSettings', 'la_config_PromoTransitionTime', 'text', '', '', 10.02, 0, 0, NULL);
INSERT INTO ConfigurationValues VALUES (DEFAULT, 'PromoTransitionControls', '1', 'In-Portal', 'in-portal:configure_promo_blocks', 'la_Text_PromoSettings', 'la_config_PromoTransitionControls', 'select', '', '1=la_Enabled||0=la_Disabled', 10.03, 0, 0, NULL);
INSERT INTO ConfigurationValues VALUES (DEFAULT, 'PromoTransitionEffect', 'fade', 'In-Portal', 'in-portal:configure_promo_blocks', 'la_Text_PromoSettings', 'la_config_PromoTransitionEffect', 'select', '', 'fade=la_opt_AnimationFade||slide=la_opt_AnimationSlide', 10.04, 0, 0, NULL);
UPDATE Phrase
SET l<%PRIMARY_LANGUAGE%>_ColumnTranslation = l<%PRIMARY_LANGUAGE%>_Translation
WHERE PhraseKey IN ('LA_FLD_CATEGORY', 'LA_FLD_ORDER');
CREATE TABLE PageRevisions (
RevisionId int(11) NOT NULL AUTO_INCREMENT,
PageId int(11) NOT NULL,
RevisionNumber int(11) NOT NULL,
IsDraft tinyint(4) NOT NULL,
FromRevisionId int(11) NOT NULL,
CreatedById int(11) DEFAULT NULL,
CreatedOn int(11) DEFAULT NULL,
AutoSavedOn int(11) DEFAULT NULL,
`Status` tinyint(4) NOT NULL DEFAULT '2',
PRIMARY KEY (RevisionId),
KEY PageId (PageId),
KEY RevisionNumber (RevisionNumber),
KEY IsDraft (IsDraft),
KEY `Status` (`Status`)
);
ALTER TABLE Category
ADD LiveRevisionNumber INT NOT NULL DEFAULT '1' AFTER PageExpiration,
ADD INDEX (LiveRevisionNumber);
ALTER TABLE PageContent
ADD RevisionId INT NOT NULL AFTER PageId,
ADD INDEX (RevisionId);
ALTER TABLE PermissionConfig CHANGE PermissionName PermissionName VARCHAR(255) NOT NULL DEFAULT '';
INSERT INTO PermissionConfig VALUES (DEFAULT, 'CATEGORY.REVISION.ADD', 'la_PermName_Category.Revision.Add_desc', 'In-Portal', 1);
INSERT INTO PermissionConfig VALUES (DEFAULT, 'CATEGORY.REVISION.ADD.PENDING', 'la_PermName_Category.Revision.Add.Pending_desc', 'In-Portal', 1);
INSERT INTO PermissionConfig VALUES (DEFAULT, 'CATEGORY.REVISION.MODERATE', 'la_PermName_Category.Revision.Moderate_desc', 'In-Portal', 1);
INSERT INTO PermissionConfig VALUES (DEFAULT, 'CATEGORY.REVISION.HISTORY.VIEW', 'la_PermName_Category.Revision.History.View_desc', 'In-Portal', 1);
INSERT INTO PermissionConfig VALUES (DEFAULT, 'CATEGORY.REVISION.HISTORY.RESTORE', 'la_PermName_Category.Revision.History.Restore_desc', 'In-Portal', 1);
INSERT INTO Permissions VALUES(DEFAULT, 'CATEGORY.REVISION.ADD', 11, 1, 0, 1);
INSERT INTO Permissions VALUES(DEFAULT, 'CATEGORY.REVISION.HISTORY.VIEW', 11, 1, 0, 1);
INSERT INTO Permissions VALUES(DEFAULT, 'CATEGORY.REVISION.HISTORY.RESTORE', 11, 1, 0, 1);
ALTER TABLE EmailQueue ADD `LogData` TEXT;
UPDATE Permissions
SET Permission = REPLACE(Permission, 'agents', 'scheduled_tasks')
WHERE Permission LIKE 'in-portal:agents%';
DELETE FROM Phrase
WHERE PhraseKey IN (
'LA_TITLE_ADDINGAGENT', 'LA_TITLE_EDITINGAGENT', 'LA_TITLE_NEWAGENT', 'LA_TITLE_AGENTS', 'LA_TOOLTIP_NEWAGENT'
);
UPDATE Phrase
SET l<%PRIMARY_LANGUAGE%>_Translation = REPLACE(l<%PRIMARY_LANGUAGE%>_Translation, 'Agents', 'Scheduled Tasks')
WHERE PhraseKey IN (
'LA_USECRONFORREGULAREVENT', 'LA_HINT_SYSTEMTOOLSRESETPARSEDCACHEDDATA', 'LA_HINT_SYSTEMTOOLSRESETCONFIGSANDPARSEDDATA'
);
DELETE FROM PersistantSessionData
WHERE VariableName LIKE 'agent%';
RENAME TABLE <%TABLE_PREFIX%>Agents TO <%TABLE_PREFIX%>ScheduledTasks;
ALTER TABLE ScheduledTasks
CHANGE AgentId ScheduledTaskId INT(11) NOT NULL AUTO_INCREMENT,
CHANGE AgentName Name VARCHAR(255) NOT NULL DEFAULT '',
CHANGE AgentType `Type` TINYINT(3) UNSIGNED NOT NULL DEFAULT '1';
ALTER TABLE ScheduledTasks
DROP INDEX AgentType,
ADD INDEX `Type` (`Type`);
UPDATE ConfigurationValues
SET VariableName = 'RunScheduledTasksFromCron'
WHERE VariableName = 'UseCronForRegularEvent';
CREATE TABLE ItemFilters (
FilterId int(11) NOT NULL AUTO_INCREMENT,
ItemPrefix varchar(255) NOT NULL,
FilterField varchar(255) NOT NULL,
FilterType varchar(100) NOT NULL,
Enabled tinyint(4) NOT NULL DEFAULT '1',
RangeCount int(11) DEFAULT NULL,
PRIMARY KEY (FilterId),
KEY ItemPrefix (ItemPrefix),
KEY Enabled (Enabled)
);
UPDATE ConfigurationValues
SET HintLabel = CONCAT('hint:', Prompt)
WHERE VariableName IN ('ForceModRewriteUrlEnding', 'PerformExactSearch');
DELETE FROM Phrase
WHERE PhraseKey IN (
'LA_TEXT_PROMOSETTINGS', 'LA_CONFIG_PROMOROTATIONDELAY', 'LA_CONFIG_PROMOTRANSITIONTIME',
'LA_CONFIG_PROMOTRANSITIONCONTROLS', 'LA_CONFIG_PROMOTRANSITIONEFFECT'
);
DELETE FROM ConfigurationValues WHERE VariableName IN ('PromoRotationDelay', 'PromoTransitionTime', 'PromoTransitionControls', 'PromoTransitionEffect');
DELETE FROM Permissions WHERE Permission LIKE 'in-portal:promo_blocks.%';
CREATE TABLE PromoBlockGroups (
PromoBlockGroupId int(11) NOT NULL AUTO_INCREMENT,
Title varchar(255) NOT NULL DEFAULT '',
CreatedOn int(10) unsigned DEFAULT NULL,
`Status` tinyint(1) NOT NULL DEFAULT '1',
RotationDelay decimal(9,2) DEFAULT NULL,
TransitionTime decimal(9,2) DEFAULT NULL,
TransitionControls tinyint(1) NOT NULL DEFAULT '1',
TransitionEffect varchar(255) NOT NULL DEFAULT '',
TransitionEffectCustom varchar(255) NOT NULL DEFAULT '',
PRIMARY KEY (PromoBlockGroupId)
);
ALTER TABLE Category
ADD PromoBlockGroupId int(10) unsigned NOT NULL DEFAULT '0',
ADD INDEX (PromoBlockGroupId);
ALTER TABLE PromoBlocks
ADD PromoBlockGroupId int(10) unsigned NOT NULL DEFAULT '0',
ADD INDEX (PromoBlockGroupId);
INSERT INTO ConfigurationValues VALUES(DEFAULT, 'DebugOnlyPromoBlockGroupConfigurator', '1', 'In-Portal', 'in-portal:configure_advanced', 'la_section_SettingsAdmin', 'la_config_DebugOnlyPromoBlockGroupConfigurator', 'checkbox', '', '', 40.13, 0, 0, NULL);
UPDATE ConfigurationValues
SET DisplayOrder = DisplayOrder + 0.01
WHERE VariableName IN ('RememberLastAdminTemplate', 'UseHTTPAuth', 'HTTPAuthUsername', 'HTTPAuthPassword', 'HTTPAuthBypassIPs');
INSERT INTO PromoBlockGroups VALUES (DEFAULT, 'Default Group', UNIX_TIMESTAMP(), '1', '7.00', '0.60', '1', 'fade', '');
UPDATE PromoBlocks SET PromoBlockGroupId = 1;
INSERT INTO Permissions VALUES (DEFAULT, 'in-portal:promo_block_groups.view', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-portal:promo_block_groups.add', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-portal:promo_block_groups.edit', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-portal:promo_block_groups.delete', 11, 1, 1, 0);
INSERT INTO ConfigurationValues VALUES(DEFAULT, 'MaintenanceMessageFront', 'Website is currently undergoing the upgrades. Please come back shortly!', 'In-Portal', 'in-portal:configure_advanced', 'la_section_SettingsMaintenance', 'la_config_MaintenanceMessageFront', 'textarea', '', 'style="width: 100%; height: 100px;"', '15.01', 0, 0, 'hint:la_config_MaintenanceMessageFront');
INSERT INTO ConfigurationValues VALUES(DEFAULT, 'MaintenanceMessageAdmin', 'Website is currently undergoing the upgrades. Please come back shortly!', 'In-Portal', 'in-portal:configure_advanced', 'la_section_SettingsMaintenance', 'la_config_MaintenanceMessageAdmin', 'textarea', '', 'style="width: 100%; height: 100px;"', '15.02', 0, 0, 'hint:la_config_MaintenanceMessageAdmin');
INSERT INTO ConfigurationValues VALUES(DEFAULT, 'SoftMaintenanceTemplate', 'maintenance', 'In-Portal', 'in-portal:configure_advanced', 'la_section_SettingsMaintenance', 'la_config_SoftMaintenanceTemplate', 'text', '', 'style="width: 200px;"', '15.03', 0, 0, 'hint:la_config_SoftMaintenanceTemplate');
INSERT INTO ConfigurationValues VALUES(DEFAULT, 'HardMaintenanceTemplate', 'maintenance', 'In-Portal', 'in-portal:configure_advanced', 'la_section_SettingsMaintenance', 'la_config_HardMaintenanceTemplate', 'text', '', 'style="width: 200px;"', '15.04', 0, 0, 'hint:la_config_HardMaintenanceTemplate');
UPDATE ConfigurationValues
SET VariableName = 'DefaultEmailSender'
WHERE VariableName = 'Smtp_AdminMailFrom';
INSERT INTO ConfigurationValues VALUES(DEFAULT, 'DefaultEmailRecipients', '', 'In-Portal', 'in-portal:configure_advanced', 'la_section_SettingsMailling', 'la_config_DefaultEmailRecipients', 'text', NULL, NULL, 50.10, 0, 0, NULL);
ALTER TABLE SiteDomains ADD DefaultEmailRecipients TEXT NULL AFTER AdminEmail;
UPDATE ConfigurationValues
SET Section = 'in-portal:configure_advanced', Heading = 'la_section_Settings3rdPartyAPI', DisplayOrder = 80.01
WHERE VariableName = 'YahooApplicationId';
UPDATE ConfigurationValues
SET DisplayOrder = DisplayOrder - 0.01
WHERE VariableName IN ('Search_MinKeyword_Length', 'ExcludeTemplateSectionsFromSearch');
UPDATE Phrase
SET l<%PRIMARY_LANGUAGE%>_ColumnTranslation = l<%PRIMARY_LANGUAGE%>_Translation
WHERE PhraseKey IN ('LA_FLD_ADDRESSLINE1', 'LA_FLD_ADDRESSLINE2', 'LA_FLD_CITY', 'LA_FLD_COMPANY', 'LA_FLD_FAX', 'LA_FLD_STATE', 'LA_FLD_ZIP');
DELETE FROM Phrase
WHERE PhraseKey IN ('LA_TEXT_RESTRICTIONS', 'LA_USERS_REVIEW_DENY', 'LA_USERS_VOTES_DENY');
DELETE FROM ConfigurationValues
WHERE VariableName IN ('User_Review_Deny', 'User_Votes_Deny');
ALTER TABLE PortalUser ADD FrontLanguage INT(11) NULL AFTER PwRequestTime;
ALTER TABLE PortalUser DROP INDEX AdminLanguage;
UPDATE PortalUser
SET FrontLanguage = 1
WHERE UserType = 0;
ALTER TABLE PortalUser
ADD PrevEmails TEXT NULL AFTER Email,
ADD EmailVerified TINYINT NOT NULL AFTER `Status`;
UPDATE PortalUser SET EmailVerified = 1;
INSERT INTO Events (EventId, Event, ReplacementTags, Enabled, FrontEndOnly, Module, Description, Type, AllowChangingSender, AllowChangingRecipient) VALUES(DEFAULT, 'USER.EMAIL.CHANGE.VERIFY', NULL, 1, 0, 'Core', 'Changed E-mail Verification', 0, 1, 1);
INSERT INTO Events (EventId, Event, ReplacementTags, Enabled, FrontEndOnly, Module, Description, Type, AllowChangingSender, AllowChangingRecipient) VALUES(DEFAULT, 'USER.EMAIL.CHANGE.UNDO', NULL, 1, 0, 'Core', 'Changed E-mail Rollback', 0, 1, 1);
ALTER TABLE Category
ADD RequireSSL TINYINT NOT NULL DEFAULT '0',
ADD RequireLogin TINYINT NOT NULL DEFAULT '0';
INSERT INTO ConfigurationValues VALUES(DEFAULT, 'UpdateCountersOnFilterChange', '1', 'In-Portal', 'in-portal:configure_categories', 'la_title_General', 'la_config_UpdateCountersOnFilterChange', 'checkbox', '', '', 10.15, 0, 0, NULL);
# use new table name (see /core/install.php:390)!
ALTER TABLE UserSessions DROP `tz`;
ALTER TABLE UserSessions ADD `TimeZone` VARCHAR(255) NOT NULL AFTER `GroupList`;
ALTER TABLE PortalUser DROP `tz`;
ALTER TABLE PortalUser ADD `TimeZone` VARCHAR(255) NOT NULL AFTER `dob`;
UPDATE SearchConfig
SET FieldName = 'TimeZone'
WHERE FieldName = 'tz' AND TableName = 'PortalUser';
RENAME TABLE <%TABLE_PREFIX%>BanRules TO <%TABLE_PREFIX%>UserBanRules;
RENAME TABLE <%TABLE_PREFIX%>Cache TO <%TABLE_PREFIX%>SystemCache;
RENAME TABLE <%TABLE_PREFIX%>ConfigurationValues TO <%TABLE_PREFIX%>SystemSettings;
RENAME TABLE <%TABLE_PREFIX%>Category TO <%TABLE_PREFIX%>Categories;
UPDATE ItemTypes SET SourceTable = 'Categories' WHERE ItemType = 1;
UPDATE ItemTypes SET SourceTable = 'Users' WHERE ItemType = 6;
UPDATE SearchConfig SET TableName = 'Categories' WHERE TableName = 'Category';
UPDATE SearchConfig SET TableName = 'CustomFields' WHERE TableName = 'CustomField';
UPDATE SearchConfig SET TableName = 'Users' WHERE TableName = 'PortalUser';
UPDATE StatItem SET ValueSQL = REPLACE(ValueSQL, '<%prefix%>Category', '<%prefix%>Categories');
UPDATE StatItem SET ValueSQL = REPLACE(ValueSQL, '<%prefix%>ItemReview', '<%prefix%>CatalogReviews');
UPDATE StatItem SET ValueSQL = REPLACE(ValueSQL, '<%prefix%>Language', '<%prefix%>Languages');
UPDATE StatItem SET ValueSQL = REPLACE(ValueSQL, '<%prefix%>PortalGroup', '<%prefix%>UserGroups');
UPDATE StatItem SET ValueSQL = REPLACE(ValueSQL, '<%prefix%>PortalUser', '<%prefix%>Users');
UPDATE StatItem SET ValueSQL = REPLACE(ValueSQL, '<%prefix%>Theme', '<%prefix%>Themes');
UPDATE StatItem SET ValueSQL = REPLACE(ValueSQL, '<%prefix%>UserSession', '<%prefix%>UserSessions');
UPDATE SystemSettings SET ValueList = REPLACE(ValueList, '<PREFIX>CustomField', '<PREFIX>CustomFields');
UPDATE SystemSettings SET ValueList = REPLACE(ValueList, '<PREFIX>PortalGroup', '<PREFIX>UserGroups');
UPDATE Counters
SET CountQuery = 'SELECT COUNT(*) FROM <%PREFIX%>Users WHERE Status = 1', TablesAffected = '|Users|'
WHERE `Name` = 'members_count';
UPDATE Counters
SET
CountQuery = REPLACE(CountQuery, '<%PREFIX%>UserSession', '<%PREFIX%>UserSessions'),
TablesAffected = REPLACE(TablesAffected, '|UserSession|', '|UserSessions|');
RENAME TABLE <%TABLE_PREFIX%>CustomField TO <%TABLE_PREFIX%>CustomFields;
RENAME TABLE <%TABLE_PREFIX%>Drafts TO <%TABLE_PREFIX%>FormSubmissionReplyDrafts;
RENAME TABLE <%TABLE_PREFIX%>Events TO <%TABLE_PREFIX%>EmailEvents;
DELETE FROM PersistantSessionData WHERE VariableName LIKE '%custom_filter%';
RENAME TABLE <%TABLE_PREFIX%>Favorites TO <%TABLE_PREFIX%>UserFavorites;
RENAME TABLE <%TABLE_PREFIX%>Images TO <%TABLE_PREFIX%>CatalogImages;
RENAME TABLE <%TABLE_PREFIX%>ItemFiles TO <%TABLE_PREFIX%>CatalogFiles;
RENAME TABLE <%TABLE_PREFIX%>ItemRating TO <%TABLE_PREFIX%>CatalogRatings;
RENAME TABLE <%TABLE_PREFIX%>ItemReview TO <%TABLE_PREFIX%>CatalogReviews;
RENAME TABLE <%TABLE_PREFIX%>Language TO <%TABLE_PREFIX%>Languages;
RENAME TABLE <%TABLE_PREFIX%>PermCache TO <%TABLE_PREFIX%>CategoryPermissionsCache;
RENAME TABLE <%TABLE_PREFIX%>PermissionConfig TO <%TABLE_PREFIX%>CategoryPermissionsConfig;
RENAME TABLE <%TABLE_PREFIX%>Phrase TO <%TABLE_PREFIX%>LanguageLabels;
RENAME TABLE <%TABLE_PREFIX%>PortalGroup TO <%TABLE_PREFIX%>UserGroups;
RENAME TABLE <%TABLE_PREFIX%>PersistantSessionData TO <%TABLE_PREFIX%>UserPersistentSessionData;
RENAME TABLE <%TABLE_PREFIX%>PortalUser TO <%TABLE_PREFIX%>Users;
RENAME TABLE <%TABLE_PREFIX%>PortalUserCustomData TO <%TABLE_PREFIX%>UserCustomData;
RENAME TABLE <%TABLE_PREFIX%>RelatedSearches TO <%TABLE_PREFIX%>CategoryRelatedSearches;
RENAME TABLE <%TABLE_PREFIX%>Relationship TO <%TABLE_PREFIX%>CatalogRelationships;
RENAME TABLE <%TABLE_PREFIX%>SearchLog TO <%TABLE_PREFIX%>SearchLogs;
RENAME TABLE <%TABLE_PREFIX%>Skins TO <%TABLE_PREFIX%>AdminSkins;
RENAME TABLE <%TABLE_PREFIX%>SubmissionLog TO <%TABLE_PREFIX%>FormSubmissionReplies;
RENAME TABLE <%TABLE_PREFIX%>Theme TO <%TABLE_PREFIX%>Themes;
RENAME TABLE <%TABLE_PREFIX%>UserGroup TO <%TABLE_PREFIX%>UserGroupRelations;
RENAME TABLE <%TABLE_PREFIX%>Visits TO <%TABLE_PREFIX%>UserVisits;
RENAME TABLE <%TABLE_PREFIX%>SessionLogs TO <%TABLE_PREFIX%>UserSessionLogs;
DELETE FROM LanguageLabels WHERE PhraseKey = 'LA_FLD_RUNMODE';
ALTER TABLE ScheduledTasks DROP RunMode;
INSERT INTO SystemSettings VALUES(DEFAULT, 'CKFinderLicenseName', '', 'In-Portal', 'in-portal:configure_advanced', 'la_section_Settings3rdPartyAPI', 'la_config_CKFinderLicenseName', 'text', NULL, NULL, 80.03, 0, 0, NULL);
INSERT INTO SystemSettings VALUES(DEFAULT, 'CKFinderLicenseKey', '', 'In-Portal', 'in-portal:configure_advanced', 'la_section_Settings3rdPartyAPI', 'la_config_CKFinderLicenseKey', 'text', NULL, NULL, 80.04, 0, 0, NULL);
INSERT INTO SystemSettings VALUES(DEFAULT, 'EnablePageContentRevisionControl', '0', 'In-Portal', 'in-portal:configure_advanced', 'la_section_SettingsAdmin', 'la_config_EnablePageContentRevisionControl', 'checkbox', '', '', 40.19, 0, 0, NULL);
# ===== v 5.2.0-B2 =====
ALTER TABLE Users
CHANGE Username Username varchar(255) NOT NULL DEFAULT '',
CHANGE IPAddress IPAddress varchar(15) NOT NULL DEFAULT '',
CHANGE PwResetConfirm PwResetConfirm varchar(255) NOT NULL DEFAULT '';
ALTER TABLE UserSessions
CHANGE TimeZone TimeZone varchar(255) NOT NULL DEFAULT '';
ALTER TABLE CountryStates
CHANGE l1_Name l1_Name varchar(255) NOT NULL DEFAULT '',
CHANGE l2_Name l2_Name varchar(255) NOT NULL DEFAULT '',
CHANGE l3_Name l3_Name varchar(255) NOT NULL DEFAULT '',
CHANGE l4_Name l4_Name varchar(255) NOT NULL DEFAULT '',
CHANGE l5_Name l5_Name varchar(255) NOT NULL DEFAULT '';
ALTER TABLE Categories
CHANGE DirectLinkAuthKey DirectLinkAuthKey varchar(20) NOT NULL DEFAULT '';
ALTER TABLE ScheduledTasks
CHANGE SiteDomainLimitation SiteDomainLimitation varchar(255) NOT NULL DEFAULT '';
ALTER TABLE ItemFilters
CHANGE ItemPrefix ItemPrefix varchar(255) NOT NULL DEFAULT '',
CHANGE FilterField FilterField varchar(255) NOT NULL DEFAULT '',
CHANGE FilterType FilterType varchar(100) NOT NULL DEFAULT '';
ALTER TABLE SpamReports
CHANGE ItemPrefix ItemPrefix varchar(255) NOT NULL DEFAULT '';
ALTER TABLE CachedUrls
CHANGE ParsedVars ParsedVars text;
ALTER TABLE CurlLog
CHANGE Message Message varchar(255) NOT NULL DEFAULT '',
CHANGE PageUrl PageUrl varchar(255) NOT NULL DEFAULT '',
CHANGE RequestUrl RequestUrl varchar(255) NOT NULL DEFAULT '',
CHANGE CurlError CurlError varchar(255) NOT NULL DEFAULT '';
UPDATE SystemSettings
SET DisplayOrder = DisplayOrder + 0.01
WHERE ModuleOwner = 'In-Portal' AND Section = 'in-portal:configure_advanced' AND Heading = 'la_section_SettingsAdmin' AND DisplayOrder > 40.11;
INSERT INTO SystemSettings VALUES(DEFAULT, 'DefaultGridPerPage', '20', 'In-Portal', 'in-portal:configure_advanced', 'la_section_SettingsAdmin', 'la_config_DefaultGridPerPage', 'select', '', '10=+10||20=+20||50=+50||100=+100||500=+500', 40.12, 0, 0, NULL);
ALTER TABLE EmailEvents ADD LastChanged INT UNSIGNED NULL;
ALTER TABLE PromoBlocks
DROP Html,
CHANGE Status Status TINYINT(1) NOT NULL DEFAULT '1',
CHANGE CategoryId CategoryId INT(11) NULL;
# ===== v 5.2.0-B3 =====
ALTER TABLE Languages
ADD HtmlEmailTemplate TEXT NULL,
ADD TextEmailTemplate TEXT NULL;
ALTER TABLE EmailLog CHANGE fromuser `From` VARCHAR(255) NOT NULL DEFAULT '';
ALTER TABLE EmailLog CHANGE addressto `To` VARCHAR(255) NOT NULL DEFAULT '';
ALTER TABLE EmailLog CHANGE subject `Subject` VARCHAR(255) NOT NULL DEFAULT '';
ALTER TABLE EmailLog CHANGE `timestamp` SentOn INT(11) NULL;
ALTER TABLE EmailLog CHANGE `event` EventName VARCHAR(255) NOT NULL DEFAULT '';
ALTER TABLE EmailLog ADD OtherRecipients TEXT NULL AFTER `To`;
ALTER TABLE EmailLog
ADD HtmlBody LONGTEXT NULL AFTER `Subject`,
ADD TextBody LONGTEXT NULL AFTER HtmlBody;
ALTER TABLE EmailLog ADD AccessKey VARCHAR(32) NOT NULL DEFAULT '';
INSERT INTO Permissions VALUES (DEFAULT, 'in-portal:emaillog.edit', 11, 1, 1, 0);
DELETE FROM LanguageLabels WHERE PhraseKey = 'LA_PROMPT_FROMUSERNAME';
INSERT INTO SystemSettings VALUES(DEFAULT, 'EmailLogRotationInterval', '-1', 'In-Portal', 'in-portal:configure_advanced', 'la_section_SettingsMailling', 'la_config_EmailLogRotationInterval', 'select', NULL, '=la_opt_EmailLogKeepNever||86400=la_opt_OneDay||604800=la_opt_OneWeek||1209600=la_opt_TwoWeeks||2419200=la_opt_OneMonth||7257600=la_opt_ThreeMonths||29030400=la_opt_OneYear||-1=la_opt_EmailLogKeepForever', 50.11, 0, 0, 'hint:la_config_EmailLogRotationInterval');
INSERT INTO Permissions VALUES (DEFAULT, 'in-portal:spam_reports.view', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-portal:spam_reports.edit', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-portal:spam_reports.delete', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-portal:item_filters.view', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-portal:item_filters.add', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-portal:item_filters.edit', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-portal:item_filters.delete', 11, 1, 1, 0);
ALTER TABLE SlowSqlCapture CHANGE QueryCrc QueryCrc BIGINT(11) NOT NULL DEFAULT '0';
UPDATE SlowSqlCapture
SET QueryCrc = CAST((QueryCrc & 0xFFFFFFFF) AS UNSIGNED INTEGER)
WHERE QueryCrc < 0;
ALTER TABLE ImportCache CHANGE VarName VarName BIGINT(11) NOT NULL DEFAULT '0';
UPDATE ImportCache
SET VarName = CAST((VarName & 0xFFFFFFFF) AS UNSIGNED INTEGER)
WHERE VarName < 0;
ALTER TABLE PageContent CHANGE ContentNum ContentNum BIGINT(11) NOT NULL DEFAULT '0';
UPDATE PageContent
SET ContentNum = CAST((ContentNum & 0xFFFFFFFF) AS UNSIGNED INTEGER)
WHERE ContentNum < 0;
ALTER TABLE CachedUrls CHANGE Hash Hash BIGINT(11) NOT NULL DEFAULT '0';
UPDATE CachedUrls
SET Hash = CAST((Hash & 0xFFFFFFFF) AS UNSIGNED INTEGER)
WHERE Hash < 0;
ALTER TABLE EmailEvents ADD BindToSystemEvent VARCHAR(255) NOT NULL DEFAULT '';
CREATE TABLE SystemEventSubscriptions (
SubscriptionId int(11) NOT NULL AUTO_INCREMENT,
EmailEventId int(11) DEFAULT NULL,
SubscriberEmail varchar(255) NOT NULL DEFAULT '',
UserId int(11) DEFAULT NULL,
CategoryId int(11) DEFAULT NULL,
IncludeSublevels tinyint(4) NOT NULL DEFAULT '1',
ItemId int(11) DEFAULT NULL,
ParentItemId int(11) DEFAULT NULL,
SubscribedOn int(11) DEFAULT NULL,
PRIMARY KEY (SubscriptionId),
KEY EmailEventId (EmailEventId)
);
INSERT INTO Permissions VALUES (DEFAULT, 'in-portal:system_event_subscriptions.view', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-portal:system_event_subscriptions.add', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-portal:system_event_subscriptions.edit', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-portal:system_event_subscriptions.delete', 11, 1, 1, 0);
UPDATE LanguageLabels
SET
l1_ColumnTranslation = l1_Translation,
l2_ColumnTranslation = l2_Translation,
l3_ColumnTranslation = l3_Translation,
l4_ColumnTranslation = l4_Translation,
l5_ColumnTranslation = l5_Translation
WHERE PhraseKey IN ('LA_FLD_BINDTOSYSTEMEVENT', 'LA_FLD_CATEGORYID');
UPDATE Categories SET l1_MenuTitle = l1_Name WHERE l1_Name = 'Content';
UPDATE SystemSettings
SET ValueList = '0=la_opt_QueryString||1=la_opt_Cookies||2=la_opt_AutoDetect'
WHERE VariableName = 'CookieSessions';
# ===== v 5.2.0-RC1 =====
UPDATE LanguageLabels SET l<%PRIMARY_LANGUAGE%>_Translation = '&lt;TITLE&gt; Tag' WHERE PhraseKey = 'LA_FLD_PAGECONTENTTITLE';
ALTER TABLE EmailLog ADD EventType TINYINT(4) NULL AFTER EventName;
DELETE FROM UserPersistentSessionData WHERE VariableName IN ('email-log[Default]columns_.', 'promo-block[Default]columns_.');
ALTER TABLE Categories
ADD NamedParentPathHash INT UNSIGNED NOT NULL DEFAULT '0' AFTER NamedParentPath,
ADD CachedTemplateHash INT UNSIGNED NOT NULL DEFAULT '0' AFTER CachedTemplate,
ADD INDEX (NamedParentPathHash),
ADD INDEX (CachedTemplateHash);
# ===== v 5.2.0 =====
INSERT INTO SystemSettings VALUES(DEFAULT, 'CategoryPermissionRebuildMode', '3', 'In-Portal', 'in-portal:configure_categories', 'la_title_General', 'la_config_CategoryPermissionRebuildMode', 'select', NULL, '1=la_opt_Manual||2=la_opt_Silent||3=la_opt_Automatic', 10.11, 0, 0, 'hint:la_config_CategoryPermissionRebuildMode');
DELETE FROM LanguageLabels WHERE PhraseKey = 'LA_CONFIG_QUICKCATEGORYPERMISSIONREBUILD';
ALTER TABLE ScheduledTasks ADD RunSchedule VARCHAR(255) NOT NULL DEFAULT '* * * * *' AFTER Event;
DELETE FROM UserPersistentSessionData WHERE VariableName = 'scheduled-task[Default]columns_.';
DELETE FROM LanguageLabels WHERE PhraseKey = 'LA_FLD_RUNINTERVAL';
ALTER TABLE Languages
ADD ShortDateFormat VARCHAR(255) NOT NULL DEFAULT 'm/d' AFTER DateFormat,
ADD ShortTimeFormat VARCHAR(255) NOT NULL DEFAULT 'g:i A' AFTER TimeFormat;
UPDATE Languages
SET
ShortDateFormat = REPLACE(REPLACE(DateFormat, '/Y', ''), '/y', ''),
ShortTimeFormat = REPLACE(TimeFormat, ':s', '');
UPDATE SystemSettings
SET GroupDisplayOrder = 1
WHERE VariableName = 'AdminConsoleInterface';
UPDATE SystemSettings
SET Section = 'in-portal:configure_general', Prompt = 'la_config_AdminConsoleInterface', DisplayOrder = 50.01, GroupDisplayOrder = 2
WHERE VariableName = 'AllowAdminConsoleInterfaceChange';
DELETE FROM LanguageLabels WHERE PhraseKey = 'LA_CONFIG_ALLOWADMINCONSOLEINTERFACECHANGE';
UPDATE SystemSettings
SET DisplayOrder = DisplayOrder - 0.01
WHERE ModuleOwner = 'In-Portal' AND Section = 'in-portal:configure_advanced' AND DisplayOrder > 40.02 AND DisplayOrder < 50;
UPDATE SystemSettings
SET VariableValue = 1
WHERE VariableName = 'UseOutputCompression';
ALTER TABLE EmailQueue CHANGE LogData LogData LONGTEXT NULL DEFAULT NULL;
DELETE FROM UserPersistentSessionData WHERE VariableName = 'mailing-list[Default]columns_.';
INSERT INTO Permissions VALUES(DEFAULT, 'in-portal:configure_general.add', 11, 1, 1, 0);
INSERT INTO Permissions VALUES(DEFAULT, 'in-portal:configure_advanced.add', 11, 1, 1, 0);
INSERT INTO Permissions VALUES(DEFAULT, 'in-portal:configure_categories.add', 11, 1, 1, 0);
INSERT INTO Permissions VALUES(DEFAULT, 'in-portal:configure_users.add', 11, 1, 1, 0);
# ===== v 5.2.1-B1 =====
UPDATE SystemSettings
SET DisplayOrder = 30.05
WHERE VariableName = 'Force_HTTP_When_SSL_Not_Required';
INSERT INTO EmailEvents (EventId, Event, ReplacementTags, Enabled, FrontEndOnly, Module, Description, Type, AllowChangingSender, AllowChangingRecipient) VALUES(DEFAULT, 'USER.NEW.PASSWORD', NULL, 1, 0, 'Core', 'Sends new password to an existing user', 0, 1, 0);
INSERT INTO EmailEvents (EventId, Event, ReplacementTags, Enabled, FrontEndOnly, Module, Description, Type, AllowChangingSender, AllowChangingRecipient) VALUES(DEFAULT, 'USER.ADD.BYADMIN', NULL, 1, 0, 'Core', 'Sends password to a new user', 0, 1, 0);
CREATE TABLE SystemLog (
LogId int(11) NOT NULL AUTO_INCREMENT,
LogUniqueId int(11) DEFAULT NULL,
LogLevel tinyint(4) NOT NULL DEFAULT '7',
LogType tinyint(4) NOT NULL DEFAULT '3',
LogCode int(11) DEFAULT NULL,
LogMessage longtext,
LogTimestamp int(11) DEFAULT NULL,
LogDate datetime DEFAULT NULL,
LogEventName varchar(100) NOT NULL DEFAULT '',
LogHostname varchar(255) NOT NULL DEFAULT '',
LogRequestSource tinyint(4) DEFAULT NULL,
LogRequestURI varchar(255) NOT NULL DEFAULT '',
LogRequestData longtext,
LogUserId int(11) DEFAULT NULL,
LogInterface tinyint(4) DEFAULT NULL,
IpAddress varchar(15) NOT NULL DEFAULT '',
LogSessionKey int(11) DEFAULT NULL,
LogSessionData longtext,
LogBacktrace longtext,
LogSourceFilename varchar(255) NOT NULL DEFAULT '',
LogSourceFileLine int(11) DEFAULT NULL,
LogProcessId bigint(20) unsigned DEFAULT NULL,
LogMemoryUsed bigint(20) unsigned NOT NULL,
LogUserData longtext NOT NULL,
LogNotificationStatus tinyint(4) NOT NULL DEFAULT '0',
PRIMARY KEY (LogId),
KEY LogLevel (LogLevel),
KEY LogType (LogType),
KEY LogNotificationStatus (LogNotificationStatus)
);
INSERT INTO SystemSettings VALUES(DEFAULT, 'EnableEmailLog', '1', 'In-Portal', 'in-portal:configure_advanced', 'la_section_SettingsLogs', 'la_config_EnableEmailLog', 'radio', NULL, '1=la_Yes||0=la_No', 65.01, 0, 1, 'hint:la_config_EnableEmailLog');
UPDATE SystemSettings
SET DisplayOrder = 65.02, Heading = 'la_section_SettingsLogs', ValueList = '86400=la_opt_OneDay||604800=la_opt_OneWeek||1209600=la_opt_TwoWeeks||2419200=la_opt_OneMonth||7257600=la_opt_ThreeMonths||29030400=la_opt_OneYear||-1=la_opt_EmailLogKeepForever'
WHERE VariableName = 'EmailLogRotationInterval';
UPDATE LanguageLabels
SET
l<%PRIMARY_LANGUAGE%>_Translation = 'Keep "E-mail Log" for',
l<%PRIMARY_LANGUAGE%>_HintTranslation = 'This setting allows you to control for how long "E-mail Log" messages will be stored in the log and then automatically deleted. Use option "Forever" with caution since it will completely disable automatic log cleanup and can lead to large size of database table that stores e-mail messages.'
WHERE PhraseKey = 'LA_CONFIG_EMAILLOGROTATIONINTERVAL' AND l<%PRIMARY_LANGUAGE%>_Translation = 'Keep Email Log for';
DELETE FROM LanguageLabels WHERE PhraseKey = 'LA_OPT_EMAILLOGKEEPNEVER';
INSERT INTO SystemSettings VALUES(DEFAULT, 'SystemLogRotationInterval', '2419200', 'In-Portal', 'in-portal:configure_advanced', 'la_section_SettingsLogs', 'la_config_SystemLogRotationInterval', 'select', NULL, '86400=la_opt_OneDay||604800=la_opt_OneWeek||1209600=la_opt_TwoWeeks||2419200=la_opt_OneMonth||7257600=la_opt_ThreeMonths||29030400=la_opt_OneYear||-1=la_opt_SystemLogKeepForever', 65.03, 0, 1, 'hint:la_config_SystemLogRotationInterval');
INSERT INTO SystemSettings VALUES(DEFAULT, 'SystemLogNotificationEmail', '', 'In-Portal', 'in-portal:configure_advanced', 'la_section_SettingsLogs', 'la_config_SystemLogNotificationEmail', 'text', 'a:5:{s:4:"type";s:6:"string";s:9:"formatter";s:10:"kFormatter";s:6:"regexp";s:85:"/^([-a-zA-Z0-9!\\#$%&*+\\/=?^_`{|}~.]+@[a-zA-Z0-9]{1}[-.a-zA-Z0-9_]*\\.[a-zA-Z]{2,6})$/i";s:10:"error_msgs";a:1:{s:14:"invalid_format";s:18:"!la_invalid_email!";}s:7:"default";s:0:"";}', NULL, 65.04, 0, 1, 'hint:la_config_SystemLogNotificationEmail');
INSERT INTO EmailEvents (EventId, Event, ReplacementTags, Enabled, FrontEndOnly, Module, Description, Type, AllowChangingSender, AllowChangingRecipient) VALUES(DEFAULT, 'SYSTEM.LOG.NOTIFY', NULL, 1, 0, 'Core', 'Notification about message added to System Log', 1, 1, 1);
ALTER TABLE Users ADD PasswordHashingMethod TINYINT NOT NULL DEFAULT '3' AFTER Password;
UPDATE Users SET PasswordHashingMethod = 1;
INSERT INTO SystemSettings VALUES(DEFAULT, 'TypeKitId', '', 'In-Portal', 'in-portal:configure_advanced', 'la_section_Settings3rdPartyAPI', 'la_config_TypeKitId', 'text', NULL, NULL, 80.05, 0, 1, NULL);
ALTER TABLE MailingLists CHANGE EmailsQueued EmailsQueuedTotal INT(10) UNSIGNED NOT NULL DEFAULT '0';
RENAME TABLE <%TABLE_PREFIX%>EmailEvents TO <%TABLE_PREFIX%>EmailTemplates;
ALTER TABLE EmailTemplates CHANGE `Event` TemplateName VARCHAR(40) NOT NULL DEFAULT '';
ALTER TABLE EmailTemplates CHANGE EventId TemplateId INT(11) NOT NULL AUTO_INCREMENT;
ALTER TABLE SystemEventSubscriptions CHANGE EmailEventId EmailTemplateId INT(11) NULL DEFAULT NULL;
DELETE FROM LanguageLabels WHERE PhraseKey IN (
'LA_FLD_EXPORTEMAILEVENTS', 'LA_FLD_EVENT', 'LA_TITLE_EMAILMESSAGES', 'LA_TAB_E-MAILS', 'LA_COL_EMAILEVENTS',
'LA_OPT_EMAILEVENTS', 'LA_FLD_EMAILEVENT', 'LA_TITLE_EMAILEVENTS', 'LA_TITLE_ADDING_E-MAIL', 'LA_TITLE_EDITING_E-MAIL',
'LA_TITLE_EDITINGEMAILEVENT', 'LA_TITLE_NEWEMAILEVENT', 'LA_TAB_EMAILEVENTS'
);
DELETE FROM UserPersistentSessionData WHERE VariableName IN ('system-event-subscription[Default]columns_.', 'email-log[Default]columns_.');
ALTER TABLE EmailLog CHANGE EventName TemplateName VARCHAR(255) NOT NULL DEFAULT '';
# ===== v 5.2.1-B2 =====
DELETE FROM LanguageLabels WHERE PhraseKey = 'LA_TAB_REPORTS';
ALTER TABLE Modules ADD ClassNamespace VARCHAR(255) NOT NULL DEFAULT '' AFTER Path;
UPDATE Modules
SET ClassNamespace = 'Intechnic\\InPortal\\Core'
WHERE `Name` IN ('Core', 'In-Portal');
UPDATE SystemSettings
SET DisplayOrder = DisplayOrder + 0.01
WHERE ModuleOwner = 'In-Portal' AND Section = 'in-portal:configure_categories' AND DisplayOrder > 10.10 AND DisplayOrder < 20;
INSERT INTO SystemSettings VALUES(DEFAULT, 'CheckViewPermissionsInCatalog', '1', 'In-Portal', 'in-portal:configure_categories', 'la_title_General', 'la_config_CheckViewPermissionsInCatalog', 'radio', NULL, '1=la_Yes||0=la_No', 10.11, 0, 1, 'hint:la_config_CheckViewPermissionsInCatalog');
# ===== v 5.2.1-RC1 =====
UPDATE LanguageLabels
SET l1_Translation = REPLACE(l1_Translation, '<br />', '\n')
WHERE PhraseKey = 'LA_EDITINGINPROGRESS';
UPDATE LanguageLabels
SET l1_ColumnTranslation = 'Helpful'
WHERE PhraseKey = 'LA_FLD_HELPFULCOUNT';
UPDATE LanguageLabels
SET l1_ColumnTranslation = 'Not Helpful'
WHERE PhraseKey = 'LA_FLD_NOTHELPFULCOUNT';
UPDATE LanguageLabels
SET Module = 'Core'
WHERE PhraseKey = 'LA_SECTION_FILE';
# ===== v 5.2.1 =====
# ===== v 5.2.2-B1 =====
UPDATE LanguageLabels
SET l1_Translation = 'Incorrect data format, please use {type}'
WHERE PhraseKey = 'LA_ERR_BAD_TYPE';
UPDATE LanguageLabels
SET l1_Translation = 'Field value is out of range, possible values from {min_value} to {max_value}'
WHERE PhraseKey = 'LA_ERR_VALUE_OUT_OF_RANGE';
UPDATE LanguageLabels
SET l1_Translation = 'Field value length is out of range, possible value length from {min_length} to {max_length}'
WHERE PhraseKey = 'LA_ERR_LENGTH_OUT_OF_RANGE';
ALTER TABLE Themes ADD StylesheetFile VARCHAR( 255 ) NOT NULL DEFAULT '';
UPDATE Themes SET StylesheetFile = 'platform/inc/styles.css' WHERE `Name` = 'advanced';
UPDATE EmailTemplates
SET l1_Subject = REPLACE(l1_Subject, "Field name='Username'", 'UserTitle'), l1_HtmlBody = REPLACE(l1_HtmlBody, "Field name='Username'", 'UserTitle')
WHERE TemplateName LIKE 'USER%';
UPDATE EmailTemplates
SET l1_Subject = REPLACE(l1_Subject, 'Field name="Username"', 'UserTitle'), l1_HtmlBody = REPLACE(l1_HtmlBody, 'Field name="Username"', 'UserTitle')
WHERE TemplateName LIKE 'USER%';
UPDATE SystemSettings SET VariableValue = 1 WHERE VariableName = 'CSVExportEncoding';
ALTER TABLE Semaphores ADD MainIDs INT NULL DEFAULT NULL AFTER MainPrefix;
# ===== v 5.2.2-B2 =====
UPDATE Modules
SET ClassNamespace = 'InPortal\\Core'
WHERE `Name` IN ('Core', 'In-Portal');
DELETE FROM CachedUrls;
UPDATE LanguageLabels
SET l1_Translation = 'Incorrect date format, please use ({format}) ex. ({sample})'
WHERE PhraseKey = 'LA_ERR_BAD_DATE_FORMAT';
UPDATE LanguageLabels
SET l1_HintTranslation = REPLACE(l1_HintTranslation, '<li>This deploy script will reset all caches at once</li>', '<li>This deploy script will reset all caches at once.</li>\r\n<li>This deploy script will dump production assets.</li>\r\n')
WHERE PhraseKey = 'LA_TITLE_SYSTEMTOOLSDEPLOY';
INSERT INTO SystemSettings VALUES(DEFAULT, 'EmailDelivery', '2', 'In-Portal', 'in-portal:configure_advanced', 'la_section_SettingsMailling', 'la_config_EmailDelivery', 'radio', NULL, '1=la_opt_EmailDeliveryQueue||2=la_opt_EmailDeliveryImmediate', 50.11, 0, 1, NULL);
# ===== v 5.2.2-B3 =====
INSERT INTO SearchConfig VALUES ('Categories', 'PageContent', 1, 1, 'lu_fielddesc_category_PageContent', 'lc_field_PageContent', 'In-Portal', 'la_text_category', 22, DEFAULT, 1, 'text', 'MULTI:PageRevisions.PageContent', '{ForeignTable}.PageId = {LocalTable}.CategoryId AND {ForeignTable}.RevisionNumber = {LocalTable}.LiveRevisionNumber', NULL, NULL, NULL, NULL, NULL);
ALTER TABLE Semaphores CHANGE MainIDs MainIDs TEXT NULL;
ALTER TABLE Users ADD KEY Email (Email);
INSERT INTO SystemSettings VALUES(DEFAULT, 'SystemLogCodeFragmentPathFilterRegExp', '#(modules/custom|system/cache/modules/custom)/.*#', 'In-Portal', 'in-portal:configure_advanced', 'la_section_SettingsLogs', 'la_config_SystemLogCodeFragmentPathFilterRegExp', 'text', NULL, NULL, 65.05, 0, 1, NULL);
ALTER TABLE SystemLog
ADD COLUMN `LogCodeFragment` longtext NULL AFTER `LogSourceFileLine`,
ADD COLUMN `LogCodeFragmentsRotated` tinyint(4) NOT NULL DEFAULT '0' AFTER `LogCodeFragment`;
ALTER TABLE SystemLog ADD INDEX `TIMESTAMP_CODE_FRAGMENTS_ROTATED` (`LogTimestamp`,`LogCodeFragmentsRotated`) USING BTREE;
ALTER TABLE Semaphores
ADD COLUMN `UserId` int(11) NULL,
ADD COLUMN `IpAddress` varchar(15) NOT NULL DEFAULT '',
ADD COLUMN `Hostname` varchar(255) NOT NULL DEFAULT '',
ADD COLUMN `RequestURI` varchar(255) NOT NULL DEFAULT '',
ADD COLUMN `Backtrace` longtext NULL;
INSERT INTO SystemSettings VALUES(DEFAULT, 'SemaphoreLifetimeInSeconds', '300', 'In-Portal', 'in-portal:configure_advanced', 'la_section_SettingsSystem', 'la_config_SemaphoreLifetimeInSeconds', 'text', '', 'style=\"width: 50px;\"', 60.1, 0, 1, 'hint:la_config_SemaphoreLifetimeInSeconds');
CREATE TABLE ExportUserPresets (
PortalUserId int NOT NULL DEFAULT 0,
ItemPrefix varchar(100) NOT NULL DEFAULT '',
PresetName varchar(100) NOT NULL DEFAULT '',
PresetData text NULL DEFAULT NULL,
PRIMARY KEY (PortalUserId, ItemPrefix, PresetName)
);
+
+ALTER TABLE Semaphores CHANGE `SessionKey` `SessionKey` char(64) NOT NULL DEFAULT '';
+ALTER TABLE UserSessionLogs ADD COLUMN `SessionKey` char(64) NOT NULL DEFAULT '' AFTER `SessionId`;
+UPDATE UserSessionLogs SET SessionKey = SessionId;
+ALTER TABLE CurlLog CHANGE `SessionKey` `SessionKey` char(64) NOT NULL DEFAULT '';
+ALTER TABLE SystemLog CHANGE `LogSessionKey` `LogSessionKey` char(64) NOT NULL DEFAULT '';
Index: branches/5.2.x/core/install.php
===================================================================
--- branches/5.2.x/core/install.php (revision 16796)
+++ branches/5.2.x/core/install.php (revision 16797)
@@ -1,1818 +1,1841 @@
<?php
/**
* @version $Id$
* @package In-Portal
* @copyright Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license GNU/GPL
* In-Portal is Open Source software.
* This means that this software may have been modified pursuant
* the GNU General Public License, and as distributed it includes
* or is derivative of works licensed under the GNU General Public License
* or other free or open source software licenses.
* See http://www.in-portal.org/license for copyright notices and details.
*/
ini_set('display_errors', 1);
error_reporting(E_ALL & ~E_STRICT);
define('IS_INSTALL', 1);
define('ADMIN', 1);
define('FULL_PATH', realpath(dirname(__FILE__).'/..') );
define('REL_PATH', '/core');
// run installator
$install_engine = new kInstallator();
$install_engine->Init();
$install_engine->Run();
$install_engine->Done();
class kInstallator {
/**
* Reference to kApplication class object
*
* @var kApplication
*/
var $Application = null;
/**
* Connection to database
*
* @var IDBConnection
*/
var $Conn = null;
/**
* XML file containing steps information
*
* @var string
*/
var $StepDBFile = '';
/**
* Step name, that currently being processed
*
* @var string
*/
var $currentStep = '';
/**
* Steps list (preset) to use for current installation
*
* @var string
*/
var $stepsPreset = '';
/**
* Installation steps to be done
*
* @var Array
*/
var $steps = Array (
'fresh_install' => Array ('sys_requirements', 'check_paths', 'db_config', 'select_license', /*'download_license',*/ 'select_domain', 'root_password', 'choose_modules', 'post_config', 'sys_config', 'select_theme', 'security', 'finish'),
'clean_reinstall' => Array ('install_setup', 'sys_requirements', 'check_paths', 'clean_db', 'db_config', 'select_license', /*'download_license',*/ 'select_domain', 'root_password', 'choose_modules', 'post_config', 'sys_config', 'select_theme', 'security', 'finish'),
'already_installed' => Array ('check_paths', 'install_setup'),
'upgrade' => Array ('check_paths', 'install_setup', 'sys_config', 'upgrade_modules', 'skin_upgrade', 'security', 'finish'),
'update_license' => Array ('check_paths', 'install_setup', 'select_license', /*'download_license',*/ 'select_domain', 'security', 'finish'),
'update_config' => Array ('check_paths', 'install_setup', 'sys_config', 'security', 'finish'),
'db_reconfig' => Array ('check_paths', 'install_setup', 'db_reconfig', 'security', 'finish'),
'sys_requirements' => Array ('check_paths', 'install_setup', 'sys_requirements', 'security', 'finish')
);
/**
* Steps, that doesn't required admin to be logged-in to proceed
*
* @var Array
*/
var $skipLoginSteps = Array ('sys_requirements', 'check_paths', 'select_license', /*'download_license',*/ 'select_domain', 'root_password', 'choose_modules', 'post_config', 'select_theme', 'security', 'finish', -1);
/**
* Steps, on which kApplication should not be initialized, because of missing correct db table structure
*
* @var Array
*/
var $skipApplicationSteps = Array ('sys_requirements', 'check_paths', 'clean_db', 'db_config', 'db_reconfig' /*, 'install_setup'*/); // remove install_setup when application will work separately from install
/**
* Folders that should be writeable to continue installation. $1 - main writeable folder from config.php ("/system" by default)
*
* @var Array
*/
var $writeableFolders = Array (
'$1',
'$1/.restricted',
'$1/images',
'$1/images/pending',
'$1/images/emoticons', // for "In-Bulletin"
'$1/user_files',
'$1/cache',
);
/**
* Contains last error message text
*
* @var string
*/
var $errorMessage = '';
/**
* Base path for includes in templates
*
* @var string
*/
var $baseURL = '';
/**
* Holds number of last executed query in the SQL
*
* @var int
*/
var $LastQueryNum = 0;
/**
* Dependencies, that should be used in upgrade process
*
* @var Array
*/
var $upgradeDepencies = Array ();
/**
* Log of upgrade - list of upgraded modules and their versions
*
* @var Array
*/
var $upgradeLog = Array ();
/**
* Common tools required for installation process
*
* @var kInstallToolkit
*/
var $toolkit = null;
function Init()
{
include_once(FULL_PATH . REL_PATH . '/kernel/kbase.php'); // required by kDBConnection class
include_once(FULL_PATH . REL_PATH . '/kernel/utility/multibyte.php'); // emulating multi-byte php extension
include_once(FULL_PATH . REL_PATH . '/kernel/utility/system_config.php');
require_once(FULL_PATH . REL_PATH . '/install/install_toolkit.php'); // toolkit required for module installations to installator
$this->toolkit = new kInstallToolkit();
$this->toolkit->setInstallator($this);
$this->StepDBFile = FULL_PATH.'/'.REL_PATH.'/install/steps_db.xml';
$https_mark = isset($_SERVER['HTTPS']) ? $_SERVER['HTTPS'] : false;
$protocol = ($https_mark == 'on') || ($https_mark == '1') ? 'https://' : 'http://';
$this->baseURL = $protocol . $_SERVER['HTTP_HOST'] . $this->toolkit->systemConfig->get('WebsitePath', 'Misc') . '/core/install/';
set_error_handler( Array(&$this, 'ErrorHandler') );
if ( $this->toolkit->systemConfigFound() ) {
// if config.php found, then check his write permission too
$this->writeableFolders[] = $this->toolkit->systemConfig->get('WriteablePath', 'Misc') . '/config.php';
}
$this->currentStep = $this->GetVar('step');
// can't check login on steps where no application present anyways :)
$this->skipLoginSteps = array_unique(array_merge($this->skipLoginSteps, $this->skipApplicationSteps));
$this->SelectPreset();
if (!$this->currentStep) {
$this->SetFirstStep(); // sets first step of current preset
}
$this->InitStep();
}
function SetFirstStep()
{
reset($this->steps[$this->stepsPreset]);
$this->currentStep = current($this->steps[$this->stepsPreset]);
}
/**
* Selects preset to proceed based on various criteria
*
*/
function SelectPreset()
{
$preset = $this->GetVar('preset');
if ($this->toolkit->systemConfigFound()) {
// only at installation first step
$status = $this->CheckDatabase(false);
if ($status && $this->AlreadyInstalled()) {
// if already installed, then all future actions need login to work
$this->skipLoginSteps = Array ('check_paths', -1);
if (!$preset) {
$preset = 'already_installed';
$this->currentStep = '';
}
}
}
if ($preset === false) {
$preset = 'fresh_install'; // default preset
}
$this->stepsPreset = $preset;
}
/**
* Returns variable from request
*
* @param string $name
* @param mixed $default
* @return string|bool
* @access private
*/
private function GetVar($name, $default = false)
{
if ( array_key_exists($name, $_COOKIE) ) {
return $_COOKIE[$name];
}
if ( array_key_exists($name, $_POST) ) {
return $_POST[$name];
}
return array_key_exists($name, $_GET) ? $_GET[$name] : $default;
}
/**
* Sets new value for request variable
*
* @param string $name
* @param mixed $value
* @return void
* @access private
*/
private function SetVar($name, $value)
{
$_POST[$name] = $value;
}
/**
* Performs needed intialization of data, that step requires
*
*/
function InitStep()
{
$require_login = !in_array($this->currentStep, $this->skipLoginSteps);
$this->InitApplication($require_login);
if ($require_login) {
// step require login to proceed
if (!$this->Application->LoggedIn()) {
$this->stepsPreset = 'already_installed';
$this->currentStep = 'install_setup'; // manually set 2nd step, because 'check_paths' step doesn't contain login form
// $this->SetFirstStep();
}
}
switch ($this->currentStep) {
case 'sys_requirements':
$required_checks = Array (
'php_version', 'composer', 'curl', 'simplexml', 'freetype', 'gd_version',
'jpeg', 'mysql', 'json', 'openssl', 'date.timezone', 'output_buffering',
);
$check_results = $this->toolkit->CallPrerequisitesMethod('core/', 'CheckSystemRequirements');
$required_checks = array_diff($required_checks, array_keys( array_filter($check_results) ));
if ( $required_checks ) {
// php-based checks failed - show error
$this->errorMessage = '<br/>Installation can not continue until all required environment parameters are set correctly';
}
elseif ( $this->GetVar('js_enabled') === false ) {
// can't check JS without form submit - set some fake error, so user stays on this step
$this->errorMessage = '&nbsp;';
}
elseif ( !$this->GetVar('js_enabled') || !$this->GetVar('cookies_enabled') ) {
// js/cookies disabled
$this->errorMessage = '<br/>Installation can not continue until all required environment parameters are set correctly';
}
break;
case 'check_paths':
$writeable_base = $this->toolkit->systemConfig->get('WriteablePath', 'Misc');
foreach ($this->writeableFolders as $folder_path) {
$file_path = FULL_PATH . str_replace('$1', $writeable_base, $folder_path);
if (file_exists($file_path) && !is_writable($file_path)) {
$this->errorMessage = '<br/>Installation can not continue until all required permissions are set correctly';
break;
}
}
if ( !$this->errorMessage && $this->toolkit->systemConfig->get('DBType', 'Database') == 'mysql' ) {
$this->toolkit->systemConfig->set('DBType', 'Database', 'mysqli');
$this->toolkit->systemConfig->save();
}
break;
case 'clean_db':
// don't use Application, because all tables will be erased and it will crash
$sql = 'SELECT Path
FROM ' . TABLE_PREFIX . 'Modules';
$modules = $this->Conn->GetCol($sql);
foreach ($modules as $module_folder) {
$remove_file = '/' . $module_folder . 'install/remove_schema.sql';
if (file_exists(FULL_PATH . $remove_file)) {
$this->toolkit->RunSQL($remove_file);
}
}
$this->toolkit->deleteEditTables();
$this->currentStep = $this->GetNextStep();
break;
case 'db_config':
case 'db_reconfig':
$fields = Array (
'DBType', 'DBHost', 'DBName', 'DBUser',
'DBUserPassword', 'DBCollation', 'TablePrefix'
);
// set fields
foreach ($fields as $field_name) {
$submit_value = $this->GetVar($field_name);
if ($submit_value !== false) {
$this->toolkit->systemConfig->set($field_name, 'Database', $submit_value);
}
/*else {
$this->toolkit->systemConfig->set($field_name, 'Database', '');
}*/
}
break;
case 'download_license':
$license_source = $this->GetVar('license_source');
if ($license_source !== false && $license_source != 1) {
// previous step was "Select License" and not "Download from Intechnic" option was selected
$this->currentStep = $this->GetNextStep();
}
break;
case 'choose_modules':
// if no modules found, then proceed to next step
$modules = $this->ScanModules();
if (!$modules) {
$this->currentStep = $this->GetNextStep();
}
break;
case 'select_theme':
// put available theme list in database
$this->toolkit->rebuildThemes();
break;
case 'upgrade_modules':
// get installed modules from db and compare their versions to upgrade script
$modules = $this->GetUpgradableModules();
if (!$modules) {
$this->currentStep = $this->GetNextStep();
}
break;
case 'skin_upgrade':
if ($this->Application->RecallVar('SkinUpgradeLog') === false) {
// no errors during skin upgrade -> skip this step
$this->currentStep = $this->GetNextStep();
}
break;
case 'install_setup':
if ( $this->Application->TableFound(TABLE_PREFIX . 'UserSession', true) ) {
// update to 5.2.0 -> rename session table before using it
// don't rename any other table here, since their names could be used in upgrade script
$this->Conn->Query('RENAME TABLE ' . TABLE_PREFIX . 'UserSession TO ' . TABLE_PREFIX . 'UserSessions');
$this->Conn->Query('RENAME TABLE ' . TABLE_PREFIX . 'SessionData TO ' . TABLE_PREFIX . 'UserSessionData');
}
+ $sessions_table_structure = $this->Conn->Query('DESCRIBE ' . TABLE_PREFIX . 'UserSessions', 'Field');
+
+ if ( !array_key_exists('SessionId', $sessions_table_structure) ) {
+ // Update to 5.2.2-B3 -> add missing columns before creating sessions.
+ $this->Conn->Query('ALTER TABLE ' . TABLE_PREFIX . 'UserSessions DROP INDEX `PRIMARY`');
+ $this->Conn->Query(
+ 'ALTER TABLE ' . TABLE_PREFIX . 'UserSessions
+ ADD `SessionId` int NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST'
+ );
+ $this->Conn->Query(
+ 'ALTER TABLE ' . TABLE_PREFIX . 'UserSessions
+ CHANGE `SessionKey` `SessionKey` char(64) NOT NULL DEFAULT ""'
+ );
+ $this->Conn->Query(
+ 'ALTER TABLE ' . TABLE_PREFIX . 'UserSessions
+ ADD UNIQUE INDEX `SessionKey` (`SessionKey`) USING BTREE'
+ );
+ $this->Conn->Query(
+ 'ALTER TABLE ' . TABLE_PREFIX . 'UserSessionData
+ CHANGE `SessionKey` `SessionId` int unsigned NOT NULL DEFAULT "0"'
+ );
+ }
+
$next_preset = $this->Application->GetVar('next_preset');
if ($next_preset !== false) {
/** @var UserHelper $user_helper */
$user_helper = $this->Application->recallObject('UserHelper');
$username = $this->Application->GetVar('login');
$password = $this->Application->GetVar('password');
if ($username == 'root') {
// verify "root" user using configuration settings
$login_result = $user_helper->loginUser($username, $password);
if ($login_result != LoginResult::OK) {
$error_phrase = $login_result == LoginResult::NO_PERMISSION ? 'la_no_permissions' : 'la_invalid_password';
$this->errorMessage = $this->Application->Phrase($error_phrase) . '. If you don\'t know your username or password, contact Intechnic Support';
}
}
else {
// non "root" user -> verify using licensing server
$url_params = Array (
'login' => md5($username),
'password' => md5($password),
'action' => 'check',
'license_code' => base64_encode( $this->toolkit->systemConfig->get('LicenseCode', 'Intechnic') ),
'version' => '4.3.0',//$this->toolkit->GetMaxModuleVersion('core/'),
'domain' => base64_encode($_SERVER['HTTP_HOST']),
);
/** @var kCurlHelper $curl_helper */
$curl_helper = $this->Application->recallObject('CurlHelper');
$curl_helper->SetRequestData($url_params);
$file_data = $curl_helper->Send(GET_LICENSE_URL);
if ( !$curl_helper->isGoodResponseCode() ) {
$this->errorMessage = 'In-Portal servers temporarily unavailable. Please contact <a href="mailto:support@in-portal.com">In-Portal support</a> personnel directly.';
}
elseif (substr($file_data, 0, 5) == 'Error') {
$this->errorMessage = substr($file_data, 6) . ' If you don\'t know your username or password, contact Intechnic Support';
}
if ($this->errorMessage == '') {
$user_helper->loginUserById(USER_ROOT);
}
}
if ($this->errorMessage == '') {
// processed with redirect to selected step preset
if (!isset($this->steps[$next_preset])) {
$this->errorMessage = 'Preset "'.$next_preset.'" not yet implemented';
}
else {
$this->stepsPreset = $next_preset;
}
}
}
else {
// if preset was not choosen, then raise error
$this->errorMessage = 'Please select action to perform';
}
break;
case 'security':
// perform write check
if ($this->Application->GetVar('skip_security_check')) {
// administrator intensionally skips security checks
break;
}
$write_check = true;
$check_paths = Array ('/', '/index.php', $this->toolkit->systemConfig->get('WriteablePath', 'Misc') . '/config.php', ADMIN_DIRECTORY . '/index.php');
foreach ($check_paths as $check_path) {
$path_check_status = $this->toolkit->checkWritePermissions(FULL_PATH . $check_path);
if (is_bool($path_check_status) && $path_check_status) {
$write_check = false;
break;
}
}
// script execute check
if (file_exists(WRITEABLE . '/install_check.php')) {
unlink(WRITEABLE . '/install_check.php');
}
$fp = fopen(WRITEABLE . '/install_check.php', 'w');
fwrite($fp, "<?php\n\techo 'OK';\n");
fclose($fp);
/** @var kCurlHelper $curl_helper */
$curl_helper = $this->Application->recallObject('CurlHelper');
$output = $curl_helper->Send($this->Application->BaseURL(WRITEBALE_BASE) . 'install_check.php');
unlink(WRITEABLE . '/install_check.php');
$execute_check = ($output !== 'OK');
$directive_check = true;
$ini_vars = Array ('register_globals' => false, 'open_basedir' => true, 'allow_url_fopen' => false);
foreach ($ini_vars as $var_name => $var_value) {
$current_value = ini_get($var_name);
if (($var_value && !$current_value) || (!$var_value && $current_value)) {
$directive_check = false;
break;
}
}
if (!$write_check || !$execute_check || !$directive_check) {
$this->errorMessage = true;
}
/*else {
$this->currentStep = $this->GetNextStep();
}*/
break;
}
$this->PerformValidation(); // returns validation status (just in case)
}
/**
* Validates data entered by user
*
* @return bool
*/
function PerformValidation()
{
if ($this->GetVar('step') != $this->currentStep) {
// just redirect from previous step, don't validate
return true;
}
$status = true;
switch ($this->currentStep) {
case 'db_config':
case 'db_reconfig':
// 1. check if required fields are filled
$section_name = 'Database';
$required_fields = Array ('DBType', 'DBHost', 'DBName', 'DBUser', 'DBCollation');
foreach ($required_fields as $required_field) {
if (!$this->toolkit->systemConfig->get($required_field, $section_name)) {
$status = false;
$this->errorMessage = 'Please fill all required fields';
break;
}
}
if ( !$status ) {
break;
}
// 2. check permissions, that use have in this database
$status = $this->CheckDatabase(($this->currentStep == 'db_config') && !$this->GetVar('UseExistingSetup'));
break;
case 'select_license':
$license_source = $this->GetVar('license_source');
if ($license_source == 2) {
// license from file -> file must be uploaded
$upload_error = $_FILES['license_file']['error'];
if ($upload_error != UPLOAD_ERR_OK) {
$this->errorMessage = 'Missing License File';
}
}
elseif (!is_numeric($license_source)) {
$this->errorMessage = 'Please select license';
}
$status = $this->errorMessage == '';
break;
case 'root_password':
// check, that password & verify password match
$password = $this->Application->GetVar('root_password');
$password_verify = $this->Application->GetVar('root_password_verify');
if ($password != $password_verify) {
$this->errorMessage = 'Passwords does not match';
}
elseif (mb_strlen($password) < 4) {
$this->errorMessage = 'Root Password must be at least 4 characters';
}
$status = $this->errorMessage == '';
break;
case 'choose_modules':
break;
case 'upgrade_modules':
$modules = $this->Application->GetVar('modules');
if (!$modules) {
$modules = Array ();
$this->errorMessage = 'Please select module(-s) to ' . ($this->currentStep == 'choose_modules' ? 'install' : 'upgrade');
}
// check interface module
$upgrade_data = $this->GetUpgradableModules();
if (array_key_exists('core', $upgrade_data) && !in_array('core', $modules)) {
// core can be upgraded, but isn't selected
$this->errorMessage = 'Please select "Core" as interface module';
}
$status = $this->errorMessage == '';
break;
}
return $status;
}
/**
* Perform installation step actions
*
*/
function Run()
{
if ($this->errorMessage) {
// was error during data validation stage
return ;
}
switch ($this->currentStep) {
case 'check_paths':
$this->generateSecurityKeys();
break;
case 'db_config':
case 'db_reconfig':
// store db configuration
$sql = 'SHOW COLLATION
LIKE \''.$this->toolkit->systemConfig->get('DBCollation', 'Database').'\'';
$collation_info = $this->Conn->Query($sql);
if ($collation_info) {
$this->toolkit->systemConfig->set('DBCharset', 'Database', $collation_info[0]['Charset']);
// database is already connected, that's why set collation on the fly
$this->Conn->Query('SET NAMES \''.$this->toolkit->systemConfig->get('DBCharset', 'Database').'\' COLLATE \''.$this->toolkit->systemConfig->get('DBCollation', 'Database').'\'');
}
$this->toolkit->systemConfig->save();
if ($this->currentStep == 'db_config') {
if ($this->GetVar('UseExistingSetup')) {
// abort clean install and redirect to already_installed
$this->stepsPreset = 'already_installed';
break;
}
// import base data into new database, not for db_reconfig
$this->toolkit->RunSQL('/core/install/install_schema.sql');
$this->toolkit->RunSQL('/core/install/install_data.sql');
// create category using sql, because Application is not available here
$table_name = $this->toolkit->systemConfig->get('TablePrefix', 'Database') . 'IdGenerator';
$this->Conn->Query('UPDATE ' . $table_name . ' SET lastid = lastid + 1');
$resource_id = $this->Conn->GetOne('SELECT lastid FROM ' . $table_name);
if ($resource_id === false) {
$this->Conn->Query('INSERT INTO '.$table_name.' (lastid) VALUES (2)');
$resource_id = 2;
}
// can't use USER_ROOT constant, since Application isn't available here
$fields_hash = Array (
'l1_Name' => 'Content', 'l1_MenuTitle' => 'Content', 'Filename' => 'Content',
'AutomaticFilename' => 0, 'CreatedById' => -1, 'CreatedOn' => time(),
'ResourceId' => $resource_id - 1, 'l1_Description' => 'Content', 'Status' => 4,
);
$this->Conn->doInsert($fields_hash, $this->toolkit->systemConfig->get('TablePrefix', 'Database') . 'Categories');
$this->toolkit->SetModuleRootCategory('Core', $this->Conn->getInsertID());
// set module "Core" version after install (based on upgrade scripts)
$this->toolkit->SetModuleVersion('Core', 'core/');
// for now we set "In-Portal" module version to "Core" module version (during clean install)
$this->toolkit->SetModuleVersion('In-Portal', 'core/');
}
break;
case 'select_license':
// reset memory cache, when application is first available (on fresh install and clean reinstall steps)
$this->Application->HandleEvent(new kEvent('adm:OnResetMemcache'));
$license_source = $this->GetVar('license_source');
switch ($license_source) {
case 1: // Download from Intechnic
break;
case 2: // Upload License File
$file_data = array_map('trim', file($_FILES['license_file']['tmp_name']));
if ((count($file_data) == 3) && $file_data[1]) {
/** @var kModulesHelper $modules_helper */
$modules_helper = $this->Application->recallObject('ModulesHelper');
if ($modules_helper->verifyLicense($file_data[1])) {
$this->toolkit->systemConfig->set('License', 'Intechnic', $file_data[1]);
$this->toolkit->systemConfig->set('LicenseCode', 'Intechnic', $file_data[2]);
$this->toolkit->systemConfig->save();
}
else {
$this->errorMessage = 'Invalid License File';
}
}
else {
$this->errorMessage = 'Invalid License File';
}
break;
case 3: // Use Existing License
$license_hash = $this->toolkit->systemConfig->get('License', 'Intechnic');
if ($license_hash) {
/** @var kModulesHelper $modules_helper */
$modules_helper = $this->Application->recallObject('ModulesHelper');
if (!$modules_helper->verifyLicense($license_hash)) {
$this->errorMessage = 'Invalid or corrupt license detected';
}
}
else {
// happens, when browser's "Back" button is used
$this->errorMessage = 'Missing License File';
}
break;
case 4: // Skip License (Local Domain Installation)
if ($this->toolkit->sectionFound('Intechnic')) {
// remove any previous license information
$this->toolkit->systemConfig->set('License', 'Intechnic');
$this->toolkit->systemConfig->set('LicenseCode', 'Intechnic');
$this->toolkit->systemConfig->save();
}
break;
}
break;
case 'download_license':
$license_login = $this->GetVar('login');
$license_password = $this->GetVar('password');
$license_id = $this->GetVar('licenses');
/** @var kCurlHelper $curl_helper */
$curl_helper = $this->Application->recallObject('CurlHelper');
if (strlen($license_login) && strlen($license_password) && !$license_id) {
// Here we determine weather login is ok & check available licenses
$url_params = Array (
'login' => md5($license_login),
'password' => md5($license_password),
'version' => $this->toolkit->GetMaxModuleVersion('core/'),
'domain' => base64_encode($_SERVER['HTTP_HOST']),
);
$curl_helper->SetRequestData($url_params);
$file_data = $curl_helper->Send(GET_LICENSE_URL);
if (!$file_data) {
// error connecting to licensing server
$this->errorMessage = 'Unable to connect to the Intechnic server! Please try again later!';
}
else {
if (substr($file_data, 0, 5) == 'Error') {
// after processing data server returned error
$this->errorMessage = substr($file_data, 6);
}
else {
// license received
if (substr($file_data, 0, 3) == 'SEL') {
// we have more, then one license -> let user choose
$this->SetVar('license_selection', base64_encode( substr($file_data, 4) )); // we received html with radio buttons with names "licenses"
$this->errorMessage = 'Please select which license to use';
}
else {
// we have one license
$this->toolkit->processLicense($file_data);
}
}
}
}
else if (!$license_id) {
// licenses were not queried AND user/password missing
$this->errorMessage = 'Incorrect Username or Password. If you don\'t know your username or password, contact Intechnic Support';
}
else {
// Here we download license
$url_params = Array (
'license_id' => md5($license_id),
'dlog' => md5($license_login),
'dpass' => md5($license_password),
'version' => $this->toolkit->GetMaxModuleVersion('core/'),
'domain' => base64_encode($_SERVER['HTTP_HOST']),
);
$curl_helper->SetRequestData($url_params);
$file_data = $curl_helper->Send(GET_LICENSE_URL);
if (!$file_data) {
// error connecting to licensing server
$this->errorMessage = 'Unable to connect to the Intechnic server! Please try again later!';
}
else {
if (substr($file_data, 0, 5) == 'Error') {
// after processing data server returned error
$this->errorMessage = substr($file_data, 6);
}
else {
$this->toolkit->processLicense($file_data);
}
}
}
break;
case 'select_domain':
/** @var kModulesHelper $modules_helper */
$modules_helper = $this->Application->recallObject('ModulesHelper');
// get domain name as entered by user on the form
$domain = $this->GetVar('domain') == 1 ? $_SERVER['HTTP_HOST'] : str_replace(' ', '', $this->GetVar('other'));
$license_hash = $this->toolkit->systemConfig->get('License', 'Intechnic');
if ($license_hash) {
// when license present, then extract domain from it
$license_hash = base64_decode($license_hash);
list ( , , $license_keys) = $modules_helper->_ParseLicense($license_hash);
$license_domain = $license_keys[0]['domain'];
}
else {
// when license missing, then use current domain or domain entered by user
$license_domain = $domain;
}
if ($domain != '') {
if (strstr($domain, $license_domain) || $modules_helper->_IsLocalSite($domain)) {
$this->toolkit->systemConfig->set('Domain', 'Misc', $domain);
$this->toolkit->systemConfig->save();
}
else {
$this->errorMessage = 'Domain name entered does not match domain name in the license!';
}
}
else {
$this->errorMessage = 'Please enter valid domain!';
}
break;
case 'sys_config':
$config_data = $this->GetVar('system_config');
foreach ($config_data as $section => $section_vars) {
foreach ($section_vars as $var_name => $var_value) {
$this->toolkit->systemConfig->set($var_name, $section, $var_value);
}
}
$this->toolkit->systemConfig->save();
break;
case 'root_password':
// update root password in database
/** @var kPasswordFormatter $password_formatter */
$password_formatter = $this->Application->recallObject('kPasswordFormatter');
$config_values = Array (
'RootPass' => $password_formatter->hashPassword($this->Application->GetVar('root_password')),
'Backup_Path' => FULL_PATH . $this->toolkit->systemConfig->get('WriteablePath', 'Misc') . DIRECTORY_SEPARATOR . 'backupdata',
'DefaultEmailSender' => 'portal@' . $this->toolkit->systemConfig->get('Domain', 'Misc')
);
$site_timezone = date_default_timezone_get();
if ($site_timezone) {
$config_values['Config_Site_Time'] = $site_timezone;
}
$this->toolkit->saveConfigValues($config_values);
/** @var UserHelper $user_helper */
$user_helper = $this->Application->recallObject('UserHelper');
// login as "root", when no errors on password screen
$user_helper->loginUser('root', $this->Application->GetVar('root_password'));
// import base language for core (english)
$this->toolkit->ImportLanguage('/core/install/english');
// make sure imported language is set as active in session, created during installation
$this->Application->Session->SetField('Language', 1);
// set imported language as primary
/** @var LanguagesItem $lang */
$lang = $this->Application->recallObject('lang.-item', null, Array('skip_autoload' => true));
$lang->Load(1); // fresh install => ID=1
$lang->setPrimary(true); // for Front-End
break;
case 'choose_modules':
// run module install scripts
$modules = $this->Application->GetVar('modules');
if ($modules) {
foreach ($modules as $module) {
$install_file = MODULES_PATH.'/'.$module.'/install.php';
if (file_exists($install_file)) {
include_once($install_file);
}
}
}
// update category cache
/** @var kPermCacheUpdater $updater */
$updater = $this->Application->makeClass('kPermCacheUpdater');
$updater->OneStepRun();
break;
case 'post_config':
$this->toolkit->saveConfigValues( $this->GetVar('config') );
break;
case 'select_theme':
// 1. mark theme, that user is selected
$theme_id = $this->GetVar('theme');
$theme_table = $this->Application->getUnitOption('theme', 'TableName');
$theme_idfield = $this->Application->getUnitOption('theme', 'IDField');
$sql = 'UPDATE ' . $theme_table . '
SET Enabled = 1, PrimaryTheme = 1
WHERE ' . $theme_idfield . ' = ' . $theme_id;
$this->Conn->Query($sql);
$this->toolkit->rebuildThemes(); // rescan theme to create structure after theme is enabled !!!
// install theme dependent demo data
if ($this->Application->GetVar('install_demo_data')) {
$sql = 'SELECT Name
FROM ' . $theme_table . '
WHERE ' . $theme_idfield . ' = ' . $theme_id;
$theme_name = $this->Conn->GetOne($sql);
$site_path = $this->toolkit->systemConfig->get('WebsitePath','Misc') . '/';
/** @var FileHelper $file_helper */
$file_helper = $this->Application->recallObject('FileHelper');
foreach ($this->Application->ModuleInfo as $module_name => $module_info) {
if ($module_name == 'In-Portal') {
continue;
}
$template_path = '/themes' . '/' . $theme_name . '/' . $module_info['TemplatePath'];
$this->toolkit->RunSQL( $template_path . '_install/install_data.sql', Array('{ThemeId}', '{SitePath}'), Array($theme_id, $site_path) );
if ( file_exists(FULL_PATH . $template_path . '_install/images') ) {
// copy theme demo images into writable path accessible by FCKEditor
$file_helper->copyFolderRecursive(FULL_PATH . $template_path . '_install/images' . DIRECTORY_SEPARATOR, WRITEABLE . '/user_files/Images');
}
}
}
break;
case 'upgrade_modules':
// get installed modules from db and compare their versions to upgrade script
$modules = $this->Application->GetVar('modules');
if ($modules) {
$upgrade_data = $this->GetUpgradableModules();
$start_from_query = $this->Application->GetVar('start_from_query');
$this->upgradeDepencies = $this->getUpgradeDependencies($modules, $upgrade_data);
if ($start_from_query !== false) {
$this->upgradeLog = unserialize( $this->Application->RecallVar('UpgradeLog') );
}
else {
$start_from_query = 0;
$this->upgradeLog = Array ('ModuleVersions' => Array ());
// remember each module version, before upgrade scripts are executed
foreach ($modules as $module_name) {
$module_info = $upgrade_data[$module_name];
$this->upgradeLog['ModuleVersions'][$module_name] = $module_info['FromVersion'];
}
$this->Application->RemoveVar('UpgradeLog');
}
// 1. perform "php before", "sql", "php after" upgrades
foreach ($modules as $module_name) {
$module_info = $upgrade_data[$module_name];
/*echo '<h2>Upgrading "' . $module_info['Name'] . '" to "' . $module_info['ToVersion'] . '"</h2>' . "\n";
flush();*/
if (!$this->RunUpgrade($module_info['Name'], $module_info['ToVersion'], $upgrade_data, $start_from_query)) {
$this->Application->StoreVar('UpgradeLog', serialize($this->upgradeLog));
$this->Done();
}
// restore upgradable module version (makes sense after sql error processing)
$upgrade_data[$module_name]['FromVersion'] = $this->upgradeLog['ModuleVersions'][$module_name];
}
// 2. import language pack, perform "languagepack" upgrade for all upgraded versions
foreach ($modules as $module_name) {
$module_info = $upgrade_data[$module_name];
$sqls =& $this->getUpgradeQueriesFromVersion($module_info['Path'], $module_info['FromVersion']);
preg_match_all('/' . VERSION_MARK . '/s', $sqls, $regs);
// import module language pack
$this->toolkit->ImportLanguage('/' . $module_info['Path'] . 'install/english', true);
// perform advanced language pack upgrade
foreach ($regs[1] as $version) {
$this->RunUpgradeScript($module_info['Path'], $version, 'languagepack');
}
}
// 3. update all theme language packs
/** @var kThemesHelper $themes_helper */
$themes_helper = $this->Application->recallObject('ThemesHelper');
$themes_helper->synchronizeModule(false);
// 4. upgrade admin skin
if (in_array('core', $modules)) {
$skin_upgrade_log = $this->toolkit->upgradeSkin($upgrade_data['core']);
if ($skin_upgrade_log === true) {
$this->Application->RemoveVar('SkinUpgradeLog');
}
else {
$this->Application->StoreVar('SkinUpgradeLog', serialize($skin_upgrade_log));
}
// for now we set "In-Portal" module version to "Core" module version (during upgrade)
$this->toolkit->SetModuleVersion('In-Portal', false, $upgrade_data['core']['ToVersion']);
}
}
break;
case 'finish':
// delete cache
$this->toolkit->deleteCache();
$this->toolkit->rebuildThemes();
// compile admin skin, so it will be available in 3 frames at once
/** @var SkinHelper $skin_helper */
$skin_helper = $this->Application->recallObject('SkinHelper');
/** @var kDBItem $skin */
$skin = $this->Application->recallObject('skin', null, Array ('skip_autoload' => true));
$skin->Load(1, 'IsPrimary');
$skin_helper->compile($skin);
// set installation finished mark
if ($this->Application->ConfigValue('InstallFinished') === false) {
$fields_hash = Array (
'VariableName' => 'InstallFinished',
'VariableValue' => 1,
);
$this->Conn->doInsert($fields_hash, TABLE_PREFIX.'SystemSettings');
}
break;
}
if ($this->errorMessage) {
// was error during run stage
return ;
}
$this->currentStep = $this->GetNextStep();
$this->InitStep(); // init next step (that will be shown now)
$this->InitApplication();
if ($this->currentStep == -1) {
// step after last step -> redirect to admin
/** @var UserHelper $user_helper */
$user_helper = $this->Application->recallObject('UserHelper');
$user_helper->logoutUser();
$this->Application->Redirect($user_helper->event->redirect, $user_helper->event->getRedirectParams(), '', 'index.php');
}
}
/**
* Generates a security keys.
*
* @return void
*/
protected function generateSecurityKeys()
{
if ( $this->toolkit->systemConfig->get('SecurityHmacKey', 'Misc')
&& $this->toolkit->systemConfig->get('SecurityEncryptionKey', 'Misc')
) {
return;
}
// Include class declarations manually, because kApplication isn't available.
require_once FULL_PATH . '/core/kernel/security/SecurityEncrypter.php';
require_once FULL_PATH . '/core/kernel/security/SecurityGenerator.php';
require_once FULL_PATH . '/core/kernel/security/SecurityGeneratorPromise.php';
// Include dependencies, to make "random_int" function available in earlier PHP versions.
require_once FULL_PATH . '/vendor/autoload.php';
// Generate missing security-related settings.
$this->toolkit->systemConfig->set(
'SecurityHmacKey',
'Misc',
base64_encode(SecurityGenerator::generateString(
SecurityEncrypter::HASHING_KEY_LENGTH,
SecurityGenerator::CHAR_ALNUM | SecurityGenerator::CHAR_SYMBOLS
))
);
$this->toolkit->systemConfig->set(
'SecurityEncryptionKey',
'Misc',
SecurityGenerator::generateBytes(SecurityEncrypter::ENCRYPTION_KEY_LENGTH)
);
$this->toolkit->systemConfig->save();
}
function getUpgradeDependencies($modules, &$upgrade_data)
{
$dependencies = Array ();
foreach ($modules as $module_name) {
$module_info = $upgrade_data[$module_name];
$upgrade_object =& $this->getUpgradeObject($module_info['Path']);
if (!is_object($upgrade_object)) {
continue;
}
foreach ($upgrade_object->dependencies as $dependent_version => $version_dependencies) {
if (!$version_dependencies) {
// module is independent -> skip
continue;
}
$parent_name = key($version_dependencies);
$parent_version = $version_dependencies[$parent_name];
if (!array_key_exists($parent_name, $dependencies)) {
// parent module
$dependencies[$parent_name] = Array ();
}
if (!array_key_exists($parent_version, $dependencies[$parent_name])) {
// parent module versions, that are required by other module versions
$dependencies[$parent_name][$parent_version] = Array ();
}
$dependencies[$parent_name][$parent_version][] = Array ($module_info['Name'] => $dependent_version);
}
}
return $dependencies;
}
/**
* Returns database queries, that should be executed to perform upgrade from given to lastest version of given module path
*
* @param string $module_path
* @param string $from_version
* @return string
*/
function &getUpgradeQueriesFromVersion($module_path, $from_version)
{
$upgrades_file = sprintf(UPGRADES_FILE, $module_path, 'sql');
$sqls = file_get_contents($upgrades_file);
$version_mark = preg_replace('/(\(.*?\))/', $from_version, VERSION_MARK);
// get only sqls from next (relative to current) version to end of file
$start_pos = strpos($sqls, $version_mark);
$sqls = substr($sqls, $start_pos);
return $sqls;
}
function RunUpgrade($module_name, $to_version, &$upgrade_data, &$start_from_query)
{
$module_info = $upgrade_data[ strtolower($module_name) ];
$sqls =& $this->getUpgradeQueriesFromVersion($module_info['Path'], $module_info['FromVersion']);
preg_match_all('/(' . VERSION_MARK . ')/s', $sqls, $matches, PREG_SET_ORDER + PREG_OFFSET_CAPTURE);
foreach ($matches as $index => $match) {
// upgrade version
$version = $match[2][0];
if ($this->toolkit->ConvertModuleVersion($version) > $this->toolkit->ConvertModuleVersion($to_version)) {
// only upgrade to $to_version, not further
break;
}
if (!in_array($module_name . ':' . $version, $this->upgradeLog)) {
if ($this->Application->isDebugMode()) {
$this->Application->Debugger->appendHTML('Upgrading "' . $module_name . '" to "' . $version . '" version: BEGIN.');
}
/*echo 'Upgrading "' . $module_name . '" to "' . $version . '".<br/>' . "\n";
flush();*/
// don't upgrade same version twice
$start_pos = $match[0][1] + strlen($match[0][0]);
$end_pos = array_key_exists($index + 1, $matches) ? $matches[$index + 1][0][1] : strlen($sqls);
$version_sqls = substr($sqls, $start_pos, $end_pos - $start_pos);
if ($start_from_query == 0) {
$this->RunUpgradeScript($module_info['Path'], $version, 'before');
}
if (!$this->toolkit->RunSQLText($version_sqls, null, null, $start_from_query)) {
$this->errorMessage .= '<input type="hidden" name="start_from_query" value="' . $this->LastQueryNum . '">';
$this->errorMessage .= '<br/>Module "' . $module_name . '" upgrade to "' . $version . '" failed.';
$this->errorMessage .= '<br/>Click Continue button below to skip this query and go further<br/>';
return false;
}
else {
// reset query counter, when all queries were processed
$start_from_query = 0;
}
$this->RunUpgradeScript($module_info['Path'], $version, 'after');
if ($this->Application->isDebugMode()) {
$this->Application->Debugger->appendHTML('Upgrading "' . $module_name . '" to "' . $version . '" version: END.');
}
// remember, that we've already upgraded given version
$this->upgradeLog[] = $module_name . ':' . $version;
}
if (array_key_exists($module_name, $this->upgradeDepencies) && array_key_exists($version, $this->upgradeDepencies[$module_name])) {
foreach ($this->upgradeDepencies[$module_name][$version] as $dependency_info) {
$dependent_module = key($dependency_info);
$dependent_version = $dependency_info[$dependent_module];
if (!$this->RunUpgrade($dependent_module, $dependent_version, $upgrade_data, $start_from_query)) {
return false;
}
}
}
// only mark module as updated, when all it's dependent modules are upgraded
$this->toolkit->SetModuleVersion($module_name, false, $version);
}
return true;
}
/**
* Run upgrade PHP scripts for module with specified path
*
* @param string $module_path
* @param Array $version
* @param string $mode upgrade mode = {before,after,languagepack}
*/
function RunUpgradeScript($module_path, $version, $mode)
{
$upgrade_object =& $this->getUpgradeObject($module_path);
if (!is_object($upgrade_object)) {
return ;
}
$upgrade_method = 'Upgrade_' . str_replace(Array ('.', '-'), '_', $version);
if (method_exists($upgrade_object, $upgrade_method)) {
$upgrade_object->$upgrade_method($mode);
}
}
/**
* Returns upgrade class for given module path
*
* @param string $module_path
* @return kUpgradeHelper
*/
function &getUpgradeObject($module_path)
{
static $upgrade_classes = Array ();
$upgrades_file = sprintf(UPGRADES_FILE, $module_path, 'php');
if (!file_exists($upgrades_file)) {
$false = false;
return $false;
}
if (!isset($upgrade_classes[$module_path])) {
require_once(FULL_PATH . REL_PATH . '/install/upgrade_helper.php');
// save class name, because 2nd time (in after call)
// $upgrade_class variable will not be present
include_once $upgrades_file;
$upgrade_classes[$module_path] = $upgrade_class;
}
/** @var CoreUpgrades $upgrade_object */
$upgrade_object = new $upgrade_classes[$module_path]();
$upgrade_object->setToolkit($this->toolkit);
return $upgrade_object;
}
/**
* Initialize kApplication
*
* @param bool $force initialize in any case
*/
function InitApplication($force = false)
{
if (($force || !in_array($this->currentStep, $this->skipApplicationSteps)) && !isset($this->Application)) {
// step is allowed for application usage & it was not initialized in previous step
global $start, $debugger, $dbg_options;
include_once(FULL_PATH.'/core/kernel/startup.php');
$this->Application =& kApplication::Instance();
$this->toolkit->Application =& kApplication::Instance();
$this->includeModuleConstants();
$this->Application->Init();
$this->Conn =& $this->Application->GetADODBConnection();
$this->toolkit->Conn =& $this->Application->GetADODBConnection();
}
}
/**
* When no modules installed, then pre-include all modules contants, since they are used in unit configs
*
*/
function includeModuleConstants()
{
$modules = $this->ScanModules();
foreach ($modules as $module_path) {
$constants_file = MODULES_PATH . '/' . $module_path . '/constants.php';
if ( file_exists($constants_file) ) {
kUtil::includeOnce($constants_file);
}
}
}
/**
* Show next step screen
*
* @param string $error_message
* @return void
*/
function Done($error_message = null)
{
if ( isset($error_message) ) {
$this->errorMessage = $error_message;
}
include_once (FULL_PATH . '/' . REL_PATH . '/install/incs/install.tpl');
if ( isset($this->Application) ) {
$this->Application->Done();
}
exit;
}
function ConnectToDatabase()
{
include_once FULL_PATH . '/core/kernel/db/i_db_connection.php';
include_once FULL_PATH . '/core/kernel/db/db_connection.php';
$required_keys = Array ('DBType', 'DBUser', 'DBName');
foreach ($required_keys as $required_key) {
if (!$this->toolkit->systemConfig->get($required_key, 'Database')) {
// one of required db connection settings missing -> abort connection
return false;
}
}
$this->Conn = new kDBConnection($this->toolkit->systemConfig->get('DBType', 'Database'), Array(&$this, 'DBErrorHandler'));
$this->Conn->setup($this->toolkit->systemConfig->getData());
// setup toolkit too
$this->toolkit->Conn =& $this->Conn;
return !$this->Conn->hasError();
}
/**
* Checks if core is already installed
*
* @return bool
*/
function AlreadyInstalled()
{
$table_prefix = $this->toolkit->systemConfig->get('TablePrefix', 'Database');
$settings_table = $this->TableExists('ConfigurationValues') ? 'ConfigurationValues' : 'SystemSettings';
$sql = 'SELECT VariableValue
FROM ' . $table_prefix . $settings_table . '
WHERE VariableName = "InstallFinished"';
return $this->TableExists($settings_table) && $this->Conn->GetOne($sql);
}
function CheckDatabase($check_installed = true)
{
// perform various check type to database specified
// 1. user is allowed to connect to database
// 2. user has all types of permissions in database
// 3. database environment settings met minimum requirements
if (mb_strlen($this->toolkit->systemConfig->get('TablePrefix', 'Database')) > 7) {
$this->errorMessage = 'Table prefix should not be longer than 7 characters';
return false;
}
// connect to database
$status = $this->ConnectToDatabase();
if ($status) {
// if connected, then check if all sql statements work
$sql_tests[] = 'DROP TABLE IF EXISTS test_table';
$sql_tests[] = 'CREATE TABLE test_table(test_col mediumint(6))';
$sql_tests[] = 'LOCK TABLES test_table WRITE';
$sql_tests[] = 'INSERT INTO test_table(test_col) VALUES (5)';
$sql_tests[] = 'UPDATE test_table SET test_col = 12';
$sql_tests[] = 'UNLOCK TABLES';
$sql_tests[] = 'ALTER TABLE test_table ADD COLUMN new_col varchar(10)';
$sql_tests[] = 'SELECT * FROM test_table';
$sql_tests[] = 'DELETE FROM test_table';
$sql_tests[] = 'DROP TABLE IF EXISTS test_table';
foreach ($sql_tests as $sql_test) {
$this->Conn->Query($sql_test);
if ($this->Conn->getErrorCode() != 0) {
$status = false;
break;
}
}
if ($status) {
// if statements work & connection made, then check table existance
if ($check_installed && $this->AlreadyInstalled()) {
$this->errorMessage = 'An In-Portal Database already exists at this location';
return false;
}
$requirements_error = Array ();
$db_check_results = $this->toolkit->CallPrerequisitesMethod('core/', 'CheckDBRequirements');
if ( !$db_check_results['version'] ) {
$requirements_error[] = '- MySQL Version is below 5.0';
}
if ( !$db_check_results['packet_size'] ) {
$requirements_error[] = '- MySQL Packet Size is below 1 MB';
}
if ( $requirements_error ) {
$this->errorMessage = 'Connection successful, but following system requirements were not met:<br/>' . implode('<br/>', $requirements_error);
return false;
}
}
else {
// user has insufficient permissions in database specified
$this->errorMessage = 'Permission Error: ('.$this->Conn->getErrorCode().') '.$this->Conn->getErrorMsg();
return false;
}
}
else {
// was error while connecting
if (!$this->Conn) return false;
$this->errorMessage = 'Connection Error: ('.$this->Conn->getErrorCode().') '.$this->Conn->getErrorMsg();
return false;
}
return true;
}
/**
* Checks if all passed tables exists
*
* @param string $tables comma separated tables list
* @return bool
*/
function TableExists($tables)
{
$prefix = $this->toolkit->systemConfig->get('TablePrefix', 'Database');
$all_found = true;
$tables = explode(',', $tables);
foreach ($tables as $table_name) {
$sql = 'SHOW TABLES LIKE "'.$prefix.$table_name.'"';
if (count($this->Conn->Query($sql)) == 0) {
$all_found = false;
break;
}
}
return $all_found;
}
/**
* Returns modules list found in modules folder
*
* @return Array
*/
function ScanModules()
{
static $modules = null;
if ( !isset($modules) ) {
// use direct include, because it's called before kApplication::Init, that creates class factory
kUtil::includeOnce( KERNEL_PATH . kApplication::MODULE_HELPER_PATH );
$modules_helper = new kModulesHelper();
$modules = $modules_helper->getModules();
}
return $modules;
}
/**
* Virtually place module under "modules" folder or it won't be recognized during upgrade to 5.1.0 version
*
* @param string $name
* @param string $path
* @param string $version
* @return string
*/
function getModulePath($name, $path, $version)
{
if ($name == 'Core') {
// don't transform path for Core module
return $path;
}
if (!preg_match('/^modules\//', $path)) {
// upgrade from 5.0.x/1.0.x to 5.1.x/1.1.x
return 'modules/' . $path;
}
return $path;
}
/**
* Returns list of modules, that can be upgraded
*
*/
function GetUpgradableModules()
{
$ret = Array ();
foreach ($this->Application->ModuleInfo as $module_name => $module_info) {
if ($module_name == 'In-Portal') {
// don't show In-Portal, because it shares upgrade scripts with Core module
continue;
}
$module_info['Path'] = $this->getModulePath($module_name, $module_info['Path'], $module_info['Version']);
$upgrades_file = sprintf(UPGRADES_FILE, $module_info['Path'], 'sql');
if (!file_exists($upgrades_file)) {
// no upgrade file
continue;
}
$sqls = file_get_contents($upgrades_file);
$versions_found = preg_match_all('/'.VERSION_MARK.'/s', $sqls, $regs);
if (!$versions_found) {
// upgrades file doesn't contain version definitions
continue;
}
$to_version = end($regs[1]);
$this_version = $this->toolkit->ConvertModuleVersion($module_info['Version']);
if ($this->toolkit->ConvertModuleVersion($to_version) > $this_version) {
// destination version is greather then current
foreach ($regs[1] as $version) {
if ($this->toolkit->ConvertModuleVersion($version) > $this_version) {
$from_version = $version;
break;
}
}
$version_info = Array (
'FromVersion' => $from_version,
'ToVersion' => $to_version,
);
$ret[ strtolower($module_name) ] = array_merge($module_info, $version_info);
}
}
return $ret;
}
/**
* Returns content to show for current step
*
* @return string
*/
function GetStepBody()
{
$step_template = FULL_PATH.'/core/install/step_templates/'.$this->currentStep.'.tpl';
if (file_exists($step_template)) {
ob_start();
include_once ($step_template);
return ob_get_clean();
}
return '{step template "'.$this->currentStep.'" missing}';
}
/**
* Parses step information file, cache result for current step ONLY & return it
*
* @return Array
*/
function &_getStepInfo()
{
static $info = Array('help_title' => null, 'step_title' => null, 'help_body' => null, 'queried' => false);
if (!$info['queried']) {
$fdata = file_get_contents($this->StepDBFile);
$parser = xml_parser_create();
xml_parse_into_struct($parser, $fdata, $values, $index);
xml_parser_free($parser);
foreach ($index['STEP'] as $section_index) {
$step_data =& $values[$section_index];
if ($step_data['attributes']['NAME'] == $this->currentStep) {
$info['step_title'] = $step_data['attributes']['TITLE'];
if (isset($step_data['attributes']['HELP_TITLE'])) {
$info['help_title'] = $step_data['attributes']['HELP_TITLE'];
}
else {
// if help title not set, then use step title
$info['help_title'] = $step_data['attributes']['TITLE'];
}
$info['help_body'] = trim($step_data['value']);
break;
}
}
$info['queried'] = true;
}
return $info;
}
/**
* Returns particular information abou current step
*
* @param string $info_type
* @return string
*/
function GetStepInfo($info_type)
{
$step_info =& $this->_getStepInfo();
if (isset($step_info[$info_type])) {
return $step_info[$info_type];
}
return '{step "'.$this->currentStep.'"; param "'.$info_type.'" missing}';
}
/**
* Returns passed steps titles
*
* @param Array $steps
* @return Array
* @see kInstaller:PrintSteps
*/
function _getStepTitles($steps)
{
$fdata = file_get_contents($this->StepDBFile);
$parser = xml_parser_create();
xml_parse_into_struct($parser, $fdata, $values, $index);
xml_parser_free($parser);
$ret = Array ();
foreach ($index['STEP'] as $section_index) {
$step_data =& $values[$section_index];
if (in_array($step_data['attributes']['NAME'], $steps)) {
$ret[ $step_data['attributes']['NAME'] ] = $step_data['attributes']['TITLE'];
}
}
return $ret;
}
/**
* Returns current step number in active steps_preset.
* Value can't be cached, because same step can have different number in different presets
*
* @return int
*/
function GetStepNumber()
{
return array_search($this->currentStep, $this->steps[$this->stepsPreset]) + 1;
}
/**
* Returns step name to process next
*
* @return string
*/
function GetNextStep()
{
$next_index = $this->GetStepNumber();
if ($next_index > count($this->steps[$this->stepsPreset]) - 1) {
return -1;
}
return $this->steps[$this->stepsPreset][$next_index];
}
/**
* Returns step name, that was processed before this step
*
* @return string
*/
function GetPreviousStep()
{
$next_index = $this->GetStepNumber() - 1;
if ($next_index < 0) {
$next_index = 0;
}
return $this->steps[$this->stepsPreset][$next_index];
}
/**
* Prints all steps from active steps preset and highlights current step
*
* @param string $active_tpl
* @param string $passive_tpl
* @return string
*/
function PrintSteps($active_tpl, $passive_tpl)
{
$ret = '';
$step_titles = $this->_getStepTitles($this->steps[$this->stepsPreset]);
foreach ($this->steps[$this->stepsPreset] as $step_name) {
$template = $step_name == $this->currentStep ? $active_tpl : $passive_tpl;
$ret .= sprintf($template, $step_titles[$step_name]);
}
return $ret;
}
/**
* Installation error handler for sql errors
*
* @param int $code
* @param string $msg
* @param string $sql
* @return bool
* @access private
*/
function DBErrorHandler($code, $msg, $sql)
{
$this->errorMessage = 'Query: <br />'.htmlspecialchars($sql, ENT_QUOTES, 'UTF-8').'<br />execution result is error:<br />['.$code.'] '.$msg;
return true;
}
/**
* Installation error handler
*
* @param int $errno
* @param string $errstr
* @param string $errfile
* @param int $errline
* @param Array|string $errcontext
*/
function ErrorHandler($errno, $errstr, $errfile = '', $errline = 0, $errcontext = '')
{
if ($errno == E_USER_ERROR) {
// only react on user fatal errors
$this->Done($errstr);
}
}
/**
* Checks, that given button should be visible on current installation step
*
* @param string $name
* @return bool
*/
function buttonVisible($name)
{
$button_visibility = Array (
'continue' => $this->GetNextStep() != -1 || ($this->stepsPreset == 'already_installed'),
'refresh' => in_array($this->currentStep, Array ('sys_requirements', 'check_paths', 'security')),
'back' => in_array($this->currentStep, Array (/*'select_license',*/ 'download_license', 'select_domain')),
);
if ($name == 'any') {
foreach ($button_visibility as $button_name => $button_visible) {
if ($button_visible) {
return true;
}
}
return false;
}
return array_key_exists($name, $button_visibility) ? $button_visibility[$name] : true;
}
}

Event Timeline