Page MenuHomeIn-Portal Phabricator

in-portal
No OneTemporary

File Metadata

Created
Wed, Feb 5, 9:18 PM

in-portal

Index: branches/5.2.x/core/kernel/db/db_load_balancer.php
===================================================================
--- branches/5.2.x/core/kernel/db/db_load_balancer.php (revision 14887)
+++ branches/5.2.x/core/kernel/db/db_load_balancer.php (revision 14888)
@@ -1,641 +1,655 @@
<?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 {
/**
* Current database type
*
* @var string
* @access protected
*/
protected $dbType = 'mysql';
/**
* Function to handle sql errors
*
* @var string
* @access public
*/
public $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 Array
* @access protected
*/
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;
/**
* Indicates, that next query should be sent to maser database
*
* @var bool
*/
public $nextQueryFromMaster = false;
/**
* Creates new instance of load balancer class
*
* @param string $dbType
* @param Array|string $errorHandler
*/
function __construct($dbType, $errorHandler = '')
{
parent::__construct();
$this->dbType = $dbType;
$this->errorHandler = $errorHandler;
$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 ) {
// skip the load balancing if there's only one server OR in admin console
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];
}
else {
$server = $this->servers[$i];
$server['serverIndex'] = $i;
$conn =& $this->reallyOpenConnection($server);
if ( $conn->connectionOpened ) {
$this->connections[$i] =& $conn;
$this->lastUsedIndex = $i;
}
else {
$conn = false;
}
}
if ( $this->nextQueryCachable && is_object($conn) ) {
$conn->nextQueryCachable = true;
$this->nextQueryCachable = false;
}
return $conn;
}
/**
* Really opens a connection.
* Returns a database object whether or not the connection was successful.
*
* @param Array $server
* @return kDBConnection
*/
protected function &reallyOpenConnection($server)
{
$db =& $this->Application->makeClass( 'kDBConnection', Array ($this->dbType, $this->errorHandler, $server['serverIndex']) );
/* @var $db kDBConnection */
$db->debugMode = $this->Application->isDebugMode();
$db->Connect($server['DBHost'], $server['DBUser'], $server['DBUserPassword'], $this->servers[0]['DBName'], true, true);
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);
}
/**
* 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 bool $no_debug
* @return Array
* @access public
*/
public function Query($sql, $key_field = null, $no_debug = false)
{
$conn =& $this->chooseConnection($sql);
return $conn->Query($sql, $key_field, $no_debug);
}
/**
* 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);
}
/**
* If it's a string, adds quotes and backslashes (only work since PHP 4.3.0)
* 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);
+ }
+
+ /**
* 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);
}
/**
* 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) ) {
$index = $this->getMasterIndex();
}
else {
$index = $this->getSlaveIndex();
}
}
$this->lastUsedIndex = $index;
$conn =& $this->openConnection($index);
return $conn;
}
}
Index: branches/5.2.x/core/kernel/db/db_connection.php
===================================================================
--- branches/5.2.x/core/kernel/db/db_connection.php (revision 14887)
+++ branches/5.2.x/core/kernel/db/db_connection.php (revision 14888)
@@ -1,1092 +1,1104 @@
<?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!');
/**
* Multi database connection class
*
*/
class kDBConnection extends kBase {
/**
* Current database type
*
* @var string
* @access protected
*/
protected $dbType = 'mysql';
/**
* Created connection handle
*
* @var resource
* @access protected
*/
protected $connectionID = null;
/**
* Remembers, that database connection was opened successfully
*
* @var bool
* @access public
*/
public $connectionOpened = false;
/**
* Connection parameters, that were used
*
* @var Array
* @access protected
*/
protected $connectionParams = Array ('host' => '', 'user' => '', 'pass' => '', 'db' => '');
/**
* Index of database server
*
* @var int
* @access protected
*/
protected $serverIndex = 0;
/**
* Handle of currently processed recordset
*
* @var resource
* @access protected
*/
protected $queryID = null;
/**
* DB type specific function mappings
*
* @var Array
* @access protected
*/
protected $metaFunctions = Array ();
/**
* Function to handle sql errors
*
* @var Array|string
* @access public
*/
public $errorHandler = '';
/**
* Error code
*
* @var int
* @access protected
*/
protected $errorCode = 0;
/**
* Error message
*
* @var string
* @access protected
*/
protected $errorMessage = '';
/**
* Defines if database connection
* operations should generate debug
* information
*
* @var bool
* @access public
*/
public $debugMode = false;
/**
* Save query execution statistics
*
* @var bool
* @access protected
*/
protected $_captureStatistics = false;
/**
* Last query to database
*
* @var string
* @access public
*/
public $lastQuery = '';
/**
* Total processed queries count
*
* @var int
* @access protected
*/
protected $_queryCount = 0;
/**
* Total time, used for serving queries
*
* @var Array
* @access protected
*/
protected $_queryTime = 0;
/**
* Indicates, that next database query could be cached, when memory caching is enabled
*
* @var bool
* @access public
*/
public $nextQueryCachable = false;
/**
* For backwards compatibility with kDBLoadBalancer class
*
* @var bool
* @access public
*/
public $nextQueryFromMaster = false;
/**
* Initializes connection class with
* db type to used in future
*
* @param string $dbType
* @param string $errorHandler
* @param int $server_index
* @access public
*/
public function __construct($dbType, $errorHandler = '', $server_index = 0)
{
if ( class_exists('kApplication') ) {
// prevents "Fatal Error" on 2nd installation step (when database is empty)
parent::__construct();
}
$this->dbType = $dbType;
$this->serverIndex = $server_index;
// $this->initMetaFunctions();
if (!$errorHandler) {
$this->errorHandler = Array(&$this, 'handleError');
}
else {
$this->errorHandler = $errorHandler;
}
$this->_captureStatistics = defined('DBG_CAPTURE_STATISTICS') && DBG_CAPTURE_STATISTICS && !(defined('ADMIN') && ADMIN);
}
/**
* Set's custom error
*
* @param int $code
* @param string $msg
* @access protected
*/
protected function setError($code, $msg)
{
$this->errorCode = $code;
$this->errorMessage = $msg;
}
/**
* Checks if previous query execution
* raised an error.
*
* @return bool
* @access public
*/
public function hasError()
{
return $this->errorCode != 0;
}
/**
* Caches function specific to requested
* db type
*
* @access protected
*/
protected function initMetaFunctions()
{
$ret = Array ();
switch ( $this->dbType ) {
case 'mysql':
$ret = Array (); // only define functions, that name differs from "dbType_<meta_name>"
break;
}
$this->metaFunctions = $ret;
}
/**
* Gets function for specific db type
* based on it's meta name
*
* @param string $name
* @return string
* @access protected
*/
protected function getMetaFunction($name)
{
/*if ( !isset($this->metaFunctions[$name]) ) {
$this->metaFunctions[$name] = $name;
}*/
return $this->dbType . '_' . $name;
}
/**
* Try to connect to database server
* using specified parameters and set
* database to $db if connection made
*
* @param string $host
* @param string $user
* @param string $pass
* @param string $db
* @param bool $force_new
* @param bool $retry
* @return bool
* @access public
*/
public function Connect($host, $user, $pass, $db, $force_new = false, $retry = false)
{
$this->connectionParams = Array ('host' => $host, 'user' => $user, 'pass' => $pass, 'db' => $db);
$func = $this->getMetaFunction('connect');
$this->connectionID = $func($host, $user, $pass, $force_new);
if ($this->connectionID) {
if (defined('DBG_SQL_MODE')) {
$this->Query('SET sql_mode = \''.DBG_SQL_MODE.'\'');
}
if (defined('SQL_COLLATION') && defined('SQL_CHARSET')) {
$this->Query('SET NAMES \''.SQL_CHARSET.'\' COLLATE \''.SQL_COLLATION.'\'');
}
$this->setError(0, ''); // reset error
$this->setDB($db);
}
// process error (fatal in most cases)
$func = $this->getMetaFunction('errno');
$this->errorCode = $this->connectionID ? $func($this->connectionID) : $func();
if ( is_resource($this->connectionID) && !$this->hasError() ) {
$this->connectionOpened = true;
return true;
}
$func = $this->getMetaFunction('error');
$this->errorMessage = $this->connectionID ? $func($this->connectionID) : $func();
$error_msg = 'Database connection failed, please check your connection settings.<br/>Error (' . $this->errorCode . '): ' . $this->errorMessage;
if ( (defined('IS_INSTALL') && IS_INSTALL) || $retry ) {
trigger_error($error_msg, E_USER_WARNING);
}
else {
throw new Exception($error_msg);
}
$this->connectionOpened = false;
return false;
}
/**
* Setups the connection according given configuration
*
* @param Array $config
* @return bool
* @access public
*/
public function setup($config)
{
if ( is_object($this->Application) ) {
$this->debugMode = $this->Application->isDebugMode();
}
return $this->Connect(
$config['Database']['DBHost'],
$config['Database']['DBUser'],
$config['Database']['DBUserPassword'],
$config['Database']['DBName']
);
}
/**
* Performs 3 reconnect attempts in case if connection to a DB was lost in the middle of script run (e.g. server restart)
*
* @param bool $force_new
* @return bool
* @access protected
*/
protected function ReConnect($force_new = false)
{
$retry_count = 0;
$connected = false;
$func = $this->getMetaFunction('close');
$func($this->connectionID);
while ( $retry_count < 3 ) {
sleep(5); // wait 5 seconds before each reconnect attempt
$connected = $this->Connect(
$this->connectionParams['host'],
$this->connectionParams['user'],
$this->connectionParams['pass'],
$this->connectionParams['db'],
$force_new, true
);
if ( $connected ) {
break;
}
$retry_count++;
}
return $connected;
}
/**
* Shows error message from previous operation
* if it failed
*
* @param string $sql
* @param string $key_field
* @param bool $no_debug
* @return bool
* @access protected
*/
protected function showError($sql = '', $key_field = null, $no_debug = false)
{
static $retry_count = 0;
$func = $this->getMetaFunction('errno');
if (!$this->connectionID) {
// no connection while doing mysql_query
$this->errorCode = $func();
if ( $this->hasError() ) {
$func = $this->getMetaFunction('error');
$this->errorMessage = $func();
$ret = $this->callErrorHandler($sql);
if (!$ret) {
exit;
}
}
return false;
}
// checking if there was an error during last mysql_query
$this->errorCode = $func($this->connectionID);
if ( $this->hasError() ) {
$func = $this->getMetaFunction('error');
$this->errorMessage = $func($this->connectionID);
$ret = $this->callErrorHandler($sql);
if ( ($this->errorCode == 2006 || $this->errorCode == 2013) && ($retry_count < 3) ) {
// #2006 - MySQL server has gone away
// #2013 - Lost connection to MySQL server during query
$retry_count++;
if ( $this->ReConnect() ) {
return $this->Query($sql, $key_field, $no_debug);
}
}
if (!$ret) {
exit;
}
}
else {
$retry_count = 0;
}
return false;
}
/**
* Sends db error to a predefined error handler
*
* @param $sql
* @return bool
* @access protected
*/
protected function callErrorHandler($sql)
{
if (is_array($this->errorHandler)) {
$func = $this->errorHandler[1];
$ret = $this->errorHandler[0]->$func($this->errorCode, $this->errorMessage, $sql);
}
else {
$func = $this->errorHandler;
$ret = $func($this->errorCode, $this->errorMessage, $sql);
}
return $ret;
}
/**
* Default error handler for sql errors
*
* @param int $code
* @param string $msg
* @param string $sql
* @return bool
* @access public
*/
public function handleError($code, $msg, $sql)
{
echo '<strong>Processing SQL</strong>: ' . $sql . '<br/>';
echo '<strong>Error (' . $code . '):</strong> ' . $msg . '<br/>';
return false;
}
/**
* Set's database name for connection
* to $new_name
*
* @param string $new_name
* @return bool
* @access protected
*/
protected function setDB($new_name)
{
if (!$this->connectionID) return false;
$func = $this->getMetaFunction('select_db');
return $func($new_name, $this->connectionID);
}
/**
* 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)
{
$row = $this->GetRow($sql, $offset);
if ( !$row ) {
return false;
}
return array_shift($row);
}
/**
* 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)
{
$sql .= ' ' . $this->getLimitClause($offset, 1);
$ret = $this->Query($sql);
if ( !$ret ) {
return false;
}
return array_shift($ret);
}
/**
* 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)
{
$rows = $this->Query($sql);
if ( !$rows ) {
return $rows;
}
$i = 0;
$row_count = count($rows);
$ret = Array ();
if ( isset($key_field) ) {
while ( $i < $row_count ) {
$ret[$rows[$i][$key_field]] = array_shift($rows[$i]);
$i++;
}
}
else {
while ( $i < $row_count ) {
$ret[] = array_shift($rows[$i]);
$i++;
}
}
return $ret;
}
/**
* 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 bool $no_debug
* @return Array
* @access public
*/
public function Query($sql, $key_field = null, $no_debug = false)
{
$this->lastQuery = $sql;
if ( !$no_debug ) {
$this->_queryCount++;
}
if ( $this->debugMode && !$no_debug ) {
return $this->debugQuery($sql, $key_field);
}
$query_func = $this->getMetaFunction('query');
// set 1st checkpoint: begin
if ( $this->_captureStatistics ) {
$start_time = microtime(true);
}
// set 1st checkpoint: end
$this->setError(0, ''); // reset error
$this->queryID = $query_func($sql, $this->connectionID);
if ( is_resource($this->queryID) ) {
$ret = Array ();
$fetch_func = $this->getMetaFunction('fetch_assoc');
if ( isset($key_field) ) {
while ( ($row = $fetch_func($this->queryID)) ) {
$ret[$row[$key_field]] = $row;
}
}
else {
while ( ($row = $fetch_func($this->queryID)) ) {
$ret[] = $row;
}
}
// set 2nd checkpoint: begin
if ( $this->_captureStatistics ) {
$query_time = microtime(true) - $start_time;
if ( $query_time > DBG_MAX_SQL_TIME && !$no_debug ) {
$this->Application->logSlowQuery($sql, $query_time);
}
$this->_queryTime += $query_time;
}
// set 2nd checkpoint: end
$this->Destroy();
return $ret;
}
else {
// set 2nd checkpoint: begin
if ( $this->_captureStatistics ) {
$this->_queryTime += microtime(true) - $start_time;
}
// set 2nd checkpoint: end
}
return $this->showError($sql, $key_field, $no_debug);
}
/**
* Retrieves data from database and return resource id on success or false otherwise
*
* @param string $select_sql
* @return resource
* @access public
* @see kDBConnection::GetNextRow
*/
public function QueryRaw($select_sql)
{
$this->lastQuery = $select_sql;
$this->_queryCount++;
$query_func = $this->getMetaFunction('query');
// set 1st checkpoint: begin
if ($this->_captureStatistics) {
$start_time = microtime(true);
}
// set 1st checkpoint: end
$this->setError(0, ''); // reset error
$resource = $query_func($select_sql, $this->connectionID);
// set 2nd checkpoint: begin
if ($this->_captureStatistics) {
$query_time = microtime(true) - $start_time;
if ($query_time > DBG_MAX_SQL_TIME) {
$this->Application->logSlowQuery($select_sql, $query_time);
}
$this->_queryTime += $query_time;
}
// set 2nd checkpoint: end
if ( is_resource($resource) ) {
return $resource;
}
return $this->showError($select_sql);
}
/**
* Returns row count in recordset
*
* @param resource $resource
* @return int
* @access public
*/
public function RowCount($resource)
{
$count_func = $this->getMetaFunction('num_rows');
return $count_func($resource);
}
/**
* Returns next available row from recordset
*
* @param resource $resource
* @param string $fetch_type
* @return Array
* @access public
* @see kDBConnection::QueryRaw
*/
public function GetNextRow($resource, $fetch_type = 'assoc')
{
$fetch_func = $this->getMetaFunction('fetch_' . $fetch_type);
return $fetch_func($resource);
}
/**
* Free memory used to hold recordset handle
*
* @param resource $resource
* @access public
* @see kDBConnection::QueryRaw
*/
public function Destroy($resource = null)
{
if ( !isset($resource) ) {
$resource = $this->queryID;
}
if ( $resource ) {
$free_func = $this->getMetaFunction('free_result');
$free_func($resource);
$this->queryID = null;
}
}
/**
* Performs sql query, that will change database content
*
* @param string $sql
* @return bool
* @access public
*/
public function ChangeQuery($sql)
{
$this->Query($sql);
return $this->errorCode == 0 ? true : false;
}
/**
* 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.
*
* Each database query will be profiled into Debugger.
*
* @param string $sql
* @param string $key_field
* @return Array
* @access public
*/
protected function debugQuery($sql, $key_field = null)
{
global $debugger;
$query_func = $this->getMetaFunction('query');
// set 1st checkpoint: begin
$profileSQLs = defined('DBG_SQL_PROFILE') && DBG_SQL_PROFILE;
if ( $profileSQLs ) {
$queryID = $debugger->generateID();
$debugger->profileStart('sql_' . $queryID, $debugger->formatSQL($sql));
}
// set 1st checkpoint: end
$this->setError(0, ''); // reset error
$this->queryID = $query_func($sql, $this->connectionID);
if ( is_resource($this->queryID) ) {
$ret = Array ();
$fetch_func = $this->getMetaFunction('fetch_assoc');
if ( isset($key_field) ) {
while ( ($row = $fetch_func($this->queryID)) ) {
$ret[$row[$key_field]] = $row;
}
}
else {
while ( ($row = $fetch_func($this->queryID)) ) {
$ret[] = $row;
}
}
// set 2nd checkpoint: begin
if ( $profileSQLs ) {
$first_cell = count($ret) == 1 && count(current($ret)) == 1 ? current(current($ret)) : null;
if ( strlen($first_cell) > 200 ) {
$first_cell = substr($first_cell, 0, 50) . ' ...';
}
$debugger->profileFinish('sql_' . $queryID, null, null, $this->getAffectedRows(), $first_cell, $this->_queryCount, $this->nextQueryCachable, $this->serverIndex);
$debugger->profilerAddTotal('sql', 'sql_' . $queryID);
$this->nextQueryCachable = false;
}
// set 2nd checkpoint: end
$this->Destroy();
return $ret;
}
else {
// set 2nd checkpoint: begin
if ( $profileSQLs ) {
$debugger->profileFinish('sql_' . $queryID, null, null, $this->getAffectedRows(), null, $this->_queryCount, $this->nextQueryCachable, $this->serverIndex);
$debugger->profilerAddTotal('sql', 'sql_' . $queryID);
$this->nextQueryCachable = false;
}
// set 2nd checkpoint: end
}
return $this->showError($sql, $key_field);
}
/**
* Returns auto increment field value from
* insert like operation if any, zero otherwise
*
* @return int
* @access public
*/
public function getInsertID()
{
$func = $this->getMetaFunction('insert_id');
return $func($this->connectionID);
}
/**
* Returns row count affected by last query
*
* @return int
* @access public
*/
public function getAffectedRows()
{
$func = $this->getMetaFunction('affected_rows');
return $func($this->connectionID);
}
/**
* Returns LIMIT sql clause part for specific db
*
* @param int $offset
* @param int $rows
* @return string
* @access public
*/
public function getLimitClause($offset, $rows)
{
if ( !($rows > 0) ) {
return '';
}
switch ( $this->dbType ) {
default:
return 'LIMIT ' . $offset . ',' . $rows;
break;
}
}
/**
* If it's a string, adds quotes and backslashes (only work since PHP 4.3.0)
* Otherwise returns as-is
*
* @param mixed $string
* @return string
* @access public
*/
public function qstr($string)
{
if ( is_null($string) ) {
return 'NULL';
}
# This will also quote numeric values. This should be harmless,
# and protects against weird problems that occur when they really
# _are_ strings such as article titles and string->number->string
# conversion is not 1:1.
return "'" . mysql_real_escape_string($string, $this->connectionID) . "'";
}
/**
+ * Calls "qstr" function for each given array element
+ *
+ * @param Array $array
+ * @param string $function
+ * @return Array
+ */
+ public function qstrArray($array, $function = 'qstr')
+ {
+ return array_map(Array (&$this, $function), $array);
+ }
+
+ /**
* Escapes strings (only work since PHP 4.3.0)
*
* @param mixed $string
* @return string
* @access public
*/
public function escape($string)
{
if ( is_null($string) ) {
return 'NULL';
}
$string = mysql_real_escape_string($string, $this->connectionID);
// prevent double-escaping of MySQL wildcard symbols ("%" and "_") in case if they were already escaped
return str_replace(Array ('\\\\%', '\\\\_'), Array ('\\%', '\\_'), $string);
}
/**
* Returns last error code occurred
*
* @return int
* @access public
*/
public function getErrorCode()
{
return $this->errorCode;
}
/**
* Returns last error message
*
* @return string
* @access public
*/
public function getErrorMsg()
{
return $this->errorMessage;
}
/**
* 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)
{
static $value_sqls = Array ();
if ($insert_now) {
$fields_sql = '`' . implode('`,`', array_keys($fields_hash)) . '`';
}
$values_sql = '';
foreach ($fields_hash as $field_name => $field_value) {
$values_sql .= $this->qstr($field_value) . ',';
}
// don't use preg here, as it may fail when string is too long
$value_sqls[] = rtrim($values_sql, ',');
$insert_result = true;
if ($insert_now) {
$insert_count = count($value_sqls);
if (($insert_count > 1) && ($value_sqls[$insert_count - 1] == $value_sqls[$insert_count - 2])) {
// last two records are the same
array_pop($value_sqls);
}
$sql = strtoupper($type) . ' INTO `' . $table . '` (' . $fields_sql . ') VALUES (' . implode('),(', $value_sqls) . ')';
$value_sqls = Array (); // reset before query to prevent repeated call from error handler to insert 2 records instead of 1
$insert_result = $this->ChangeQuery($sql);
}
return $insert_result;
}
/**
* 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)
{
if (!$fields_hash) return true;
$fields_sql = '';
foreach ($fields_hash as $field_name => $field_value) {
$fields_sql .= '`'.$field_name.'` = ' . $this->qstr($field_value) . ',';
}
// don't use preg here, as it may fail when string is too long
$fields_sql = rtrim($fields_sql, ',');
$sql = 'UPDATE `'.$table.'` SET '.$fields_sql.' WHERE '.$key_clause;
return $this->ChangeQuery($sql);
}
/**
* 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)
{
static $table_found = false;
if ( $table_found === false ) {
$table_found = array_flip($this->GetCol('SHOW TABLES'));
}
if ( !preg_match('/^' . preg_quote(TABLE_PREFIX, '/') . '(.*)/', $table_name) ) {
$table_name = TABLE_PREFIX . $table_name;
}
if ( $force ) {
if ( $this->Query('SHOW TABLES LIKE ' . $this->qstr($table_name)) ) {
$table_found[$table_name] = 1;
}
else {
unset($table_found[$table_name]);
}
}
return isset($table_found[$table_name]);
}
/**
* Returns query processing statistics
*
* @return Array
* @access public
*/
public function getQueryStatistics()
{
return Array ('time' => $this->_queryTime, 'count' => $this->_queryCount);
}
/**
* Get status information from SHOW STATUS in an associative array
*
* @param string $which
* @return Array
* @access public
*/
public function getStatus($which = '%')
{
$status = Array ();
$records = $this->Query('SHOW STATUS LIKE "' . $which . '"');
foreach ($records as $record) {
$status[ $record['Variable_name'] ] = $record['Value'];
}
return $status;
}
/**
* Get slave replication lag. It will only work if the DB user has the PROCESS privilege.
*
* @return int
* @access public
*/
public function getSlaveLag()
{
// don't use kDBConnection::Query method, since it will create an array of all server processes
$rs = $this->QueryRaw('SHOW PROCESSLIST');
$skip_states = Array (
'Waiting for master to send event',
'Connecting to master',
'Queueing master event to the relay log',
'Waiting for master update',
'Requesting binlog dump',
);
// find slave SQL thread
while ( $row = $this->GetNextRow($rs, 'array') ) {
if ( $row['User'] == 'system user' && !in_array($row['State'], $skip_states) ) {
// this is it, return the time (except -ve)
$this->Destroy($rs);
return $row['Time'] > 0x7fffffff ? false : $row['Time'];
}
}
$this->Destroy($rs);
return false;
}
}
\ No newline at end of file
Index: branches/5.2.x/core/kernel/managers/cache_manager.php
===================================================================
--- branches/5.2.x/core/kernel/managers/cache_manager.php (revision 14887)
+++ branches/5.2.x/core/kernel/managers/cache_manager.php (revision 14888)
@@ -1,752 +1,752 @@
<?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 kCacheManager extends kBase implements kiCacheable {
/**
* Used variables from ConfigurationValues table
*
* @var Array
* @access protected
*/
protected $configVariables = Array();
/**
* Used variables from ConfigurationValues table retrieved from unit cache
*
* @var Array
* @access protected
*/
protected $originalConfigVariables = Array ();
/**
* IDs of config variables used in current run (for caching)
*
* @var Array
* @access protected
*/
protected $configIDs = Array ();
/**
* IDs of config variables retrieved from unit cache
*
* @var Array
* @access protected
*/
protected $originalConfigIDs = Array ();
/**
* Object of memory caching class
*
* @var kCache
* @access protected
*/
protected $cacheHandler = null;
protected $temporaryCache = Array (
'registerAggregateTag' => Array (),
'registerScheduledTask' => Array (),
'registerHook' => Array (),
'registerBuildEvent' => Array (),
'registerAggregateTag' => Array (),
);
/**
* Creates caching manager instance
*
* @access public
*/
public function InitCache()
{
$this->cacheHandler =& $this->Application->makeClass('kCache');
}
/**
* Returns cache key, used to cache phrase and configuration variable IDs used on current page
*
* @return string
* @access protected
*/
protected function getCacheKey()
{
// TODO: maybe language part isn't required, since same phrase from different languages have one ID now
return $this->Application->GetVar('t') . $this->Application->GetVar('m_theme') . $this->Application->GetVar('m_lang') . $this->Application->isAdmin;
}
/**
* Loads phrases and configuration variables, that were used on this template last time
*
* @access public
*/
public function LoadApplicationCache()
{
$phrase_ids = $config_ids = Array ();
$sql = 'SELECT PhraseList, ConfigVariables
FROM ' . TABLE_PREFIX . 'PhraseCache
WHERE Template = ' . $this->Conn->qstr( md5($this->getCacheKey()) );
$res = $this->Conn->GetRow($sql);
if ($res) {
if ( $res['PhraseList'] ) {
$phrase_ids = explode(',', $res['PhraseList']);
}
if ( $res['ConfigVariables'] ) {
$config_ids = array_diff( explode(',', $res['ConfigVariables']), $this->originalConfigIDs);
}
}
$this->Application->Phrases->Init('phrases', '', null, $phrase_ids);
$this->configIDs = $this->originalConfigIDs = $config_ids;
$this->InitConfig();
}
/**
* Updates phrases and configuration variables, that were used on this template
*
* @access public
*/
public function UpdateApplicationCache()
{
$update = false;
//something changed
$update = $update || $this->Application->Phrases->NeedsCacheUpdate();
$update = $update || (count($this->configIDs) && $this->configIDs != $this->originalConfigIDs);
if ($update) {
$fields_hash = Array (
'PhraseList' => implode(',', $this->Application->Phrases->Ids),
'CacheDate' => adodb_mktime(),
'Template' => md5( $this->getCacheKey() ),
'ConfigVariables' => implode(',', array_unique($this->configIDs)),
);
$this->Conn->doInsert($fields_hash, TABLE_PREFIX . 'PhraseCache', 'REPLACE');
}
}
/**
* Loads configuration variables, that were used on this template last time
*
* @access protected
*/
protected function InitConfig()
{
if (!$this->originalConfigIDs) {
return ;
}
$sql = 'SELECT VariableValue, VariableName
FROM ' . TABLE_PREFIX . 'ConfigurationValues
WHERE VariableId IN (' . implode(',', $this->originalConfigIDs) . ')';
$config_variables = $this->Conn->GetCol($sql, 'VariableName');
$this->configVariables = array_merge($this->configVariables, $config_variables);
}
/**
* Returns configuration option value by name
*
* @param string $name
* @return string
* @access public
*/
public function ConfigValue($name)
{
if ($name == 'Smtp_AdminMailFrom') {
$res = $this->Application->siteDomainField('AdminEmail');
if ($res) {
return $res;
}
}
if ( array_key_exists($name, $this->configVariables) ) {
return $this->configVariables[$name];
}
if ( defined('IS_INSTALL') && IS_INSTALL && !$this->Application->TableFound('ConfigurationValues', true) ) {
return false;
}
$this->Conn->nextQueryCachable = true;
$sql = 'SELECT VariableId, VariableValue
FROM ' . TABLE_PREFIX . 'ConfigurationValues
WHERE VariableName = ' . $this->Conn->qstr($name);
$res = $this->Conn->GetRow($sql);
if ($res !== false) {
$this->configIDs[] = $res['VariableId'];
$this->configVariables[$name] = $res['VariableValue'];
return $res['VariableValue'];
}
trigger_error('Usage of undefined configuration variable "<strong>' . $name . '</strong>"', E_USER_NOTICE);
return false;
}
function SetConfigValue($name, $value)
{
$this->configVariables[$name] = $value;
$fields_hash = Array ('VariableValue' => $value);
$this->Conn->doUpdate($fields_hash, TABLE_PREFIX . 'ConfigurationValues', 'VariableName = ' . $this->Conn->qstr($name));
if ( array_key_exists($name, $this->originalConfigVariables) && $value != $this->originalConfigVariables[$name] ) {
$this->DeleteUnitCache();
}
}
/**
* Loads data, that was cached during unit config parsing
*
* @return bool
* @access public
*/
public function LoadUnitCache()
{
if ( $this->Application->isCachingType(CACHING_TYPE_MEMORY) ) {
$data = $this->Application->getCache('master:configs_parsed', false, CacheSettings::$unitCacheRebuildTime);
}
else {
$data = $this->Application->getDBCache('configs_parsed', CacheSettings::$unitCacheRebuildTime);
}
if ( $data ) {
$cache = unserialize($data); // 126 KB all modules
unset($data);
$this->Application->InitManagers();
$this->Application->Factory->setFromCache($cache);
$this->Application->UnitConfigReader->setFromCache($cache);
$this->Application->EventManager->setFromCache($cache);
$aggregator =& $this->Application->recallObject('TagsAggregator', 'kArray');
/* @var $aggregator kArray */
$aggregator->setFromCache($cache);
$this->setFromCache($cache);
$this->Application->setFromCache($cache);
unset($cache);
return true;
}
if ( $this->Application->isCachingType(CACHING_TYPE_MEMORY) ) {
$this->Application->rebuildCache('master:configs_parsed', kCache::REBUILD_NOW, CacheSettings::$unitCacheRebuildTime);
}
else {
$this->Application->rebuildDBCache('configs_parsed', kCache::REBUILD_NOW, CacheSettings::$unitCacheRebuildTime);
}
return false;
}
/**
* Empties factory and event manager cache (without storing changes)
*/
public function EmptyUnitCache()
{
$cache_keys = Array (
'Factory.Files', 'Factory.realClasses', 'Factory.Dependencies',
'EventManager.buildEvents', 'EventManager.beforeHooks',
'EventManager.afterHooks', 'EventManager.beforeRegularEvents',
'EventManager.afterRegularEvents'
);
$empty_cache = Array ();
foreach ($cache_keys as $cache_key) {
$empty_cache[$cache_key] = Array ();
}
$this->Application->Factory->setFromCache($empty_cache);
$this->Application->EventManager->setFromCache($empty_cache);
// otherwise ModulesHelper indirectly used from includeConfigFiles won't work
$this->Application->RegisterDefaultClasses();
}
/**
* Updates data, that was parsed from unit configs this time
*
* @access public
*/
public function UpdateUnitCache()
{
$aggregator =& $this->Application->recallObject('TagsAggregator', 'kArray');
/* @var $aggregator kArray */
$this->preloadConfigVars(); // preloading will put to cache
$cache = array_merge(
$this->Application->Factory->getToCache(),
$this->Application->UnitConfigReader->getToCache(),
$this->Application->EventManager->getToCache(),
$aggregator->getToCache(),
$this->getToCache(),
$this->Application->getToCache()
);
$cache_rebuild_by = SERVER_NAME . ' (' . getenv('REMOTE_ADDR') . ') - ' . adodb_date('d/m/Y H:i:s');
if ($this->Application->isCachingType(CACHING_TYPE_MEMORY)) {
$this->Application->setCache('master:configs_parsed', serialize($cache));
$this->Application->setCache('master:last_cache_rebuild', $cache_rebuild_by);
}
else {
$this->Application->setDBCache('configs_parsed', serialize($cache));
$this->Application->setDBCache('last_cache_rebuild', $cache_rebuild_by);
}
}
public function delayUnitProcessing($method, $params)
{
if ($this->Application->InitDone) {
// init already done -> call immediately (happens during installation)
$function = Array (&$this->Application, $method);
call_user_func_array($function, $params);
return ;
}
$this->temporaryCache[$method][] = $params;
}
public function applyDelayedUnitProcessing()
{
foreach ($this->temporaryCache as $method => $method_calls) {
$function = Array (&$this->Application, $method);
foreach ($method_calls as $method_call) {
call_user_func_array($function, $method_call);
}
$this->temporaryCache[$method] = Array ();
}
}
/**
* 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)
{
if ( isset($config_variables) && !array_intersect(array_keys($this->originalConfigVariables), $config_variables) ) {
// prevent cache reset, when given config variables are not in unit cache
return;
}
if ( $this->Application->isCachingType(CACHING_TYPE_MEMORY) ) {
$this->Application->rebuildCache('master:configs_parsed', kCache::REBUILD_LATER, CacheSettings::$unitCacheRebuildTime);
}
else {
$this->Application->rebuildDBCache('configs_parsed', kCache::REBUILD_LATER, CacheSettings::$unitCacheRebuildTime);
}
}
/**
* Deletes cached section tree, used during permission checking and admin console tree display
*
* @return void
* @access public
*/
public function DeleteSectionCache()
{
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);
}
}
/**
* Preloads 21 widely used configuration variables, so they will get to cache for sure
*
* @access protected
*/
protected function preloadConfigVars()
{
$config_vars = Array (
// session related
'SessionTimeout', 'SessionCookieName', 'SessionCookieDomains', 'SessionBrowserSignatureCheck',
'SessionIPAddressCheck', 'CookieSessions', 'KeepSessionOnBrowserClose', 'User_GuestGroup',
'User_LoggedInGroup', 'RegistrationUsernameRequired',
// output related
'UseModRewrite', 'UseContentLanguageNegotiation', 'UseOutputCompression', 'OutputCompressionLevel',
'Config_Site_Time', 'SystemTagCache',
// tracking related
'UseChangeLog', 'UseVisitorTracking', 'ModRewriteUrlEnding', 'ForceModRewriteUrlEnding',
'RunScheduledTasksFromCron',
);
- $escaped_config_vars = array_map(Array (&$this->Conn, 'qstr'), $config_vars);
+ $escaped_config_vars = $this->Conn->qstrArray($config_vars);
$sql = 'SELECT VariableId, VariableName, VariableValue
FROM ' . TABLE_PREFIX . 'ConfigurationValues
WHERE VariableName IN (' . implode(',', $escaped_config_vars) . ')';
$data = $this->Conn->Query($sql, 'VariableId');
foreach ($data as $variable_id => $variable_info) {
$this->configIDs[] = $variable_id;
$this->configVariables[ $variable_info['VariableName'] ] = $variable_info['VariableValue'];
}
}
/**
* Sets data from cache to object
*
* Used for cases, when ConfigValue is called before LoadApplicationCache method (e.g. session init, url engine init)
*
* @param Array $data
* @access public
*/
public function setFromCache(&$data)
{
$this->configVariables = $this->originalConfigVariables = $data['Application.ConfigHash'];
$this->configIDs = $this->originalConfigIDs = $data['Application.ConfigCacheIds'];
}
/**
* 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 (
'Application.ConfigHash' => $this->configVariables,
'Application.ConfigCacheIds' => $this->configIDs,
// not in use, since it only represents template specific values, not global ones
// 'Application.Caches.ConfigVariables' => $this->originalConfigIDs,
);
}
/**
* Returns caching type (none, memory, temporary)
*
* @param int $caching_type
* @return bool
* @access public
*/
public function isCachingType($caching_type)
{
return $this->cacheHandler->getCachingType() == $caching_type;
}
/**
* Prints caching statistics
*
* @access public
*/
public function printStatistics()
{
$this->cacheHandler->printStatistics();
}
/**
* 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->cacheHandler->getCache($key, $store_locally, $max_rebuild_seconds);
}
/**
* Adds new value to cache $cache_name and identified by key $key
*
* @param int $key key name to add to cache
* @param mixed $value value of chached record
* @param int $expiration when value expires (0 - doesn't expire)
* @return bool
* @access public
*/
public function setCache($key, $value, $expiration = 0)
{
return $this->cacheHandler->setCache($key, $value, $expiration);
}
/**
* Sets rebuilding mode for given cache
*
* @param string $name
* @param int $mode
* @param int $max_rebuilding_time
*/
public function rebuildCache($name, $mode = null, $max_rebuilding_time = 0)
{
$this->cacheHandler->rebuildCache($name, $mode, $max_rebuilding_time);
}
/**
* Deletes key from cache
*
* @param string $key
* @access public
*/
public function deleteCache($key)
{
$this->cacheHandler->delete($key);
}
/**
* Reset's all memory cache at once
*
* @access public
*/
public function resetCache()
{
$this->cacheHandler->reset();
}
/**
* 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)
{
if ( $this->_getDBCache($name . '_rebuild') ) {
// cache rebuild requested -> rebuild now
$this->deleteDBCache($name . '_rebuild');
return false;
}
// no serials in cache key OR cache is outdated
$wait_seconds = $max_rebuild_seconds;
while (true) {
$cache = $this->_getDBCache($name);
$rebuilding = $this->_getDBCache($name . '_rebuilding');
if ( ($cache === false) && (!$rebuilding || $wait_seconds == 0) ) {
// cache missing and nobody rebuilding it -> rebuild; enough waiting for cache to be ready
return false;
}
elseif ( $cache !== false ) {
// cache present -> return it
return $cache;
}
$wait_seconds -= kCache::WAIT_STEP;
sleep(kCache::WAIT_STEP);
}
return false;
}
/**
* Returns value from database cache
*
* @param string $name key name
* @return mixed
* @access protected
*/
protected function _getDBCache($name)
{
$this->Conn->nextQueryCachable = true;
$sql = 'SELECT Data, Cached, LifeTime
FROM ' . TABLE_PREFIX . 'Cache
WHERE VarName = ' . $this->Conn->qstr($name);
$data = $this->Conn->GetRow($sql);
if ($data) {
$lifetime = (int)$data['LifeTime']; // in seconds
if (($lifetime > 0) && ($data['Cached'] + $lifetime < adodb_mktime())) {
// delete expired
$this->Conn->nextQueryCachable = true;
$sql = 'DELETE FROM ' . TABLE_PREFIX . 'Cache
WHERE VarName = ' . $this->Conn->qstr($name);
$this->Conn->Query($sql);
return false;
}
return $data['Data'];
}
return false;
}
/**
* Sets value to database cache
*
* @param string $name
* @param mixed $value
* @param int|bool $expiration
* @access public
*/
public function setDBCache($name, $value, $expiration = false)
{
$this->deleteDBCache($name . '_rebuilding');
$this->_setDBCache($name, $value, $expiration);
}
/**
* Sets value to database cache
*
* @param string $name
* @param mixed $value
* @param int|bool $expiration
* @access protected
*/
protected function _setDBCache($name, $value, $expiration = false)
{
if ((int)$expiration <= 0) {
$expiration = -1;
}
$fields_hash = Array (
'VarName' => $name,
'Data' => &$value,
'Cached' => adodb_mktime(),
'LifeTime' => (int)$expiration,
);
$this->Conn->nextQueryCachable = true;
$this->Conn->doInsert($fields_hash, TABLE_PREFIX . 'Cache', 'REPLACE');
}
/**
* Sets rebuilding mode for given cache
*
* @param string $name
* @param int $mode
* @param int $max_rebuilding_time
*/
public function rebuildDBCache($name, $mode = null, $max_rebuilding_time = 0)
{
if ( !isset($mode) || $mode == kCache::REBUILD_NOW ) {
$this->_setDBCache($name . '_rebuilding', 1, $max_rebuilding_time);
$this->deleteDBCache($name . '_rebuild');
}
elseif ( $mode == kCache::REBUILD_LATER ) {
$this->_setDBCache($name . '_rebuild', 1, 0);
$this->deleteDBCache($name . '_rebuilding');
}
}
/**
* Deletes key from database cache
*
* @param string $name
* @access public
*/
public function deleteDBCache($name)
{
$sql = 'DELETE FROM ' . TABLE_PREFIX . 'Cache
WHERE VarName = ' . $this->Conn->qstr($name);
$this->Conn->Query($sql);
}
/**
* 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
* @access public
*/
public function incrementCacheSerial($prefix, $id = null, $increment = true)
{
$pascal_case_prefix = implode('', array_map('ucfirst', explode('-', $prefix)));
$serial_name = $pascal_case_prefix . (isset($id) ? 'IDSerial:' . $id : 'Serial');
if ($increment) {
if (defined('DEBUG_MODE') && DEBUG_MODE && $this->Application->isDebugMode()) {
$this->Application->Debugger->appendHTML('Incrementing serial: <strong>' . $serial_name . '</strong>.');
}
$this->setCache($serial_name, (int)$this->getCache($serial_name) + 1);
if (!defined('IS_INSTALL') || !IS_INSTALL) {
// delete cached mod-rewrite urls related to given prefix and id
$delete_clause = isset($id) ? $prefix . ':' . $id : $prefix;
$sql = 'DELETE FROM ' . TABLE_PREFIX . 'CachedUrls
WHERE Prefixes LIKE ' . $this->Conn->qstr('%|' . $delete_clause . '|%');
$this->Conn->Query($sql);
}
}
return $serial_name;
}
/**
* Returns cached category informaton 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)
{
$serial_name = '[%CIDSerial:' . $category_id . '%]';
$cache_key = $name . $serial_name;
$ret = $this->getCache($cache_key);
if ($ret === false) {
if (!$category_id) {
// don't query database for "Home" category (ID = 0), because it doesn't exist in database
return false;
}
// this allows to save 2 sql queries for each category
$this->Conn->nextQueryCachable = true;
$sql = 'SELECT NamedParentPath, CachedTemplate, TreeLeft, TreeRight
FROM ' . TABLE_PREFIX . 'Category
WHERE CategoryId = ' . (int)$category_id;
$category_data = $this->Conn->GetRow($sql);
if ($category_data !== false) {
// only direct links to category pages work (symlinks, container pages and so on won't work)
$this->setCache('filenames' . $serial_name, $category_data['NamedParentPath']);
$this->setCache('category_designs' . $serial_name, ltrim($category_data['CachedTemplate'], '/'));
$this->setCache('category_tree' . $serial_name, $category_data['TreeLeft'] . ';' . $category_data['TreeRight']);
}
}
return $this->getCache($cache_key);
}
}
\ No newline at end of file
Index: branches/5.2.x/core/units/custom_fields/custom_fields_event_handler.php
===================================================================
--- branches/5.2.x/core/units/custom_fields/custom_fields_event_handler.php (revision 14887)
+++ branches/5.2.x/core/units/custom_fields/custom_fields_event_handler.php (revision 14888)
@@ -1,347 +1,347 @@
<?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 CustomFieldsEventHandler extends kDBEventHandler {
/**
* Changes permission section to one from REQUEST, not from config
*
* @param kEvent $event
* @return bool
* @access public
*/
public function CheckPermission(&$event)
{
$sql = 'SELECT Prefix
FROM '.TABLE_PREFIX.'ItemTypes
WHERE ItemType = '.$this->Conn->qstr( $this->Application->GetVar('cf_type') );
$main_prefix = $this->Conn->GetOne($sql);
$section = $this->Application->getUnitOption($main_prefix.'.custom', 'PermSection');
$event->setEventParam('PermSection', $section);
return parent::CheckPermission($event);
}
/**
* Apply any custom changes to list's sql query
*
* @param kEvent $event
* @return void
* @access protected
* @see kDBEventHandler::OnListBuild()
*/
protected function SetCustomQuery(&$event)
{
$object =& $event->getObject();
/* @var $object kDBList */
$item_type = $this->Application->GetVar('cf_type');
if (!$item_type) {
$prefix = $event->getEventParam('SourcePrefix');
$item_type = $this->Application->getUnitOption($prefix, 'ItemType');
}
if ($event->Special == 'general') {
$object->addFilter('generaltab_filter', '%1$s.OnGeneralTab = 1');
}
if ($item_type) {
- $hidden_fields = array_map(Array(&$this->Conn, 'qstr'), $this->_getHiddenFields($event));
+ $hidden_fields = $this->Conn->qstrArray($this->_getHiddenFields($event));
if ($hidden_fields) {
$object->addFilter('hidden_filter', '%1$s.FieldName NOT IN (' . implode(',', $hidden_fields) . ')');
}
$object->addFilter('itemtype_filter', '%1$s.Type = '.$item_type);
}
if (!($this->Application->isDebugMode() && $this->Application->isAdminUser)) {
$object->addFilter('user_filter', '%1$s.IsSystem = 0');
}
}
/**
* Returns prefix, that custom fields are printed for
*
* @param kEvent $event
* @return string
*/
function _getSourcePrefix(&$event)
{
$prefix = $event->getEventParam('SourcePrefix');
if (!$prefix) {
$sql = 'SELECT Prefix
FROM ' . TABLE_PREFIX . 'ItemTypes
WHERE ItemType = ' . $this->Conn->qstr( $this->Application->GetVar('cf_type') );
$prefix = $this->Conn->GetOne($sql);
}
return $prefix;
}
/**
* Get custom fields, that should no be shown anywhere
*
* @param kEvent $event
* @return Array
* @access protected
*/
protected function _getHiddenFields(&$event)
{
$prefix = $this->_getSourcePrefix($event);
$hidden_fields = Array ();
$virtual_fields = $this->Application->getUnitOption($prefix, 'VirtualFields', Array ());
$custom_fields = $this->Application->getUnitOption($prefix, 'CustomFields', Array ());
/* @var $custom_fields Array */
foreach ($custom_fields as $custom_field) {
$check_field = 'cust_' . $custom_field;
$show_mode = array_key_exists('show_mode', $virtual_fields[$check_field]) ? $virtual_fields[$check_field]['show_mode'] : true;
if ( ($show_mode === false) || (($show_mode === smDEBUG) && !(defined('DEBUG_MODE') && DEBUG_MODE)) ) {
$hidden_fields[] = $custom_field;
}
}
return $hidden_fields;
}
/**
* Prevents from duplicate item creation
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnBeforeItemCreate(&$event)
{
parent::OnBeforeItemCreate($event);
$object =& $event->getObject();
/* @var $object kDBItem */
$sql = 'SELECT COUNT(*)
FROM ' . $this->Application->getUnitOption($event->Prefix, 'TableName') . '
WHERE FieldName = ' . $this->Conn->qstr($object->GetDBField('FieldName')) . ' AND Type = ' . $object->GetDBField('Type');
$found = $this->Conn->GetOne($sql);
if ( $found ) {
$event->status = kEvent::erFAIL;
$object->SetError('FieldName', 'duplicate', 'la_error_CustomExists');
}
}
/**
* Occurs after deleting item, id of deleted item
* is stored as 'id' param of event
*
* @param kEvent $event
* @access public
*/
function OnAfterItemDelete(&$event)
{
$object =& $event->getObject();
/* @var $object kDBItem */
$main_prefix = $this->getPrefixByItemType( $object->GetDBField('Type') );
$ml_helper =& $this->Application->recallObject('kMultiLanguageHelper');
/* @var $ml_helper kMultiLanguageHelper */
// call main item config to clone cdata table
$this->Application->getUnitOption($main_prefix, 'TableName');
$ml_helper->deleteField($main_prefix . '-cdata', $event->getEventParam('id'));
}
/**
* Get config prefix based on item type
*
* @param int $item_type
* @return string
* @access protected
*/
protected function getPrefixByItemType($item_type)
{
$sql = 'SELECT Prefix
FROM ' . TABLE_PREFIX . 'ItemTypes
WHERE ItemType = ' . $item_type;
return $this->Conn->GetOne($sql);
}
/**
* Creates new database columns, once custom field is successfully created
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnSaveCustomField(&$event)
{
if ( $event->MasterEvent->status != kEvent::erSUCCESS ) {
return ;
}
$object =& $event->getObject();
/* @var $object kDBItem */
$main_prefix = $this->getPrefixByItemType($object->GetDBField('Type'));
$ml_helper =& $this->Application->recallObject('kMultiLanguageHelper');
/* @var $ml_helper kMultiLanguageHelper */
// call main item config to clone cdata table
define('CUSTOM_FIELD_ADDED', 1); // used in cdata::scanCustomFields method
$this->Application->getUnitOption($main_prefix, 'TableName');
$ml_helper->createFields($main_prefix . '-cdata');
}
/**
* 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(&$event)
{
parent::OnMassDelete($event);
$event->SetRedirectParam('opener', 's');
}
/**
* 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(&$event)
{
parent::OnPreCreate($event);
$object =& $event->getObject();
/* @var $object kDBItem */
$object->SetDBField('Type', $this->Application->GetVar('cf_type'));
}
/**
* Prepares ValueList field's value as xml for editing
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnAfterItemLoad(&$event)
{
parent::OnAfterItemLoad($event);
$object =& $event->getObject();
/* @var $object kDBItem */
if ( !in_array($object->GetDBField('ElementType'), $this->_getMultiElementTypes()) ) {
return ;
}
$custom_field_helper =& $this->Application->recallObject('InpCustomFieldsHelper');
/* @var $custom_field_helper InpCustomFieldsHelper */
$options = $custom_field_helper->GetValuesHash($object->GetDBField('ValueList'), VALUE_LIST_SEPARATOR, false);
$records = Array ();
$option_key = key($options);
if ( $option_key === '' || $option_key == 0 ) {
// remove 1st empty option, and add it later, when options will be saved, but allow string option keys
unset($options[$option_key]); // keep index, don't use array_unshift!
}
foreach ($options as $option_key => $option_title) {
$records[] = Array ('OptionKey' => $option_key, 'OptionTitle' => $option_title);
}
$minput_helper =& $this->Application->recallObject('MInputHelper');
/* @var $minput_helper MInputHelper */
$xml = $minput_helper->prepareMInputXML($records, Array ('OptionKey', 'OptionTitle'));
$object->SetDBField('Options', $xml);
}
/**
* Returns custom field element types, that will use minput control
*
* @return Array
* @access protected
*/
protected function _getMultiElementTypes()
{
return Array ('select', 'multiselect', 'radio');
}
/**
* Saves minput content to ValueList field
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnBeforeItemUpdate(&$event)
{
parent::OnBeforeItemUpdate($event);
$object =& $event->getObject();
/* @var $object kDBItem */
if ( !in_array($object->GetDBField('ElementType'), $this->_getMultiElementTypes()) ) {
return ;
}
$minput_helper =& $this->Application->recallObject('MInputHelper');
/* @var $minput_helper MInputHelper */
$ret = $object->GetDBField('ElementType') == 'select' ? Array ('' => '=+') : Array ();
$records = $minput_helper->parseMInputXML($object->GetDBField('Options'));
if ( $object->GetDBField('SortValues') ) {
usort($records, Array (&$this, '_sortValues'));
ksort($records);
}
foreach ($records as $record) {
if ( substr($record['OptionKey'], 0, 3) == 'SQL' ) {
$ret[] = $record['OptionTitle'];
}
else {
$ret[] = $record['OptionKey'] . '=' . $record['OptionTitle'];
}
}
$object->SetDBField('ValueList', implode(VALUE_LIST_SEPARATOR, $ret));
}
function _sortValues($record_a, $record_b)
{
return strcasecmp($record_a['OptionTitle'], $record_b['OptionTitle']);
}
}
\ No newline at end of file
Index: branches/5.2.x/core/units/helpers/search_helper.php
===================================================================
--- branches/5.2.x/core/units/helpers/search_helper.php (revision 14887)
+++ branches/5.2.x/core/units/helpers/search_helper.php (revision 14888)
@@ -1,798 +1,798 @@
<?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
}
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)
{
$object =& $event->getObject();
/* @var $object kDBItem */
// 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();
$object =& $event->getObject();
/* @var $object kDBList */
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) {
list ($filter_type, $field_value) = each($field_options);
$is_empty = strlen(is_array($field_value) ? implode('', $field_value) : $field_value) == 0;
if ($is_empty) {
if (isset($custom_filter[$field_name])) {
// use isset, because non-existing key will cause "php notice"!
unset($custom_filter[$field_name][$filter_type]); // remove filter
if (!$custom_filter[$field_name]) {
// if no filters left for field, then delete record at all
unset($custom_filter[$field_name]);
}
}
}
else {
$custom_filter[$field_name][$filter_type]['submit_value'] = $field_value;
}
}
}
}
if ($custom_filter) {
$custom_filters[$grid_name] = $custom_filter;
}
else {
unset($custom_filters[$grid_name]);
}
// update "custom filter" with values from submit: end
if (!$custom_filter) {
// in case when no filters specified, there are nothing to process
$this->Application->StorePersistentVar($event->getPrefixSpecial().'_custom_filter.'.$view_name, serialize($custom_filters) );
return false;
}
$object =& $event->getObject(); // don't recall it each time in getCustomFilterSearchClause
$grid_info = $this->Application->getUnitOption($event->Prefix.'.'.$grid_name, 'Grids');
foreach ($custom_filter as $field_name => $field_options) {
list ($filter_type, $field_options) = each($field_options);
$field_options['grid_options'] = $grid_info['Fields'][$field_name];
$field_options = $this->getCustomFilterSearchClause($object, $field_name, $filter_type, $field_options);
if ($field_options['value']) {
unset($field_options['grid_options']);
$custom_filter[$field_name][$filter_type] = $field_options;
}
}
$custom_filters[$grid_name] = $custom_filter;
$this->Application->StorePersistentVar($event->getPrefixSpecial().'_custom_filter.'.$view_name, serialize($custom_filters) );
return $custom_filter;
}
/**
* 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) {
list ($filter_type, $field_options) = each($field_options);
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;
}
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 ($from !== false && $to === false) {
$from = strtotime(date('Y-m-d', $from) . ' 00:00:00', $from); // reset to morning
$to = $from + $day_seconds;
}
elseif ($from === false && $to !== false) {
$to = strtotime(date('Y-m-d', $to) . ' 23:59:59', $to); // reset to evening
$from = $to - $day_seconds;
}
if ($from !== false && $to !== false) {
$filter_value = $table_name.'`'.$field_name.'` >= '.$from.' AND '.$table_name.'`'.$field_name.'` <= '.$to;
}
break;
case 'equals':
case 'options':
$field_value = strlen($field_options['submit_value']) ? $this->Conn->qstr($field_options['submit_value']) : false;
if ($field_value) {
$filter_value = $table_name.'`'.$field_name.'` = '.$field_value;
}
break;
case 'picker':
$field_value = strlen($field_options['submit_value']) ? $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 = strlen($field_options['submit_value']) ? $this->Conn->escape($field_options['submit_value']) : false;
if ($field_value) {
$field_options2 = $object->GetFieldOptions($field_name);
$multiple = array_key_exists('multiple', $field_options2) && $field_options2['multiple'];
$field_value = explode('|', substr($field_value, 1, -1));
- $field_value = array_map(Array (&$this->Conn, 'escape'), $field_value);
+ $field_value = $this->Conn->qstrArray($field_value, 'escape');
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
*/
function processRangeField(&$object, $search_field, $value, $type)
{
if ( !strlen($value[$type]) ) {
return false;
}
$options = $object->GetFieldOptions($search_field);
$dt_separator = array_key_exists('date_time_separator', $options) ? $options['date_time_separator'] : ' ';
$value[$type] = trim($value[$type], $dt_separator); // trim any
$tmp_value = explode($dt_separator, $value[$type], 2);
if ( count($tmp_value) == 1 ) {
$time_format = $this->_getInputTimeFormat($options);
if ( $time_format ) {
// time is missing, but time format available -> guess time and add to date
$time = ($type == 'from') ? adodb_mktime(0, 0, 0) : adodb_mktime(23, 59, 59);
$time = adodb_date($time_format, $time);
$value[$type] .= $dt_separator . $time;
}
}
$formatter =& $this->Application->recallObject($options['formatter']);
/* @var $formatter kFormatter */
$value_ts = $formatter->Parse($value[$type], $search_field, $object);
if ( $object->GetErrorPseudo($search_field) ) {
// invalid format -> ignore this date in search
$object->RemoveError($search_field);
return false;
}
return $value_ts;
}
/**
* Returns InputTimeFormat using given field options
*
* @param Array $field_options
* @return string
*/
function _getInputTimeFormat($field_options)
{
if ( array_key_exists('input_time_format', $field_options) ) {
return $field_options['input_time_format'];
}
$lang_current =& $this->Application->recallObject('lang.current');
/* @var $lang_current LanguagesItem */
return $lang_current->GetDBField('InputTimeFormat');
}
/**
* Resets current search
*
* @param kEvent $event
*/
function resetSearch(&$event)
{
$this->Application->RemoveVar($event->getPrefixSpecial().'_search_filter');
$this->Application->RemoveVar($event->getPrefixSpecial().'_search_keyword');
$view_name = $this->Application->RecallVar($event->getPrefixSpecial().'_current_view');
$this->Application->RemovePersistentVar($event->getPrefixSpecial().'_custom_filter.'.$view_name);
}
/**
* Creates filters based on "types" & "except" parameters from PrintList
*
* @param kEvent $event
* @param Array $type_clauses
* @param string $types
* @param string $except_types
*/
function SetComplexFilter(&$event, &$type_clauses, $types, $except_types)
{
$includes_or_filter =& $this->Application->makeClass('kMultipleFilter', Array (kDBList::FLT_TYPE_OR));
/* @var $includes_or_filter kMultipleFilter */
$excepts_and_filter =& $this->Application->makeClass('kMultipleFilter', Array (kDBList::FLT_TYPE_AND));
/* @var $excepts_and_filter kMultipleFilter */
$includes_or_filter_h =& $this->Application->makeClass('kMultipleFilter', Array (kDBList::FLT_TYPE_OR));
/* @var $includes_or_filter_h kMultipleFilter */
$excepts_and_filter_h =& $this->Application->makeClass('kMultipleFilter', Array (kDBList::FLT_TYPE_AND));
/* @var $excepts_and_filter_h kMultipleFilter */
if ( $types ) {
$types = explode(',', $types);
foreach ($types as $type) {
$type = trim($type);
if ( isset($type_clauses[$type]) ) {
if ( $type_clauses[$type]['having_filter'] ) {
$includes_or_filter_h->addFilter('filter_' . $type, $type_clauses[$type]['include']);
}
else {
$includes_or_filter->addFilter('filter_' . $type, $type_clauses[$type]['include']);
}
}
}
}
if ( $except_types ) {
$except_types = explode(',', $except_types);
foreach ($except_types as $type) {
$type = trim($type);
if ( isset($type_clauses[$type]) ) {
if ( $type_clauses[$type]['having_filter'] ) {
$excepts_and_filter_h->addFilter('filter_' . $type, $type_clauses[$type]['except']);
}
else {
$excepts_and_filter->addFilter('filter_' . $type, $type_clauses[$type]['except']);
}
}
}
}
$object =& $event->getObject();
/* @var $object kDBList */
$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);
}
}
\ No newline at end of file
Index: branches/5.2.x/core/units/helpers/language_import_helper.php
===================================================================
--- branches/5.2.x/core/units/helpers/language_import_helper.php (revision 14887)
+++ branches/5.2.x/core/units/helpers/language_import_helper.php (revision 14888)
@@ -1,1104 +1,1104 @@
<?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.
*/
/**
* Language pack format version description
*
* v1
* ==========
* All language properties are separate nodes inside <LANGUAGE> node. There are
* two more nodes PHRASES and EVENTS for phrase and email event translations.
*
* v2
* ==========
* All data, that will end up in Language table is now attributes of LANGUAGE node
* and is name exactly as field name, that will be used to store that data.
*
* v4
* ==========
* Hint & Column translation added to each phrase translation
*/
defined('FULL_PATH') or die('restricted access!');
define('LANG_OVERWRITE_EXISTING', 1);
define('LANG_SKIP_EXISTING', 2);
class LanguageImportHelper extends kHelper {
/**
* Current Language in import
*
* @var LanguagesItem
*/
var $lang_object = null;
/**
* Current user's IP address
*
* @var string
*/
var $ip_address = '';
/**
* Event type + name mapping to id (from system)
*
* @var Array
*/
var $events_hash = Array ();
/**
* Language pack import mode
*
* @var int
*/
var $import_mode = LANG_SKIP_EXISTING;
/**
* Language IDs, that were imported
*
* @var Array
*/
var $_languages = Array ();
/**
* Temporary table names to perform import on
*
* @var Array
*/
var $_tables = Array ();
/**
* Phrase types allowed for import/export operations
*
* @var Array
*/
var $phrase_types_allowed = Array ();
/**
* Encoding, used for language pack exporting
*
* @var string
*/
var $_exportEncoding = 'base64';
/**
* Exported data limits (all or only specified ones)
*
* @var Array
*/
var $_exportLimits = Array (
'phrases' => false,
'emailevents' => false,
);
/**
* Debug language pack import process
*
* @var bool
*/
var $_debugMode = false;
/**
* Latest version of language pack format. Versions are not backwards compatible!
*
* @var int
*/
var $_latestVersion = 4;
/**
* Prefix-based serial numbers, that should be changed after import is finished
*
* @var Array
*/
var $changedPrefixes = Array ();
public function __construct()
{
parent::__construct();
// "core/install/english.lang", phrase count: 3318, xml parse time on windows: 10s, insert time: 0.058s
set_time_limit(0);
ini_set('memory_limit', -1);
$this->lang_object =& $this->Application->recallObject('lang.import', null, Array ('skip_autoload' => true));
if (!(defined('IS_INSTALL') && IS_INSTALL)) {
// perform only, when not in installation mode
$this->_updateEventsCache();
}
$this->ip_address = getenv('HTTP_X_FORWARDED_FOR') ? getenv('HTTP_X_FORWARDED_FOR') : getenv('REMOTE_ADDR');
// $this->_debugMode = $this->Application->isDebugMode();
}
/**
* Performs import of given language pack (former Parse method)
*
* @param string $filename
* @param string $phrase_types
* @param Array $module_ids
* @param int $import_mode
* @return bool
*/
function performImport($filename, $phrase_types, $module_ids, $import_mode = LANG_SKIP_EXISTING)
{
// define the XML parsing routines/functions to call based on the handler path
if (!file_exists($filename) || !$phrase_types /*|| !$module_ids*/) {
return false;
}
if ($this->_debugMode) {
$start_time = microtime(true);
$this->Application->Debugger->appendHTML(__CLASS__ . '::' . __FUNCTION__ . '("' . $filename . '")');
}
if (defined('IS_INSTALL') && IS_INSTALL) {
// new events could be added during module upgrade
$this->_updateEventsCache();
}
$this->_initImportTables();
$phrase_types = explode('|', substr($phrase_types, 1, -1) );
// $module_ids = explode('|', substr($module_ids, 1, -1) );
$this->phrase_types_allowed = array_flip($phrase_types);
$this->import_mode = $import_mode;
$this->_parseXML($filename);
// copy data from temp tables to live
foreach ($this->_languages as $language_id) {
$this->_performUpgrade($language_id, 'phrases', 'PhraseKey', Array ('l%s_Translation', 'l%s_HintTranslation', 'l%s_ColumnTranslation', 'PhraseType'));
$this->_performUpgrade($language_id, 'emailevents', 'EventId', Array ('l%s_Subject', 'Headers', 'MessageType', 'l%s_Body'));
$this->_performUpgrade($language_id, 'country-state', 'CountryStateId', Array ('l%s_Name'));
}
$this->_initImportTables(true);
$this->changedPrefixes = array_unique($this->changedPrefixes);
foreach ($this->changedPrefixes as $prefix) {
$this->Application->incrementCacheSerial($prefix);
}
if ($this->_debugMode) {
$this->Application->Debugger->appendHTML(__CLASS__ . '::' . __FUNCTION__ . '("' . $filename . '"): ' . (microtime(true) - $start_time));
}
return true;
}
/**
* Creates XML file with exported language data (former Create method)
*
* @param string $filename filename to export into
* @param Array $phrase_types phrases types to export from modules passed in $module_ids
* @param Array $language_ids IDs of languages to export
* @param Array $module_ids IDs of modules to export phrases from
*/
function performExport($filename, $phrase_types, $language_ids, $module_ids)
{
$fp = fopen($filename,'w');
if (!$fp || !$phrase_types || !$module_ids || !$language_ids) {
return false;
}
$phrase_types = explode('|', substr($phrase_types, 1, -1) );
$module_ids = explode('|', substr($module_ids, 1, -1) );
$ret = '<LANGUAGES Version="' . $this->_latestVersion . '">' . "\n";
$export_fields = $this->_getExportFields();
$email_message_helper =& $this->Application->recallObject('EmailMessageHelper');
/* @var $email_message_helper EmailMessageHelper */
// get languages
$sql = 'SELECT *
FROM ' . $this->Application->getUnitOption('lang','TableName') . '
WHERE LanguageId IN (' . implode(',', $language_ids) . ')';
$languages = $this->Conn->Query($sql, 'LanguageId');
// get phrases
$phrase_modules = $module_ids;
array_push($phrase_modules, ''); // for old language packs without module
- $phrase_modules = array_map(Array (&$this->Conn, 'qstr'), $phrase_modules);
+ $phrase_modules = $this->Conn->qstrArray($phrase_modules);
// apply phrase selection limit
if ($this->_exportLimits['phrases']) {
- $escaped_phrases = array_map(Array (&$this->Conn, 'qstr'), $this->_exportLimits['phrases']);
+ $escaped_phrases = $this->Conn->qstrArray($this->_exportLimits['phrases']);
$limit_where = 'Phrase IN (' . implode(',', $escaped_phrases) . ')';
}
else {
$limit_where = 'TRUE';
}
$sql = 'SELECT *
FROM ' . $this->Application->getUnitOption('phrases','TableName') . '
WHERE PhraseType IN (' . implode(',', $phrase_types) . ') AND Module IN (' . implode(',', $phrase_modules) . ') AND ' . $limit_where . '
ORDER BY Phrase';
$phrases = $this->Conn->Query($sql, 'PhraseId');
// email events
$module_sql = preg_replace('/(.*),/U', 'INSTR(Module,\'\\1\') OR ', implode(',', $module_ids) . ',');
// apply event selection limit
if ($this->_exportLimits['emailevents']) {
- $escaped_email_events = array_map(Array (&$this->Conn, 'qstr'), $this->_exportLimits['emailevents']);
+ $escaped_email_events = $this->Conn->qstrArray($this->_exportLimits['emailevents']);
$limit_where = '`Event` IN (' . implode(',', $escaped_email_events) . ')';
}
else {
$limit_where = 'TRUE';
}
$sql = 'SELECT *
FROM ' . $this->Application->getUnitOption('emailevents', 'TableName') . '
WHERE `Type` IN (' . implode(',', $phrase_types) . ') AND (' . substr($module_sql, 0, -4) . ') AND ' . $limit_where . '
ORDER BY `Event`, `Type`';
$events = $this->Conn->Query($sql, 'EventId');
if (in_array('Core', $module_ids)) {
// countries
$sql = 'SELECT *
FROM ' . $this->Application->getUnitOption('country-state', 'TableName') . '
WHERE Type = ' . DESTINATION_TYPE_COUNTRY . '
ORDER BY `IsoCode`';
$countries = $this->Conn->Query($sql, 'CountryStateId');
// states
$sql = 'SELECT *
FROM ' . $this->Application->getUnitOption('country-state', 'TableName') . '
WHERE Type = ' . DESTINATION_TYPE_STATE . '
ORDER BY `IsoCode`';
$states = $this->Conn->Query($sql, 'CountryStateId');
foreach ($states as $state_id => $state_data) {
$country_id = $state_data['StateCountryId'];
if (!array_key_exists('States', $countries[$country_id])) {
$countries[$country_id]['States'] = Array ();
}
$countries[$country_id]['States'][] = $state_id;
}
}
foreach ($languages as $language_id => $language_info) {
// language
$ret .= "\t" . '<LANGUAGE Encoding="' . $this->_exportEncoding . '"';
foreach ($export_fields as $export_field) {
$ret .= ' ' . $export_field . '="' . htmlspecialchars($language_info[$export_field]) . '"';
}
$ret .= '>' . "\n";
// filename replacements
$replacements = $language_info['FilenameReplacements'];
if ($replacements) {
$ret .= "\t\t" . '<REPLACEMENTS>';
$ret .= $this->_exportEncoding == 'base64' ? base64_encode($replacements) : '<![CDATA[' . $replacements . ']]>';
$ret .= '</REPLACEMENTS>' . "\n";
}
// phrases
if ($phrases) {
$ret .= "\t\t" . '<PHRASES>' . "\n";
foreach ($phrases as $phrase_id => $phrase) {
$translation = $phrase['l' . $language_id . '_Translation'];
$hint_translation = $phrase['l' . $language_id . '_HintTranslation'];
$column_translation = $phrase['l' . $language_id . '_ColumnTranslation'];
if (!$translation) {
// phrase is not translated on given language
continue;
}
if ( $this->_exportEncoding == 'base64' ) {
$data = base64_encode($translation);
$hint_translation = base64_encode($hint_translation);
$column_translation = base64_encode($column_translation);
}
else {
$data = '<![CDATA[' . $translation . ']]>';
$hint_translation = htmlspecialchars($hint_translation);
$column_translation = htmlspecialchars($column_translation);
}
$attributes = Array (
'Label="' . $phrase['Phrase'] . '"',
'Module="' . $phrase['Module'] . '"',
'Type="' . $phrase['PhraseType'] . '"'
);
if ( $phrase['l' . $language_id . '_HintTranslation'] ) {
$attributes[] = 'Hint="' . $hint_translation . '"';
}
if ( $phrase['l' . $language_id . '_ColumnTranslation'] ) {
$attributes[] = 'Column="' . $column_translation . '"';
}
$ret .= "\t\t\t" . '<PHRASE ' . implode(' ', $attributes) . '>' . $data . '</PHRASE>' . "\n";
}
$ret .= "\t\t" . '</PHRASES>' . "\n";
}
// email events
if ($events) {
$ret .= "\t\t" . '<EVENTS>' . "\n";
foreach ($events as $event_id => $event) {
$fields_hash = Array (
'Headers' => $event['Headers'],
'Subject' => $event['l' . $language_id . '_Subject'],
'Body' => $event['l' . $language_id . '_Body'],
);
$template = $email_message_helper->buildTemplate($fields_hash);
if (!$template) {
// email event is not translated on given language
continue;
}
$data = $this->_exportEncoding == 'base64' ? base64_encode($template) : '<![CDATA[' . $template . ']]>';
$ret .= "\t\t\t" . '<EVENT MessageType="' . $event['MessageType'] . '" Event="' . $event['Event'] . '" Type="' . $event['Type'] . '">' . $data . '</EVENT>'."\n";
}
$ret .= "\t\t" . '</EVENTS>' . "\n";
}
if (in_array('Core', $module_ids) && $countries) {
$ret .= "\t\t" . '<COUNTRIES>' . "\n";
foreach ($countries as $country_id => $country_data) {
$translation = $country_data['l' . $language_id . '_Name'];
if (!$translation) {
// country is not translated on given language
continue;
}
$data = $this->_exportEncoding == 'base64' ? base64_encode($translation) : $translation;
if (array_key_exists('States', $country_data)) {
$ret .= "\t\t\t" . '<COUNTRY Iso="' . $country_data['IsoCode'] . '" Translation="' . $data . '">' . "\n";
foreach ($country_data['States'] as $state_id) {
$translation = $states[$state_id]['l' . $language_id . '_Name'];
if (!$translation) {
// state is not translated on given language
continue;
}
$data = $this->_exportEncoding == 'base64' ? base64_encode($translation) : $translation;
$ret .= "\t\t\t\t" . '<STATE Iso="' . $states[$state_id]['IsoCode'] . '" Translation="' . $data . '"/>' . "\n";
}
$ret .= "\t\t\t" . '</COUNTRY>' . "\n";
}
else {
$ret .= "\t\t\t" . '<COUNTRY Iso="' . $country_data['IsoCode'] . '" Translation="' . $data . '"/>' . "\n";
}
}
$ret .= "\t\t" . '</COUNTRIES>' . "\n";
}
$ret .= "\t" . '</LANGUAGE>' . "\n";
}
$ret .= '</LANGUAGES>';
fwrite($fp, $ret);
fclose($fp);
return true;
}
/**
* Sets language pack encoding (not charset) used during export
*
* @param string $encoding
*/
function setExportEncoding($encoding)
{
$this->_exportEncoding = $encoding;
}
/**
* Sets language pack data limits for export
*
* @param mixed $phrases
* @param mixed $email_events
*/
function setExportLimits($phrases, $email_events)
{
if (!is_array($phrases)) {
$phrases = str_replace(',', "\n", $phrases);
$phrases = preg_replace("/\n+/", "\n", str_replace("\r", '', trim($phrases)));
$phrases = $phrases ? array_map('trim', explode("\n", $phrases)) : Array ();
}
if (!is_array($email_events)) {
$email_events = str_replace(',', "\n", $email_events);
$email_events = preg_replace("/\n+/", "\n", str_replace("\r", '', trim($email_events)));
$email_events = $email_events ? array_map('trim', explode("\n", $email_events)) : Array ();
}
$this->_exportLimits = Array ('phrases' => $phrases, 'emailevents' => $email_events);
}
/**
* Performs upgrade of given language pack part
*
* @param int $language_id
* @param string $prefix
* @param string $unique_field
* @param Array $data_fields
*/
function _performUpgrade($language_id, $prefix, $unique_field, $data_fields)
{
$live_records = $this->_getTableData($language_id, $prefix, $unique_field, $data_fields[0], false);
$temp_records = $this->_getTableData($language_id, $prefix, $unique_field, $data_fields[0], true);
if (!$temp_records) {
// no data for given language
return ;
}
// perform insert for records, that are missing in live table
$to_insert = array_diff($temp_records, $live_records);
if ($to_insert) {
- $to_insert = array_map(Array (&$this->Conn, 'qstr'), $to_insert);
+ $to_insert = $this->Conn->qstrArray($to_insert);
$sql = 'INSERT INTO ' . $this->Application->getUnitOption($prefix, 'TableName') . '
SELECT *
FROM ' . $this->_tables[$prefix] . '
WHERE ' . $unique_field . ' IN (' . implode(',', $to_insert) . ')';
$this->Conn->Query($sql);
// new records were added
$this->changedPrefixes[] = $prefix;
}
// perform update for records, that are present in live table
$to_update = array_diff($temp_records, $to_insert);
if ($to_update) {
- $to_update = array_map(Array (&$this->Conn, 'qstr'), $to_update);
+ $to_update = $this->Conn->qstrArray($to_update);
$sql = 'UPDATE ' . $this->Application->getUnitOption($prefix, 'TableName') . ' live
SET ';
foreach ($data_fields as $index => $data_field) {
$data_field = sprintf($data_field, $language_id);
$sql .= ' live.' . $data_field . ' = (
SELECT temp' . $index . '.' . $data_field . '
FROM ' . $this->_tables[$prefix] . ' temp' . $index . '
WHERE temp' . $index . '.' . $unique_field . ' = live.' . $unique_field . '
),';
}
$sql = substr($sql, 0, -1); // cut last comma
$where_clause = Array (
// this won't make any difference, but just in case
$unique_field . ' IN (' . implode(',', $to_update) . ')',
);
if ($this->import_mode == LANG_SKIP_EXISTING) {
// empty OR not set
$data_field = sprintf($data_fields[0], $language_id);
$where_clause[] = '(' . $data_field . ' = "") OR (' . $data_field . ' IS NULL)';
}
if ($where_clause) {
$sql .= "\n" . 'WHERE (' . implode(') AND (', $where_clause) . ')';
}
$this->Conn->Query($sql);
if ($this->Conn->getAffectedRows() > 0) {
// existing records were updated
$this->changedPrefixes[] = $prefix;
}
}
}
/**
* Returns data from given table used for language pack upgrade
*
* @param int $language_id
* @param string $prefix
* @param string $unique_field
* @param string $data_field
* @param bool $temp_mode
* @return Array
*/
function _getTableData($language_id, $prefix, $unique_field, $data_field, $temp_mode = false)
{
$data_field = sprintf($data_field, $language_id);
$table_name = $this->Application->getUnitOption($prefix, 'TableName');
if ($temp_mode) {
// for temp table get only records, that have contents on given language (not empty and isset)
$sql = 'SELECT ' . $unique_field . '
FROM ' . $this->Application->GetTempName($table_name, 'prefix:' . $prefix) . '
WHERE (' . $data_field . ' <> "") AND (' . $data_field . ' IS NOT NULL)';
}
else {
// for live table get all records, no matter on what language
$sql = 'SELECT ' . $unique_field . '
FROM ' . $table_name;
}
return $this->Conn->GetCol($sql);
}
function _parseXML($filename)
{
if ($this->_debugMode) {
$start_time = microtime(true);
$this->Application->Debugger->appendHTML(__CLASS__ . '::' . __FUNCTION__ . '("' . $filename . '")');
}
$fdata = file_get_contents($filename);
$xml_parser =& $this->Application->recallObject('kXMLHelper');
/* @var $xml_parser kXMLHelper */
$root_node =& $xml_parser->Parse($fdata);
if (!is_object($root_node) || !is_a($root_node, 'kXMLNode')) {
// invalid language pack contents
return false;
}
if ($root_node->Children) {
$this->_processLanguages($root_node->firstChild);
}
if ($this->_debugMode) {
$this->Application->Debugger->appendHTML(__CLASS__ . '::' . __FUNCTION__ . '("' . $filename . '"): ' . (microtime(true) - $start_time));
}
return true;
}
/**
* Creates temporary tables, used during language import
*
* @param bool $drop_only
*/
function _initImportTables($drop_only = false)
{
$this->_tables['phrases'] = $this->_prepareTempTable('phrases', $drop_only);
$this->_tables['emailevents'] = $this->_prepareTempTable('emailevents', $drop_only);
$this->_tables['country-state'] = $this->_prepareTempTable('country-state', $drop_only);
}
/**
* Create temp table for prefix, if table already exists, then delete it and create again
*
* @param string $prefix
* @param bool $drop_only
* @return string Name of created temp table
* @access protected
*/
protected function _prepareTempTable($prefix, $drop_only = false)
{
$id_field = $this->Application->getUnitOption($prefix, 'IDField');
$table = $this->Application->getUnitOption($prefix,'TableName');
$temp_table = $this->Application->GetTempName($table);
$sql = 'DROP TABLE IF EXISTS %s';
$this->Conn->Query( sprintf($sql, $temp_table) );
if (!$drop_only) {
$sql = 'CREATE TABLE ' . $temp_table . ' SELECT * FROM ' . $table . ' WHERE 0';
$this->Conn->Query($sql);
$sql = 'ALTER TABLE %1$s CHANGE %2$s %2$s INT(11) NOT NULL DEFAULT "0"';
$this->Conn->Query( sprintf($sql, $temp_table, $id_field) );
switch ($prefix) {
case 'phrases':
$unique_field = 'PhraseKey';
break;
case 'emailevents':
$unique_field = 'EventId';
break;
case 'country-state':
$unique_field = 'CountryStateId';
break;
default:
throw new Exception('Unknown prefix "<strong>' . $prefix . '</strong>" during language pack import');
break;
}
$sql = 'ALTER TABLE ' . $temp_table . ' ADD UNIQUE (' . $unique_field . ')';
$this->Conn->Query($sql);
}
return $temp_table;
}
/**
* Prepares mapping between event name+type and their ids in database
*
*/
function _updateEventsCache()
{
$sql = 'SELECT EventId, CONCAT(Event,"_",Type) AS EventMix
FROM ' . TABLE_PREFIX . 'Events';
$this->events_hash = $this->Conn->GetCol($sql, 'EventMix');
}
/**
* Returns language fields to be exported
*
* @return Array
*/
function _getExportFields()
{
return Array (
'PackName', 'LocalName', 'DateFormat', 'TimeFormat', 'InputDateFormat', 'InputTimeFormat',
'DecimalPoint', 'ThousandSep', 'Charset', 'UnitSystem', 'Locale', 'UserDocsUrl'
);
}
/**
* Processes parsed XML
*
* @param kXMLNode $language_node
*/
function _processLanguages(&$language_node)
{
if (array_key_exists('VERSION', $language_node->Parent->Attributes)) {
// version present -> use it
$version = $language_node->Parent->Attributes['VERSION'];
}
else {
// version missing -> guess it
if (is_object($language_node->FindChild('DATEFORMAT'))) {
$version = 1;
}
elseif (array_key_exists('CHARSET', $language_node->Attributes)) {
$version = 2;
}
}
if ($version == 1) {
$field_mapping = Array (
'DATEFORMAT' => 'DateFormat',
'TIMEFORMAT' => 'TimeFormat',
'INPUTDATEFORMAT' => 'InputDateFormat',
'INPUTTIMEFORMAT' => 'InputTimeFormat',
'DECIMAL' => 'DecimalPoint',
'THOUSANDS' => 'ThousandSep',
'CHARSET' => 'Charset',
'UNITSYSTEM' => 'UnitSystem',
'DOCS_URL' => 'UserDocsUrl',
);
}
else {
$export_fields = $this->_getExportFields();
}
do {
$language_id = false;
$fields_hash = Array (
'PackName' => $language_node->Attributes['PACKNAME'],
'LocalName' => $language_node->Attributes['PACKNAME'],
'Encoding' => $language_node->Attributes['ENCODING'],
'Charset' => 'utf-8',
'SynchronizationModes' => Language::SYNCHRONIZE_DEFAULT,
);
if ($version > 1) {
foreach ($export_fields as $export_field) {
$attribute_name = strtoupper($export_field);
if (array_key_exists($attribute_name, $language_node->Attributes)) {
$fields_hash[$export_field] = $language_node->Attributes[$attribute_name];
}
}
}
$sub_node =& $language_node->firstChild;
/* @var $sub_node kXMLNode */
do {
switch ($sub_node->Name) {
case 'PHRASES':
if ($sub_node->Children) {
if (!$language_id) {
$language_id = $this->_processLanguage($fields_hash);
}
if ($this->_debugMode) {
$start_time = microtime(true);
}
$this->_processPhrases($sub_node->firstChild, $language_id, $fields_hash['Encoding']);
if ($this->_debugMode) {
$this->Application->Debugger->appendHTML(__CLASS__ . '::' . '_processPhrases: ' . (microtime(true) - $start_time));
}
}
break;
case 'EVENTS':
if ($sub_node->Children) {
if (!$language_id) {
$language_id = $this->_processLanguage($fields_hash);
}
$this->_processEvents($sub_node->firstChild, $language_id, $fields_hash['Encoding']);
}
break;
case 'COUNTRIES':
if ($sub_node->Children) {
if (!$language_id) {
$language_id = $this->_processLanguage($fields_hash);
}
$this->_processCountries($sub_node->firstChild, $language_id, $fields_hash['Encoding']);
}
break;
case 'REPLACEMENTS':
// added since v2
$replacements = $sub_node->Data;
if ($fields_hash['Encoding'] != 'plain') {
$replacements = base64_decode($replacements);
}
$fields_hash['FilenameReplacements'] = $replacements;
break;
default:
if ($version == 1) {
$fields_hash[ $field_mapping[$sub_node->Name] ] = $sub_node->Data;
}
break;
}
} while (($sub_node =& $sub_node->NextSibling()));
} while (($language_node =& $language_node->NextSibling()));
}
/**
* Performs phases import
*
* @param kXMLNode $phrase_node
* @param int $language_id
* @param string $language_encoding
*/
function _processPhrases(&$phrase_node, $language_id, $language_encoding)
{
static $other_translations = Array ();
if ($this->Application->isDebugMode()) {
$this->Application->Debugger->profileStart('L[' . $language_id . ']P', 'Language: ' . $language_id . '; Phrases Import');
}
do {
$phrase_key = mb_strtoupper($phrase_node->Attributes['LABEL']);
$fields_hash = Array (
'Phrase' => $phrase_node->Attributes['LABEL'],
'PhraseKey' => $phrase_key,
'PhraseType' => $phrase_node->Attributes['TYPE'],
'Module' => array_key_exists('MODULE', $phrase_node->Attributes) ? $phrase_node->Attributes['MODULE'] : 'Core',
'LastChanged' => adodb_mktime(),
'LastChangeIP' => $this->ip_address,
);
$translation = $phrase_node->Data;
$hint_translation = isset($phrase_node->Attributes['HINT']) ? $phrase_node->Attributes['HINT'] : '';
$column_translation = isset($phrase_node->Attributes['COLUMN']) ? $phrase_node->Attributes['COLUMN'] : '';
if (array_key_exists($fields_hash['PhraseType'], $this->phrase_types_allowed)) {
if ($language_encoding != 'plain') {
$translation = base64_decode($translation);
$hint_translation = base64_decode($hint_translation);
$column_translation = base64_decode($column_translation);
}
if (array_key_exists($phrase_key, $other_translations)) {
$other_translations[$phrase_key]['l' . $language_id . '_Translation'] = $translation;
$other_translations[$phrase_key]['l' . $language_id . '_HintTranslation'] = $hint_translation;
$other_translations[$phrase_key]['l' . $language_id . '_ColumnTranslation'] = $column_translation;
}
else {
$other_translations[$phrase_key] = Array (
'l' . $language_id . '_Translation' => $translation,
'l' . $language_id . '_HintTranslation' => $hint_translation,
'l' . $language_id . '_ColumnTranslation' => $column_translation,
);
}
$fields_hash = array_merge($fields_hash, $other_translations[$phrase_key]);
$this->Conn->doInsert($fields_hash, $this->_tables['phrases'], 'REPLACE', false);
}
} while (($phrase_node =& $phrase_node->NextSibling()));
if ($this->Application->isDebugMode()) {
$this->Application->Debugger->profileFinish('L[' . $language_id . ']P', 'Language: ' . $language_id . '; Phrases Import');
}
$this->Conn->doInsert($fields_hash, $this->_tables['phrases'], 'REPLACE');
}
/**
* Performs email event import
*
* @param kXMLNode $event_node
* @param int $language_id
* @param string $language_encoding
*/
function _processEvents(&$event_node, $language_id, $language_encoding)
{
static $other_translations = Array ();
if ($this->Application->isDebugMode()) {
$this->Application->Debugger->profileStart('L[' . $language_id . ']E', 'Language: ' . $language_id . '; Events Import');
}
$email_message_helper =& $this->Application->recallObject('EmailMessageHelper');
/* @var $email_message_helper EmailMessageHelper */
do {
$event_id = $this->_getEventId($event_node->Attributes['EVENT'], $event_node->Attributes['TYPE']);
if ($event_id) {
if ($language_encoding == 'plain') {
$template = rtrim($event_node->Data);
}
else {
$template = base64_decode($event_node->Data);
}
$parsed = $email_message_helper->parseTemplate($template);
$fields_hash = Array (
'EventId' => $event_id,
'Event' => $event_node->Attributes['EVENT'],
'Type' => $event_node->Attributes['TYPE'],
'MessageType' => $event_node->Attributes['MESSAGETYPE'],
);
if (array_key_exists($event_id, $other_translations)) {
$other_translations[$event_id]['l' . $language_id . '_Subject'] = $parsed['Subject'];
$other_translations[$event_id]['l' . $language_id . '_Body'] = $parsed['Body'];
}
else {
$other_translations[$event_id] = Array (
'l' . $language_id . '_Subject' => $parsed['Subject'],
'l' . $language_id . '_Body' => $parsed['Body'],
);
}
if ($parsed['Headers']) {
$other_translations[$event_id]['Headers'] = $parsed['Headers'];
}
elseif (!$parsed['Headers'] && !array_key_exists('Headers', $other_translations[$event_id])) {
$other_translations[$event_id]['Headers'] = $parsed['Headers'];
}
$fields_hash = array_merge($fields_hash, $other_translations[$event_id]);
$this->Conn->doInsert($fields_hash, $this->_tables['emailevents'], 'REPLACE', false);
}
} while (($event_node =& $event_node->NextSibling()));
if ($this->Application->isDebugMode()) {
$this->Application->Debugger->profileFinish('L[' . $language_id . ']E', 'Language: ' . $language_id . '; Events Import');
}
if (isset($fields_hash)) {
// at least one email event in language pack was found in database
$this->Conn->doInsert($fields_hash, $this->_tables['emailevents'], 'REPLACE');
}
}
/**
* Performs country_state translation import
*
* @param kXMLNode $country_state_node
* @param int $language_id
* @param string $language_encoding
* @param bool $process_states
* @return void
*/
function _processCountries(&$country_state_node, $language_id, $language_encoding, $process_states = false)
{
static $other_translations = Array ();
do {
if ($process_states) {
$country_state_id = $this->_getStateId($country_state_node->Parent->Attributes['ISO'], $country_state_node->Attributes['ISO']);
}
else {
$country_state_id = $this->_getCountryId($country_state_node->Attributes['ISO']);
}
if ($country_state_id) {
if ($language_encoding == 'plain') {
$translation = rtrim($country_state_node->Attributes['TRANSLATION']);
}
else {
$translation = base64_decode($country_state_node->Attributes['TRANSLATION']);
}
$fields_hash = Array (
'CountryStateId' => $country_state_id,
);
if (array_key_exists($country_state_id, $other_translations)) {
$other_translations[$country_state_id]['l' . $language_id . '_Name'] = $translation;
}
else {
$other_translations[$country_state_id] = Array (
'l' . $language_id . '_Name' => $translation,
);
}
$fields_hash = array_merge($fields_hash, $other_translations[$country_state_id]);
$this->Conn->doInsert($fields_hash, $this->_tables['country-state'], 'REPLACE', false);
if (!$process_states && $country_state_node->Children) {
$this->_processCountries($country_state_node->firstChild, $language_id, $language_encoding, true);
}
}
} while (($country_state_node =& $country_state_node->NextSibling()));
$this->Conn->doInsert($fields_hash, $this->_tables['country-state'], 'REPLACE');
}
/**
* Creates/updates language based on given fields and returns it's id
*
* @param Array $fields_hash
* @return int
*/
function _processLanguage($fields_hash)
{
// 1. get language from database
$sql = 'SELECT ' . $this->lang_object->IDField . '
FROM ' . $this->lang_object->TableName . '
WHERE PackName = ' . $this->Conn->qstr($fields_hash['PackName']);
$language_id = $this->Conn->GetOne($sql);
if ($language_id) {
// 2. language found -> update, when allowed
$this->lang_object->Load($language_id);
if ($this->import_mode == LANG_OVERWRITE_EXISTING) {
// update live language record based on data from xml
$this->lang_object->SetFieldsFromHash($fields_hash);
$this->lang_object->Update();
}
}
else {
// 3. language not found -> create
$this->lang_object->SetFieldsFromHash($fields_hash);
$this->lang_object->SetDBField('Enabled', STATUS_ACTIVE);
if ($this->lang_object->Create()) {
$language_id = $this->lang_object->GetID();
if (defined('IS_INSTALL') && IS_INSTALL) {
// language created during install becomes admin interface language
$this->lang_object->setPrimary(true, true);
}
}
}
// 4. collect ID of every processed language
if (!in_array($language_id, $this->_languages)) {
$this->_languages[] = $language_id;
}
return $language_id;
}
/**
* Returns event id based on it's name and type
*
* @param string $event_name
* @param string $event_type
* @return int
*/
function _getEventId($event_name, $event_type)
{
$cache_key = $event_name . '_' . $event_type;
return array_key_exists($cache_key, $this->events_hash) ? $this->events_hash[$cache_key] : 0;
}
/**
* Returns country id based on it's 3letter ISO code
*
* @param string $iso
* @return int
*/
function _getCountryId($iso)
{
static $cache = null;
if (!isset($cache)) {
$sql = 'SELECT CountryStateId, IsoCode
FROM ' . TABLE_PREFIX . 'CountryStates
WHERE Type = ' . DESTINATION_TYPE_COUNTRY;
$cache = $this->Conn->GetCol($sql, 'IsoCode');
}
return array_key_exists($iso, $cache) ? $cache[$iso] : false;
}
/**
* Returns state id based on 3letter country ISO code and 2letter state ISO code
*
* @param string $country_iso
* @param string $state_iso
* @return int
*/
function _getStateId($country_iso, $state_iso)
{
static $cache = null;
if (!isset($cache)) {
$sql = 'SELECT CountryStateId, CONCAT(StateCountryId, "-", IsoCode) AS IsoCode
FROM ' . TABLE_PREFIX . 'CountryStates
WHERE Type = ' . DESTINATION_TYPE_STATE;
$cache = $this->Conn->GetCol($sql, 'IsoCode');
}
$country_id = $this->_getCountryId($country_iso);
return array_key_exists($country_id . '-' . $state_iso, $cache) ? $cache[$country_id . '-' . $state_iso] : false;
}
}
\ No newline at end of file
Index: branches/5.2.x/core/install/upgrades.php
===================================================================
--- branches/5.2.x/core/install/upgrades.php (revision 14887)
+++ branches/5.2.x/core/install/upgrades.php (revision 14888)
@@ -1,1927 +1,1927 @@
<?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 {
/**
* 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') {
$ml_helper =& $this->Application->recallObject('kMultiLanguageHelper');
/* @var $ml_helper 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_' . EmailEvent::EVENT_TYPE_ADMIN,
'USER.PSWD_' . EmailEvent::EVENT_TYPE_FRONTEND,
'USER.PSWDC_' . EmailEvent::EVENT_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') {
if ($this->Conn->GetOne('SELECT LanguageId FROM '.TABLE_PREFIX.'Language WHERE PrimaryLang = 1')) 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
$ml_helper =& $this->Application->recallObject('kMultiLanguageHelper');
/* @var $ml_helper 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
$priority_helper =& $this->Application->recallObject('PriorityHelper');
/* @var $priority_helper kPriorityHelper */
$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()
{
$skin =& $this->Application->recallObject('skin', null, Array ('skip_autoload' => 1));
/* @var $skin kDBItem */
$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();
$skin_helper =& $this->Application->recallObject('SkinHelper');
/* @var $skin_helper 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 = ' . EmailEvent::EVENT_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
$rewrite_processor =& $this->Application->recallObject('kRewriteUrlProcessor');
/* @var $rewrite_processor 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');
}
}
$updater =& $this->Application->makeClass('kPermCacheUpdater');
/* @var $updater 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') {
// 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
$ml_helper =& $this->Application->recallObject('kMultiLanguageHelper');
/* @var $ml_helper kMultiLanguageHelper */
$ml_helper->createFields('phrases');
$ml_helper->createFields('emailevents');
$languages = $ml_helper->getLanguages();
if ($this->Conn->TableFound(TABLE_PREFIX . 'EmailMessage', true)) {
$email_message_helper =& $this->Application->recallObject('EmailMessageHelper');
/* @var $email_message_helper EmailMessageHelper */
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_message_helper->parseTemplate($translation_data['Template']);
$fields_hash = Array (
'l' . $language_id . '_Subject' => $parsed['Subject'],
'l' . $language_id . '_Body' => $parsed['Body'],
);
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();
}
}
/**
* 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);
$ml_helper =& $this->Application->recallObject('kMultiLanguageHelper');
/* @var $ml_helper 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()
{
$custom_field_helper =& $this->Application->recallObject('InpCustomFieldsHelper');
/* @var $custom_field_helper 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');
$minput_helper =& $this->Application->recallObject('MInputHelper');
/* @var $minput_helper 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'] == EmailEvent::EVENT_TYPE_FRONTEND) {
// from user
$fields_hash = Array (
'CustomSender' => 1,
'SenderAddressType' => EmailEvent::ADDRESS_TYPE_USER,
'SenderAddress' => $username
);
}
if ($event_data['Type'] == EmailEvent::EVENT_TYPE_ADMIN) {
// to user
$records = Array (
Array (
'RecipientType' => EmailEvent::RECIPIENT_TYPE_TO,
'RecipientName' => '',
'RecipientAddressType' => EmailEvent::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 == '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 == '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 = array_map(Array (&$this->Conn, 'qstr'), $fields);
+ $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 != 'after') {
return ;
}
$this->transformFieldPhrases();
}
/**
* Merges column and field phrases
*
* @return void
*/
protected function transformFieldPhrases()
{
$sql = 'SELECT *
FROM ' . TABLE_PREFIX . 'Phrase
WHERE PhraseKey LIKE "LA_COL_%"';
$column_phrases = $this->Conn->Query($sql, 'PhraseKey');
$sql = 'SELECT *
FROM ' . TABLE_PREFIX . 'Phrase
WHERE PhraseKey LIKE "LA_FLD_%"';
$field_phrases = $this->Conn->Query($sql, 'PhraseKey');
$ml_helper =& $this->Application->recallObject('kMultiLanguageHelper');
/* @var $ml_helper kMultiLanguageHelper */
$delete_ids = Array ();
$ml_helper->createFields('phrases');
$languages = $ml_helper->getLanguages();
foreach ($column_phrases as $phrase_key => $phrase_info) {
$field_phrase_key = 'LA_FLD_' . substr($phrase_key, 7);
if ( !isset($field_phrases[$field_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 . '_ColumnTranslation'] = $phrase_info['l' . $language_id . '_Translation'];
}
$delete_ids[] = $phrase_info['PhraseId'];
$this->Conn->doUpdate($fields_hash, TABLE_PREFIX . 'Phrase', 'PhraseId = ' . $field_phrases[$field_phrase_key]['PhraseId']);
}
// delete all column phrases, that were absorbed by field phrases
if ( $delete_ids ) {
$sql = 'DELETE FROM ' . TABLE_PREFIX . 'Phrase
WHERE PhraseId IN (' . implode(',', $delete_ids) . ')';
$this->Conn->Query($sql);
$sql = 'DELETE FROM ' . TABLE_PREFIX . 'PhraseCache';
$this->Conn->Query($sql);
}
}
/**
* 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 == 'after') {
$this->transformSortings();
$this->transformFieldPhrases(); // because of "la_col_ItemPrefix" phrase
$this->createPageRevisions();
}
}
/**
* Transforms a way, how list sortings are stored
*
* @return void
*/
function transformSortings()
{
$sql = 'SELECT VariableName, PortalUserId
FROM ' . TABLE_PREFIX . 'PersistantSessionData
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 = array_map(Array (&$this->Conn, 'qstr'), $old_variable_names);
+ $old_variable_names = $this->Conn->qstrArray($old_variable_names);
$sql = 'SELECT VariableValue, VariableName
FROM ' . TABLE_PREFIX . 'PersistantSessionData
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 . 'PersistantSessionData');
// delete sortings, that were already processed
$sql = 'DELETE FROM ' . TABLE_PREFIX . 'PersistantSessionData
WHERE PortalUserId = ' . $user_id . ' AND VariableName IN (' . implode(',', $old_variable_names) . ')';
$this->Conn->Query($sql);
}
}
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,
'FromRevisionNumber' => 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);
}
}
}
\ No newline at end of file

Event Timeline