Page MenuHomeIn-Portal Phabricator

in-portal
No OneTemporary

File Metadata

Created
Sat, Apr 19, 11:47 AM

in-portal

Index: branches/5.2.x/core/kernel/managers/cache_manager.php
===================================================================
--- branches/5.2.x/core/kernel/managers/cache_manager.php (revision 15225)
+++ branches/5.2.x/core/kernel/managers/cache_manager.php (revision 15226)
@@ -1,812 +1,852 @@
<?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 SystemSettings table
*
* @var Array
* @access protected
*/
protected $configVariables = Array();
/**
* Used variables from SystemSettings 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 (),
);
/**
* Name of database table, where configuration settings are stored
*
* @var string
* @access protected
*/
protected $settingTableName = '';
/**
* Set's references to kApplication and kDBConnection class instances
*
* @access public
*/
public function __construct()
{
parent::__construct();
$this->settingTableName = TABLE_PREFIX . 'SystemSettings';
if ( defined('IS_INSTALL') && IS_INSTALL ) {
// table substitution required, so "root" can perform login to upgrade to 5.2.0, where setting table was renamed
if ( !$this->Application->TableFound(TABLE_PREFIX . 'SystemSettings') ) {
$this->settingTableName = TABLE_PREFIX . 'ConfigurationValues';
}
}
}
/**
* 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 ' . $this->settingTableName . '
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)
{
$site_domain_override = Array (
'DefaultEmailSender' => 'AdminEmail',
'DefaultEmailRecipients' => 'DefaultEmailRecipients',
);
if ( isset($site_domain_override[$name]) ) {
$res = $this->Application->siteDomainField($site_domain_override[$name]);
if ( $res ) {
return $res;
}
}
if ( array_key_exists($name, $this->configVariables) ) {
return $this->configVariables[$name];
}
if ( defined('IS_INSTALL') && IS_INSTALL && !$this->Application->TableFound($this->settingTableName, true) ) {
return false;
}
$this->Conn->nextQueryCachable = true;
$sql = 'SELECT VariableId, VariableValue
FROM ' . $this->settingTableName . '
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;
}
/**
* Changes value of individual configuration variable (+resets cache, when needed)
*
* @param string $name
* @param string $value
* @param bool $local_cache_only
* @return string
* @access public
*/
public function SetConfigValue($name, $value, $local_cache_only = false)
{
$this->configVariables[$name] = $value;
if ( $local_cache_only ) {
return;
}
$fields_hash = Array ('VariableValue' => $value);
$this->Conn->doUpdate($fields_hash, $this->settingTableName, '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->setFromCache($cache);
$aggregator = $this->Application->recallObject('TagsAggregator', 'kArray');
/* @var $aggregator kArray */
$aggregator->setFromCache($cache);
$this->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()
{
// maybe discover keys automatically from corresponding classes
$cache_keys = Array (
'Factory.Files', 'Factory.realClasses',
'ConfigReader.prefixFiles',
'EventManager.beforeHooks', 'EventManager.afterHooks', 'EventManager.scheduledTasks', 'EventManager.buildEvents',
'Application.ReplacementTemplates', 'Application.RewriteListeners', 'Application.ModuleInfo',
'Application.ConfigHash', 'Application.ConfigCacheIds',
);
$empty_cache = Array ();
foreach ($cache_keys as $cache_key) {
$empty_cache[$cache_key] = Array ();
}
$this->Application->setFromCache($empty_cache);
$this->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->getToCache(),
$aggregator->getToCache(),
$this->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);
+ $this->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);
+ $this->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', 'DefaultGridPerPage',
// tracking related
'UseChangeLog', 'UseVisitorTracking', 'ModRewriteUrlEnding', 'ForceModRewriteUrlEnding',
'RunScheduledTasksFromCron',
);
$escaped_config_vars = $this->Conn->qstrArray($config_vars);
$sql = 'SELECT VariableId, VariableName, VariableValue
FROM ' . $this->settingTableName . '
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
+ * Stores new $value in cache with $key name
*
* @param int $key key name to add to cache
* @param mixed $value value of cached 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);
}
/**
+ * Stores new $value in cache with $key name (only if not there already)
+ *
+ * @param int $key key name to add to cache
+ * @param mixed $value value of cached record
+ * @param int $expiration when value expires (0 - doesn't expire)
+ * @return bool
+ * @access public
+ */
+ public function addCache($key, $value, $expiration = 0)
+ {
+ return $this->cacheHandler->addCache($key, $value, $expiration);
+ }
+
+ /**
* Sets rebuilding mode for given cache
*
* @param string $name
* @param int $mode
* @param int $max_rebuilding_time
- * @return void
+ * @return bool
* @access public
*/
public function rebuildCache($name, $mode = null, $max_rebuilding_time = 0)
{
- $this->cacheHandler->rebuildCache($name, $mode, $max_rebuilding_time);
+ return $this->cacheHandler->rebuildCache($name, $mode, $max_rebuilding_time);
}
/**
* Deletes key from cache
*
* @param string $key
* @return void
* @access public
*/
public function deleteCache($key)
{
$this->cacheHandler->delete($key);
}
/**
* Reset's all memory cache at once
*
* @return void
* @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)
{
// no serials in cache key OR cache is outdated
+ $rebuilding = false;
$wait_seconds = $max_rebuild_seconds;
while (true) {
$cached_data = $this->_getDBCache(Array ($name, $name . '_rebuilding', $name . '_rebuild'));
if ( $cached_data[$name . '_rebuild'] ) {
// cache rebuild requested -> rebuild now
$this->deleteDBCache($name . '_rebuild');
- return false;
+ if ( $this->rebuildDBCache($name, kCache::REBUILD_NOW, $max_rebuild_seconds, '[M1]') ) {
+ return false;
+ }
}
$cache = $cached_data[$name];
$rebuilding = $cached_data[$name . '_rebuilding'];
if ( ($cache === false) && (!$rebuilding || $wait_seconds == 0) ) {
// cache missing and nobody rebuilding it -> rebuild; enough waiting for cache to be ready
+ $this->rebuildDBCache($name, kCache::REBUILD_NOW, $max_rebuild_seconds, '[M2' . ($rebuilding ? 'R' : '!R') . ',WS=' . $wait_seconds . ']');
+
return false;
}
elseif ( $cache !== false ) {
// cache present -> return it
+ $this->cacheHandler->storeStatistics($name, $rebuilding ? 'h' : 'H');
+
return $cache;
}
$wait_seconds -= kCache::WAIT_STEP;
sleep(kCache::WAIT_STEP);
}
+ $this->rebuildDBCache($name, kCache::REBUILD_NOW, $max_rebuild_seconds, '[M3' . ($rebuilding ? 'R' : '!R') . ',WS=' . $wait_seconds . ']');
+
return false;
}
/**
* Returns value from database cache
*
* @param string|Array $names key name
* @return mixed
* @access protected
*/
protected function _getDBCache($names)
{
$res = Array ();
$names = (array)$names;
$this->Conn->nextQueryCachable = true;
$sql = 'SELECT Data, Cached, LifeTime, VarName
FROM ' . TABLE_PREFIX . 'SystemCache
WHERE VarName IN (' . implode(',', $this->Conn->qstrArray($names)) . ')';
$cached_data = $this->Conn->Query($sql, 'VarName');
foreach ($names as $name) {
if ( !isset($cached_data[$name]) ) {
$res[$name] = false;
continue;
}
$lifetime = (int)$cached_data[$name]['LifeTime']; // in seconds
if ( ($lifetime > 0) && ($cached_data[$name]['Cached'] + $lifetime < adodb_mktime()) ) {
// delete expired
$this->Conn->nextQueryCachable = true;
$sql = 'DELETE FROM ' . TABLE_PREFIX . 'SystemCache
WHERE VarName = ' . $this->Conn->qstr($name);
$this->Conn->Query($sql);
$res[$name] = false;
continue;
}
$res[$name] = $cached_data[$name]['Data'];
}
return count($res) == 1 ? array_pop($res) : $res;
}
/**
* Sets value to database cache
*
* @param string $name
* @param mixed $value
* @param int|bool $expiration
* @return void
* @access public
*/
public function setDBCache($name, $value, $expiration = false)
{
+ $this->cacheHandler->storeStatistics($name, 'WU');
+
$this->deleteDBCache($name . '_rebuilding');
$this->_setDBCache($name, $value, $expiration);
}
/**
* Sets value to database cache
*
* @param string $name
* @param mixed $value
* @param int|bool $expiration
+ * @param string $insert_type
+ * @return bool
* @access protected
*/
- protected function _setDBCache($name, $value, $expiration = false)
+ protected function _setDBCache($name, $value, $expiration = false, $insert_type = 'REPLACE')
{
- if ((int)$expiration <= 0) {
+ 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 . 'SystemCache', 'REPLACE');
+
+ return $this->Conn->doInsert($fields_hash, TABLE_PREFIX . 'SystemCache', $insert_type);
+ }
+
+ /**
+ * Sets value to database cache
+ *
+ * @param string $name
+ * @param mixed $value
+ * @param int|bool $expiration
+ * @return bool
+ * @access protected
+ */
+ protected function _addDBCache($name, $value, $expiration = false)
+ {
+ return $this->_setDBCache($name, $value, $expiration, 'INSERT');
}
/**
* Sets rebuilding mode for given cache
*
* @param string $name
* @param int $mode
* @param int $max_rebuilding_time
- * @return void
+ * @param string $miss_type
+ * @return bool
* @access public
*/
- public function rebuildDBCache($name, $mode = null, $max_rebuilding_time = 0)
+ public function rebuildDBCache($name, $mode = null, $max_rebuilding_time = 0, $miss_type = 'M')
{
if ( !isset($mode) || $mode == kCache::REBUILD_NOW ) {
- $this->_setDBCache($name . '_rebuilding', 1, $max_rebuilding_time);
+ $this->cacheHandler->storeStatistics($name, $miss_type);
+
+ if ( !$max_rebuilding_time ) {
+ return true;
+ }
+
+ if ( !$this->_addDBCache($name . '_rebuilding', 1, $max_rebuilding_time) ) {
+ $this->cacheHandler->storeStatistics($name, 'l');
+
+ return false;
+ }
+
$this->deleteDBCache($name . '_rebuild');
+ $this->cacheHandler->storeStatistics($name, 'L');
}
elseif ( $mode == kCache::REBUILD_LATER ) {
$this->_setDBCache($name . '_rebuild', 1, 0);
$this->deleteDBCache($name . '_rebuilding');
}
+
+ return true;
}
/**
* Deletes key from database cache
*
* @param string $name
* @return void
* @access public
*/
public function deleteDBCache($name)
{
$sql = 'DELETE FROM ' . TABLE_PREFIX . 'SystemCache
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
* @return string
* @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 . 'Categories
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/kernel/utility/cache.php
===================================================================
--- branches/5.2.x/core/kernel/utility/cache.php (revision 15225)
+++ branches/5.2.x/core/kernel/utility/cache.php (revision 15226)
@@ -1,789 +1,895 @@
<?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!');
/**
* Manager of all implemented caching handlers
*
*/
class kCache extends kBase {
/**
* Rebuild cache now
*
*/
const REBUILD_NOW = 1;
/**
* Rebuild cache later
*
*/
const REBUILD_LATER = 2;
/**
* Cache waiting step (in seconds)
*
*/
const WAIT_STEP = 2;
/**
* Object of cache handler
*
* @var FakeCacheHandler
*/
var $_handler = null;
/**
* Part of what we retrieve will be stored locally (per script run) not to bother memcache a lot
*
* @var Array
*/
var $_localStorage = Array ();
/**
* What type of caching is being used
*
* @var int
*/
var $cachingType = CACHING_TYPE_NONE;
/**
- * Cache usage statistics (per script run)
- *
- * @var Array
- */
- var $statistics = Array ();
-
- /**
* Debug cache usage
*
* @var bool
*/
var $debugCache = false;
/**
* Displays cache usage statistics
*
* @var bool
+ * @access protected
*/
- var $displayCacheStatistics = false;
+ protected $_storeStatistics = false;
/**
* Site key name
* Prepended to each cached key name
*
* @var string
*/
var $siteKeyName = '';
/**
* Site key value
* Prepended to each cached key name
*
* @var string
*/
var $siteKeyValue = null;
/**
* Creates cache manager
*
* @access public
*/
public function __construct()
{
parent::__construct();
$vars = kUtil::getConfigVars();
$this->siteKeyName = 'site_serial:' . crc32(SQL_TYPE . '://' . SQL_USER . ':' . SQL_PASS . '@' . SQL_SERVER . ':' . TABLE_PREFIX . ':' . SQL_DB);
// get cache handler class to use
$handler_class = (isset($vars['CacheHandler']) ? $vars['CacheHandler'] : '') . 'CacheHandler';
// defined cache handler doesn't exist -> use default
if ( !class_exists($handler_class) ) {
$handler_class = 'FakeCacheHandler';
}
$handler = new $handler_class();
if ( !$handler->isWorking() ) {
// defined cache handler is not working -> use default
trigger_error('Failed to initialize "<strong>' . $handler_class . '</strong>" caching handler.', E_USER_WARNING);
$handler = new FakeCacheHandler();
}
elseif ( $this->Application->isDebugMode() && ($handler->cachingType == CACHING_TYPE_MEMORY) ) {
$this->Application->Debugger->appendHTML('Memory Caching: "<strong>' . $handler_class . '</strong>"');
}
$this->_handler =& $handler;
$this->cachingType = $handler->cachingType;
$this->debugCache = $handler->cachingType == CACHING_TYPE_MEMORY && $this->Application->isDebugMode();
- $this->displayCacheStatistics = defined('DBG_CACHE') && DBG_CACHE && $this->Application->isDebugMode();
+ $this->_storeStatistics = defined('DBG_CACHE') && DBG_CACHE;
+
+ if ( $this->_storeStatistics ) {
+ // don't use FileHelper, since kFactory isn't ready yet
+ if ( !file_exists(RESTRICTED . DIRECTORY_SEPARATOR . 'cache_usage') ) {
+ mkdir(RESTRICTED . DIRECTORY_SEPARATOR . 'cache_usage');
+ }
+ }
}
/**
* Returns caching type of current storage engine
*
* @return int
*/
function getCachingType()
{
return $this->cachingType;
}
-
/**
* Stores value to cache
*
* @param string $name
* @param mixed $value
* @param int $expiration cache record expiration time in seconds
* @return bool
*/
function setCache($name, $value, $expiration)
{
// 1. stores current version of serial for given cache key
$this->_setCache($name . '_serials', $this->replaceSerials($name), $expiration);
+ $this->storeStatistics($name, 'W');
- // 2. remove rebuilding mark
+ // 2. don't replace serials within the key
+ $saved = $this->_setCache($name, $value, $expiration);
+ $this->storeStatistics($name, 'U');
+
+ // 3. remove rebuilding mark
$this->delete($name . '_rebuilding');
- return $this->_setCache($name, $value, $expiration);
+ return $saved;
}
/**
* Stores value to cache
*
* @param string $name
* @param mixed $value
* @param int $expiration cache record expiration time in seconds
* @return bool
*/
function _setCache($name, $value, $expiration)
{
$prepared_name = $this->prepareKeyName($name);
$this->_localStorage[$prepared_name] = $value;
return $this->_handler->set($prepared_name, $value, $expiration);
}
/**
+ * Stores value to cache (only if it's not there already)
+ *
+ * @param string $name
+ * @param mixed $value
+ * @param int $expiration cache record expiration time in seconds
+ * @return bool
+ */
+ function addCache($name, $value, $expiration)
+ {
+ // 1. stores current version of serial for given cache key
+ $this->_setCache($name . '_serials', $this->replaceSerials($name), $expiration);
+
+ // 2. remove rebuilding mark
+ $this->delete($name . '_rebuilding');
+
+ // 3. don't replace serials within the key
+ return $this->_addCache($name, $value, $expiration);
+ }
+
+ /**
+ * Stores value to cache (only if it's not there already)
+ *
+ * @param string $name
+ * @param mixed $value
+ * @param int $expiration cache record expiration time in seconds
+ * @return bool
+ */
+ function _addCache($name, $value, $expiration)
+ {
+ $prepared_name = $this->prepareKeyName($name);
+ $added = $this->_handler->add($prepared_name, $value, $expiration);
+
+ if ( $added ) {
+ $this->_localStorage[$prepared_name] = $value;
+ }
+
+ return $added;
+ }
+
+ /**
* Sets rebuilding mode for given cache
*
* @param string $name
* @param int $mode
* @param int $max_rebuilding_time
+ * @param string $miss_type
+ * @return bool
*/
- function rebuildCache($name, $mode = null, $max_rebuilding_time = 0)
+ function rebuildCache($name, $mode = null, $max_rebuilding_time = 0, $miss_type = 'M')
{
if ( !isset($mode) || $mode == self::REBUILD_NOW ) {
- $this->_setCache($name . '_rebuilding', 1, $max_rebuilding_time);
+ $this->storeStatistics($name, $miss_type);
+
+ if ( !$max_rebuilding_time ) {
+ return true;
+ }
+
+ // prevent parallel rebuild attempt by using "add" instead of "set" method
+ if ( !$this->_addCache($name . '_rebuilding', 1, $max_rebuilding_time) ) {
+ $this->storeStatistics($name, 'l');
+
+ return false;
+ }
+
+ $this->storeStatistics($name, 'L');
$this->delete($name . '_rebuild');
}
elseif ( $mode == self::REBUILD_LATER ) {
$this->_setCache($name . '_rebuild', 1, 0);
$this->delete($name . '_rebuilding');
}
+
+ return true;
}
/**
* Returns value from cache
*
* @param string $name
* @param bool $store_locally store data locally after retrieved
* @param int $max_rebuild_seconds
* @return mixed
*/
function getCache($name, $store_locally = true, $max_rebuild_seconds = 0)
{
- $cached_data = $this->_getCache(Array ($name . '_rebuild', $name . '_serials'), Array (true, true));
+ $cached_data = $this->_getCache(Array ($name . '_rebuild', $name . '_serials'), Array (true, false));
if ( $cached_data[$name . '_rebuild'] ) {
// cache rebuild requested -> rebuild now
$this->delete($name . '_rebuild');
- return false;
+ if ( $this->rebuildCache($name, self::REBUILD_NOW, $max_rebuild_seconds, '[M1]') ) {
+ return false;
+ }
}
+ // There are 2 key types:
+ // - with serials, e.g. with_serial_key[%LangSerial%]
+ // - without serials, e.g. without_serial
+ // Evaluated serials of each cache key are stored in '{$name}_serials' cache key.
+ // If cache is present, but serial is outdated, then cache value is assumed to be outdated.
+
$new_serial = $this->replaceSerials($name);
$old_serial = $cached_data[$name . '_serials'];
if ( $name == $new_serial || $new_serial != $old_serial ) {
// no serials in cache key OR cache is outdated
$wait_seconds = $max_rebuild_seconds;
while (true) {
$cached_data = $this->_getCache(Array ($name, $name . '_rebuilding'), Array ($store_locally, false));
$cache = $cached_data[$name];
$rebuilding = $cached_data[$name . '_rebuilding'];
if ( ($cache === false) && (!$rebuilding || $wait_seconds == 0) ) {
// cache missing and nobody rebuilding it -> rebuild; enough waiting for cache to be ready
+ $this->rebuildCache($name, self::REBUILD_NOW, $max_rebuild_seconds, '[M2' . ($rebuilding ? 'R' : '!R') . ',WS=' . $wait_seconds . ']');
+
return false;
}
elseif ( $cache !== false ) {
+ // re-read serial, since it might have been changed in parallel process !!!
+ $old_serial = $this->_getCache($name . '_serials', false);
+
// cache present (if other user is rebuilding it, then it's outdated cache) -> return it
- return $rebuilding || $new_serial == $old_serial ? $cache : false;
+ if ( $rebuilding || $new_serial == $old_serial ) {
+ $this->storeStatistics($name, $rebuilding ? 'h' : 'H');
+
+ return $cache;
+ }
+
+ $this->rebuildCache($name, self::REBUILD_NOW, $max_rebuild_seconds, '[M3' . ($rebuilding ? 'R' : '!R') . ',WS=' . $wait_seconds . ']');
+
+ return false;
}
$wait_seconds -= self::WAIT_STEP;
sleep(self::WAIT_STEP);
}
+ }
- return $cache;
+ $cache = $this->_getCache($name, $store_locally);
+
+ if ( $cache === false ) {
+ $this->rebuildCache($name, self::REBUILD_NOW, $max_rebuild_seconds, '[M4]');
+ }
+ else {
+ $this->storeStatistics($name, 'H');
}
- return $this->_getCache($name, $store_locally);
+ return $cache;
}
/**
* Returns value from cache
*
* @param string|Array $names
* @param bool|Array $store_locally store data locally after retrieved
* @return mixed
*/
function _getCache($names, $store_locally = true)
{
static $request_number = 1;
$res = Array ();
$names = (array)$names;
$store_locally = (array)$store_locally;
$to_get = $prepared_names = array_map(Array (&$this, 'prepareKeyName'), $names);
foreach ($prepared_names as $index => $prepared_name) {
$name = $names[$index];
if ( $store_locally[$index] && array_key_exists($prepared_name, $this->_localStorage) ) {
- if ( $this->displayCacheStatistics ) {
- $this->setStatistics($prepared_name, $this->_localStorage[$prepared_name]);
- }
-
$res[$name] = $this->_localStorage[$prepared_name];
unset($to_get[$index]);
}
}
if ( $to_get ) {
$multi_res = $this->_handler->get($to_get);
foreach ($to_get as $index => $prepared_name) {
$name = $names[$index];
if ( array_key_exists($prepared_name, $multi_res) ) {
$res[$name] =& $multi_res[$prepared_name];
}
else {
$res[$name] = false;
}
$this->_postProcessGetCache($prepared_name, $res[$name], $store_locally[$index], $request_number);
}
$request_number++;
}
return count($res) == 1 ? array_pop($res) : $res;
}
/**
* Stores variable in local cache & collects debug info about cache
*
* @param string $name
* @param mixed $res
* @param bool $store_locally
* @param int $request_number
* @return void
* @access protected
*/
protected function _postProcessGetCache($name, &$res, $store_locally = true, $request_number)
{
if ( $this->debugCache ) {
// don't display subsequent serial cache retrievals (ones, that are part of keys)
if ( is_array($res) ) {
$this->Application->Debugger->appendHTML('r' . $request_number . ': Restoring key "' . $name . '". Type: ' . gettype($res) . '.');
}
else {
$res_display = strip_tags($res);
if ( strlen($res_display) > 200 ) {
$res_display = substr($res_display, 0, 50) . ' ...';
}
$this->Application->Debugger->appendHTML('r' . $request_number . ': Restoring key "' . $name . '" resulted [' . $res_display . ']');
}
}
if ( $store_locally /*&& ($res !== false)*/ ) {
$this->_localStorage[$name] = $res;
-
- if ( $this->displayCacheStatistics ) {
- $this->setStatistics($name, $res);
- }
}
}
/**
* Deletes value from cache
*
* @param string $name
* @return mixed
*/
function delete($name)
{
$name = $this->prepareKeyName($name);
unset($this->_localStorage[$name]);
return $this->_handler->delete($name);
}
/**
* Reset's all memory cache at once
*/
function reset()
{
// don't check for enabled, because we maybe need to reset cache anyway
if ($this->cachingType == CACHING_TYPE_TEMPORARY) {
return ;
}
$site_key = $this->_cachePrefix(true);
$this->_handler->set($site_key, $this->_handler->get($site_key) + 1);
}
/**
* Replaces serials and adds unique site prefix to cache variable name
*
* @param string $name
* @return string
*/
protected function prepareKeyName($name)
{
if ( $this->cachingType == CACHING_TYPE_TEMPORARY ) {
return $name;
}
// add site-wide prefix to key
return $this->_cachePrefix() . $name;
}
/**
* Replaces serials within given string
*
* @param string $value
* @return string
* @access protected
*/
protected function replaceSerials($value)
{
if ( preg_match_all('/\[%(.*?)%\]/', $value, $regs) ) {
// [%LangSerial%] - prefix-wide serial in case of any change in "lang" prefix
// [%LangIDSerial:5%] - one id-wide serial in case of data, associated with given id was changed
// [%CiIDSerial:ItemResourceId:5%] - foreign key-based serial in case of data, associated with given foreign key was changed
$serial_names = $regs[1];
$serial_count = count($serial_names);
$store_locally = Array ();
for ($i = 0; $i < $serial_count; $i++) {
$store_locally[] = true;
}
$serial_values = $this->_getCache($serial_names, $store_locally);
if ( !is_array($serial_values) ) {
$serial_values = Array (current($serial_names) => $serial_values);
}
foreach ($serial_names as $serial_name) {
$value = str_replace('[%' . $serial_name . '%]', '[' . $serial_name . '=' . $serial_values[$serial_name] . ']', $value);
}
}
return $value;
}
/**
* Returns site-wide caching prefix
*
* @param bool $only_site_key_name
* @return string
*/
function _cachePrefix($only_site_key_name = false)
{
if ($only_site_key_name) {
return $this->siteKeyName;
}
if ( !isset($this->siteKeyValue) ) {
$this->siteKeyValue = $this->_handler->get($this->siteKeyName);
if (!$this->siteKeyValue) {
$this->siteKeyValue = 1;
$this->_handler->set($this->siteKeyName, $this->siteKeyValue);
}
}
return "{$this->siteKeyName}:{$this->siteKeyValue}:";
}
- function setStatistics($name, $found)
- {
- if (strpos($name, ']:') !== false) {
- list ($cache_name, $name) = explode(']:', $name, 2);
- }
- else {
- $cache_name = '-';
- }
-
- if (!array_key_exists($cache_name, $this->statistics)) {
- $this->statistics[$cache_name] = Array ();
- }
-
- if (!array_key_exists($name, $this->statistics[$cache_name])) {
- $this->statistics[$cache_name][$name] = Array ();
- }
-
- $status_key = $found ? 'found' : 'not_found';
-
- if (!isset($this->statistics[$cache_name][$name][$status_key])) {
- $this->statistics[$cache_name][$name][$status_key] = 0;
- }
-
- $this->statistics[$cache_name][$name][$status_key]++;
- }
-
/**
- * Returns storage size in bytes
+ * Stores statistics about cache usage in a file (one file per cache)
*
- * @return int
+ * @param string $name
+ * @param string $action_type {M - miss, L - lock, W - write, U - unlock, H - actual hit, h - outdated hit}
+ * @return void
+ * @access public
*/
- function getStorageSize()
+ public function storeStatistics($name, $action_type)
{
- return strlen( serialize($this->_localStorage) );
- }
-
- function printStatistics()
- {
- $cache_size = $this->getStorageSize();
-
- $this->Application->Debugger->appendHTML('<strong>Cache Size:</strong> ' . kUtil::formatSize($cache_size) . ' (' . $cache_size . ')');
-
- foreach ($this->statistics as $cache_name => $cache_data) {
- foreach ($cache_data as $key => $value) {
- if (!array_key_exists('found', $value) || $value['found'] == 1) {
- // remove cached records, that were used only 1 or 2 times
- unset($this->statistics[$cache_name][$key]);
- }
- }
+ if ( !$this->_storeStatistics ) {
+ return;
}
- kUtil::print_r($this->statistics, 'Cache Statistics:');
+ $name = str_replace(Array ('/', '\\', ':'), '_', $name);
+ $fp = fopen(RESTRICTED . DIRECTORY_SEPARATOR . 'cache_usage' . DIRECTORY_SEPARATOR . $name, 'a');
+ fwrite($fp, $action_type);
+ fclose($fp);
}
}
class FakeCacheHandler {
var $cachingType = CACHING_TYPE_TEMPORARY;
function FakeCacheHandler()
{
}
/**
* Retrieves value from cache
*
* @param string $names
* @return mixed
*/
function get($names)
{
if ( is_array($names) ) {
$res = Array ();
foreach ($names as $name) {
$res[$name] = false;
}
return $res;
}
return false;
}
/**
* Stores value in cache
*
* @param string $name
* @param mixed $value
* @param int $expiration
* @return bool
*/
function set($name, $value, $expiration = 0)
{
return true;
}
/**
+ * Stores value in cache (only if it's not there already)
+ *
+ * @param string $name
+ * @param mixed $value
+ * @param int $expiration
+ * @return bool
+ */
+ function add($name, $value, $expiration = 0)
+ {
+ return true;
+ }
+
+ /**
* Deletes key from cach
*
* @param string $name
* @return bool
*/
function delete($name)
{
return true;
}
/**
* Determines, that cache storage is working fine
*
* @return bool
*/
function isWorking()
{
return true;
}
}
class MemcacheCacheHandler {
var $_enabled = false;
/**
* Memcache connection
*
* @var Memcache
*/
var $_handler = null;
var $cachingType = CACHING_TYPE_MEMORY;
function MemcacheCacheHandler($default_servers = '')
{
$vars = kUtil::getConfigVars();
$memcached_servers = isset($vars['MemcacheServers']) ? $vars['MemcacheServers'] : $default_servers;
if ( $memcached_servers && class_exists('Memcache') ) {
$this->_enabled = true;
$this->_handler = new Memcache();
$servers = explode(';', $memcached_servers);
foreach ($servers as $server) {
if ( preg_match('/(.*):([\d]+)$/', $server, $regs) ) {
// "hostname:port" OR "unix:///path/to/socket:0"
$server = $regs[1];
$port = $regs[2];
}
else {
$port = 11211;
}
$this->_handler->addServer($server, $port);
}
// verify, that memcache server is working
if ( !$this->_handler->set('test', 1) ) {
$this->_enabled = false;
}
}
}
/**
* Retrieves value from cache
*
* @param string $name
* @return mixed
*/
function get($name)
{
return $this->_handler->get($name);
}
/**
* Stores value in cache
*
* @param string $name
* @param mixed $value
* @param int $expiration
* @return bool
*/
function set($name, $value, $expiration = 0)
{
// 0 - don't use compression
return $this->_handler->set($name, $value, 0, $expiration);
}
/**
+ * Stores value in cache (only if it's not there already)
+ *
+ * @param string $name
+ * @param mixed $value
+ * @param int $expiration
+ * @return bool
+ */
+ function add($name, $value, $expiration = 0)
+ {
+ // 0 - don't use compression
+ return $this->_handler->add($name, $value, 0, $expiration);
+ }
+
+ /**
* Deletes key from cache
*
* @param string $name
* @return bool
*/
function delete($name)
{
return $this->_handler->delete($name, 0);
}
/**
* Determines, that cache storage is working fine
*
* @return bool
*/
function isWorking()
{
return $this->_enabled;
}
}
class ApcCacheHandler {
var $_enabled = false;
var $cachingType = CACHING_TYPE_MEMORY;
function ApcCacheHandler()
{
$this->_enabled = function_exists('apc_fetch');
// verify, that apc is working
if ($this->_enabled && !$this->set('test', 1)) {
$this->_enabled = false;
}
}
/**
* Retrieves value from cache
*
* @param string $name
* @return mixed
*/
function get($name)
{
return apc_fetch($name);
}
/**
* Stores value in cache
*
* @param string $name
* @param mixed $value
* @param int $expiration
* @return bool
*/
function set($name, $value, $expiration = 0)
{
return apc_store($name, $value, $expiration);
}
/**
+ * Stores value in cache (only if it's not there already)
+ *
+ * @param string $name
+ * @param mixed $value
+ * @param int $expiration
+ * @return bool
+ */
+ function add($name, $value, $expiration = 0)
+ {
+ return apc_add($name, $value, $expiration);
+ }
+
+ /**
* Deletes key from cache
*
* @param string $name
* @return bool
*/
function delete($name)
{
return apc_delete($name);
}
/**
* Determines, that cache storage is working fine
*
* @return bool
*/
function isWorking()
{
return $this->_enabled;
}
}
class XCacheCacheHandler {
var $_enabled = false;
var $cachingType = CACHING_TYPE_MEMORY;
function XCacheCacheHandler()
{
$this->_enabled = function_exists('xcache_get');
// verify, that xcache is working
if ($this->_enabled && !$this->set('test', 1)) {
$this->_enabled = false;
}
}
/**
* Retrieves value from cache
*
* @param string|Array $names
* @return mixed
*/
function get($names)
{
if ( is_array($names) ) {
$res = Array ();
foreach ($names as $name) {
$res[$name] = $this->get($name);
}
return $res;
}
return xcache_isset($names) ? xcache_get($names) : false;
}
/**
* Stores value in cache
*
* @param string $name
* @param mixed $value
* @param int $expiration
* @return bool
*/
function set($name, $value, $expiration = 0)
{
return xcache_set($name, $value, $expiration);
}
/**
+ * Stores value in cache (only if it's not there already)
+ *
+ * @param string $name
+ * @param mixed $value
+ * @param int $expiration
+ * @return bool
+ */
+ function add($name, $value, $expiration = 0)
+ {
+ // not atomic operation, like in Memcached and may fail
+ if ( xcache_isset($name) ) {
+ return false;
+ }
+
+ return $this->set($name, $value, $expiration);
+ }
+
+ /**
* Deletes key from cache
*
* @param string $name
* @return bool
*/
function delete($name)
{
return xcache_unset($name);
}
/**
* Determines, that cache storage is working fine
*
* @return bool
*/
function isWorking()
{
return $this->_enabled;
}
}
\ No newline at end of file
Index: branches/5.2.x/core/kernel/utility/unit_config_reader.php
===================================================================
--- branches/5.2.x/core/kernel/utility/unit_config_reader.php (revision 15225)
+++ branches/5.2.x/core/kernel/utility/unit_config_reader.php (revision 15226)
@@ -1,1028 +1,1019 @@
<?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 kUnitConfigReader extends kBase implements kiCacheable {
/**
* Configs reader
*
* @var Array
* @access private
*/
var $configData = Array();
var $configFiles = Array();
var $CacheExpired = false;
var $prefixFiles = array();
var $ProcessAllConfigs = false;
var $FinalStage = false;
var $StoreCache = false;
var $AfterConfigProcessed = array();
/**
* Escaped directory separator for using in regular expressions
*
* @var string
*/
var $_directorySeparator = '';
/**
* Regular expression for detecting module folder
*
* @var string
*/
var $_moduleFolderRegExp = '';
/**
* Folders to skip during unit config search
*
* @var Array
*/
var $_skipFolders = Array ('CVS', '.svn', 'admin_templates', 'libchart');
/**
* Creates instance of unit config reader
*
*/
public function __construct()
{
parent::__construct();
$this->_directorySeparator = preg_quote(DIRECTORY_SEPARATOR);
$editor_path = explode('/', trim(EDITOR_PATH, '/'));
$this->_skipFolders[] = array_pop($editor_path); // last of cmseditor folders
$this->_moduleFolderRegExp = '#' . $this->_directorySeparator . '(core|modules' . $this->_directorySeparator . '.*?)' . $this->_directorySeparator . '#';
}
/**
* Sets data from cache to object
*
* @param Array $data
* @access public
*/
public function setFromCache(&$data)
{
$this->prefixFiles = $data['ConfigReader.prefixFiles'];
}
/**
* Gets object data for caching
*
* @access public
* @return Array
*/
public function getToCache()
{
return Array (
'ConfigReader.prefixFiles' => $this->prefixFiles,
);
}
function scanModules($folderPath, $cache = true)
{
if (defined('IS_INSTALL') && IS_INSTALL && !defined('FORCE_CONFIG_CACHE')) {
// disable config caching during installation
$cache = false;
}
if ($cache) {
$restored = $this->Application->cacheManager->LoadUnitCache();
if ($restored) {
if ( defined('DEBUG_MODE') && DEBUG_MODE && $this->Application->isDebugMode() ) {
$this->Application->Debugger->appendHTML('UnitConfigReader: Restoring Cache');
}
return;
}
}
if ( defined('DEBUG_MODE') && DEBUG_MODE && $this->Application->isDebugMode() ) {
$this->Application->Debugger->appendHTML('UnitConfigReader: Generating Cache');
}
$this->ProcessAllConfigs = true;
$this->includeConfigFiles($folderPath, $cache);
$this->ParseConfigs();
// tell AfterConfigRead to store cache if needed
// can't store it here because AfterConfigRead needs ability to change config data
$this->StoreCache = $cache;
if ( !$this->Application->InitDone ) {
// scanModules is called multiple times during installation process
$this->Application->InitManagers();
// get build-in rewrite listeners ONLY to be able to parse mod-rewrite url when unit config cache is missing
$this->retrieveCollections();
$this->_sortRewriteListeners();
}
$this->Application->cacheManager->applyDelayedUnitProcessing();
}
function findConfigFiles($folderPath, $level = 0)
{
// if FULL_PATH = "/" ensure, that all "/" in $folderPath are not deleted
$reg_exp = '/^' . preg_quote(FULL_PATH, '/') . '/';
$folderPath = preg_replace($reg_exp, '', $folderPath, 1); // this make sense, since $folderPath may NOT contain FULL_PATH
$base_folder = FULL_PATH . $folderPath . DIRECTORY_SEPARATOR;
$sub_folders = glob($base_folder . '*', GLOB_ONLYDIR);
if (!$sub_folders) {
return ;
}
if ($level == 0) {
// don't scan Front-End themes because of extensive directory structure
$sub_folders = array_diff($sub_folders, Array ($base_folder . 'themes', $base_folder . 'tools'));
}
foreach ($sub_folders as $full_path) {
$sub_folder = substr($full_path, strlen($base_folder));
if (in_array($sub_folder, $this->_skipFolders)) {
continue;
}
if (preg_match('/^\./', $sub_folder)) {
// don't scan ".folders"
continue;
}
$config_name = $this->getConfigName($folderPath . DIRECTORY_SEPARATOR . $sub_folder);
if (file_exists(FULL_PATH . $config_name)) {
$this->configFiles[] = $config_name;
}
$this->findConfigFiles($full_path, $level + 1);
}
}
function includeConfigFiles($folderPath, $cache = true)
{
$this->Application->refreshModuleInfo();
if ( $this->Application->isCachingType(CACHING_TYPE_MEMORY) ) {
- $data = $this->Application->getCache('master:config_files', false, CacheSettings::$unitCacheRebuildTime);
+ $data = $this->Application->getCache('master:config_files', false, $cache ? CacheSettings::$unitCacheRebuildTime : 0);
}
else {
- $data = $this->Application->getDBCache('config_files', CacheSettings::$unitCacheRebuildTime);
+ $data = $this->Application->getDBCache('config_files', $cache ? CacheSettings::$unitCacheRebuildTime : 0);
}
if ( $data ) {
$this->configFiles = unserialize($data);
if ( !defined('DBG_VALIDATE_CONFIGS') && !DBG_VALIDATE_CONFIGS ) {
shuffle($this->configFiles);
}
}
else {
- if ( $cache ) {
- if ( $this->Application->isCachingType(CACHING_TYPE_MEMORY) ) {
- $this->Application->rebuildCache('master:config_files', kCache::REBUILD_NOW, CacheSettings::$unitCacheRebuildTime);
- }
- else {
- $this->Application->rebuildDBCache('config_files', kCache::REBUILD_NOW, CacheSettings::$unitCacheRebuildTime);
- }
- }
-
$this->findConfigFiles(FULL_PATH . DIRECTORY_SEPARATOR . 'core'); // search from core directory
$this->findConfigFiles($folderPath); // search from modules directory
if ( $cache ) {
if ( $this->Application->isCachingType(CACHING_TYPE_MEMORY) ) {
$this->Application->setCache('master:config_files', serialize($this->configFiles));
}
else {
$this->Application->setDBCache('config_files', serialize($this->configFiles));
}
}
}
foreach ($this->configFiles as $filename) {
$prefix = $this->PreloadConfigFile($filename);
if (!$prefix) {
throw new Exception('Prefix not defined in config file <strong>' . $filename . '</strong>');
}
}
if ($cache) {
unset($this->configFiles);
}
}
/**
* Process all read config files - called ONLY when there is no cache!
*
*/
function ParseConfigs()
{
// 1. process normal configs
$prioritized_configs = array();
foreach ($this->configData as $prefix => $config) {
if (isset($config['ConfigPriority'])) {
$prioritized_configs[$prefix] = $config['ConfigPriority'];
continue;
}
$this->parseConfig($prefix);
}
foreach ($this->configData as $prefix => $config) {
$this->postProcessConfig($prefix, 'AggregateConfigs', 'sub_prefix');
$clones = $this->postProcessConfig($prefix, 'Clones', 'prefix');
}
// 2. process prioritized configs
asort($prioritized_configs);
foreach ($prioritized_configs as $prefix => $priority) {
$this->parseConfig($prefix);
}
}
function AfterConfigRead($store_cache = null)
{
// if (!$this->ProcessAllConfigs) return ;
$this->FinalStage = true;
foreach ($this->configData as $prefix => $config) {
$this->runAfterConfigRead($prefix);
}
if ( !isset($store_cache) ) {
// $store_cache not overridden -> use global setting
$store_cache = $this->StoreCache;
}
if ($store_cache || (defined('IS_INSTALL') && IS_INSTALL)) {
// cache is not stored during install, but dynamic clones should be processed in any case
$this->processDynamicClones();
$this->retrieveCollections();
}
if ($store_cache) {
$this->_sortRewriteListeners();
$this->Application->HandleEvent(new kEvent('adm:OnAfterCacheRebuild'));
$this->Application->cacheManager->UpdateUnitCache();
if (defined('DEBUG_MODE') && DEBUG_MODE && defined('DBG_VALIDATE_CONFIGS') && DBG_VALIDATE_CONFIGS) {
// validate configs here to have changes from OnAfterConfigRead hooks to prefixes
foreach ($this->configData as $prefix => $config) {
if (!isset($config['TableName'])) continue;
$this->ValidateConfig($prefix);
}
}
}
}
/**
* Sort rewrite listeners according to RewritePriority (non-prioritized listeners goes first)
*
*/
function _sortRewriteListeners()
{
$listeners = Array ();
$prioritized_listeners = Array ();
// process non-prioritized listeners
foreach ($this->Application->RewriteListeners as $prefix => $listener_data) {
if ($listener_data['priority'] === false) {
$listeners[$prefix] = $listener_data;
}
else {
$prioritized_listeners[$prefix] = $listener_data['priority'];
}
}
// process prioritized listeners
asort($prioritized_listeners, SORT_NUMERIC);
foreach ($prioritized_listeners as $prefix => $priority) {
$listeners[$prefix] = $this->Application->RewriteListeners[$prefix];
}
$this->Application->RewriteListeners = $listeners;
}
/**
* Re-reads all configs
*
*/
function ReReadConfigs()
{
// don't reset prefix file, since file scanning could slow down the process
$prefix_files_backup = $this->prefixFiles;
$this->Application->cacheManager->EmptyUnitCache();
$this->prefixFiles = $prefix_files_backup;
// parse all configs
$this->ProcessAllConfigs = true;
$this->AfterConfigProcessed = Array ();
$this->includeConfigFiles(MODULES_PATH, false);
$this->ParseConfigs();
$this->AfterConfigRead(false);
$this->processDynamicClones();
// don't call kUnitConfigReader::retrieveCollections since it
// will overwrite what we already have in kApplication class instance
}
/**
* Process clones, that were defined via OnAfterConfigRead event
*
*/
function processDynamicClones()
{
$new_clones = Array();
foreach ($this->configData as $prefix => $config) {
$clones = $this->postProcessConfig($prefix, 'Clones', 'prefix');
if ($clones) {
$new_clones = array_merge($new_clones, $clones);
}
}
// execute delayed methods for cloned unit configs
$this->Application->cacheManager->applyDelayedUnitProcessing();
// call OnAfterConfigRead for cloned configs
$new_clones = array_unique($new_clones);
foreach ($new_clones as $prefix) {
$this->runAfterConfigRead($prefix);
}
}
/**
* Process all collectible unit config options here to also catch ones, defined from OnAfterConfigRead events
*
*/
function retrieveCollections()
{
foreach ($this->configData as $prefix => $config) {
// collect replacement templates
if (array_key_exists('ReplacementTemplates', $config) && $config['ReplacementTemplates']) {
$this->Application->ReplacementTemplates = array_merge($this->Application->ReplacementTemplates, $config['ReplacementTemplates']);
}
// collect rewrite listeners
if (array_key_exists('RewriteListener', $config) && $config['RewriteListener']) {
$rewrite_listeners = $config['RewriteListener'];
if (!is_array($rewrite_listeners)) {
// when one method is used to build and parse url
$rewrite_listeners = Array ($rewrite_listeners, $rewrite_listeners);
}
foreach ($rewrite_listeners as $index => $rewrite_listener) {
if (strpos($rewrite_listener, ':') === false) {
$rewrite_listeners[$index] = $prefix . '_EventHandler:' . $rewrite_listener;
}
}
$rewrite_priority = array_key_exists('RewritePriority', $config) ? $config['RewritePriority'] : false;
$this->Application->RewriteListeners[$prefix] = Array ('listener' => $rewrite_listeners, 'priority' => $rewrite_priority);
}
}
}
/**
* Register nessasary classes
* This method should only process the data which is cached!
*
* @param string $prefix
* @access private
*/
function parseConfig($prefix)
{
$this->parseClasses($prefix);
$this->parseScheduledTasks($prefix);
$this->parseHooks($prefix);
$this->parseAggregatedTags($prefix);
}
protected function parseClasses($prefix)
{
$config =& $this->configData[$prefix];
$register_classes = $this->getClasses($prefix);
foreach ($register_classes as $class_info) {
$this->Application->registerClass(
$class_info['class'],
$config['BasePath'] . DIRECTORY_SEPARATOR . $class_info['file'],
$class_info['pseudo']
);
if ( isset($class_info['build_event']) && $class_info['build_event'] ) {
$this->Application->delayUnitProcessing('registerBuildEvent', Array ($class_info['pseudo'], $class_info['build_event']));
}
}
}
protected function parseScheduledTasks($prefix)
{
$config =& $this->configData[$prefix];
if ( !isset($config['ScheduledTasks']) || !$config['ScheduledTasks'] ) {
return ;
}
$scheduled_tasks = $config['ScheduledTasks'];
foreach ($scheduled_tasks as $short_name => $scheduled_task_info) {
$event_status = array_key_exists('Status', $scheduled_task_info) ? $scheduled_task_info['Status'] : STATUS_ACTIVE;
$this->Application->delayUnitProcessing('registerScheduledTask', Array ( $short_name, $config['Prefix'] . ':' . $scheduled_task_info['EventName'], $scheduled_task_info['RunInterval'], $event_status ));
}
}
protected function parseHooks($prefix)
{
$config =& $this->configData[$prefix];
if ( !isset($config['Hooks']) || !$config['Hooks'] ) {
return ;
}
$hooks = $config['Hooks'];
foreach ($hooks as $hook) {
if ( isset($config['ParentPrefix']) && ($hook['HookToPrefix'] == $config['ParentPrefix']) ) {
trigger_error('Depricated Hook Usage [prefix: <strong>' . $config['Prefix'] . '</strong>; do_prefix: <strong>' . $hook['DoPrefix'] . '</strong>] use <strong>#PARENT#</strong> as <strong>HookToPrefix</strong> value, where HookToPrefix is same as ParentPrefix', defined('E_USER_DEPRECATED') ? E_USER_DEPRECATED : E_USER_NOTICE);
}
if ($hook['HookToPrefix'] == '') {
// new: set hooktoprefix to current prefix if not set
$hook['HookToPrefix'] = $config['Prefix'];
}
if ( isset($config['ParentPrefix']) ) {
// new: allow to set hook to parent prefix what ever it is
if ($hook['HookToPrefix'] == '#PARENT#') {
$hook['HookToPrefix'] = $config['ParentPrefix'];
}
if ($hook['DoPrefix'] == '#PARENT#') {
$hook['DoPrefix'] = $config['ParentPrefix'];
}
}
elseif ($hook['HookToPrefix'] == '#PARENT#' || $hook['DoPrefix'] == '#PARENT#') {
// we need parent prefix but it's not set !
continue;
}
$hook_events = (array)$hook['HookToEvent'];
$do_prefix = $hook['DoPrefix'] == '' ? $config['Prefix'] : $hook['DoPrefix'];
foreach ($hook_events as $hook_event) {
$hook_event = $hook['HookToPrefix'] . '.' . $hook['HookToSpecial'] . ':' . $hook_event;
$do_event = $do_prefix . '.' . $hook['DoSpecial'] . ':' . $hook['DoEvent'];
$this->Application->delayUnitProcessing('registerHook', Array ($hook_event, $do_event, $hook['Mode'], $hook['Conditional']));
}
}
}
protected function parseAggregatedTags($prefix)
{
$config =& $this->configData[$prefix];
$aggregated_tags = isset($config['AggregateTags']) ? $config['AggregateTags'] : Array ();
foreach ($aggregated_tags as $aggregate_tag) {
if ( isset($config['ParentPrefix']) ) {
if ($aggregate_tag['AggregateTo'] == $config['ParentPrefix']) {
trigger_error('Depricated Aggregate Tag Usage [prefix: <b>'.$config['Prefix'].'</b>; AggregateTo: <b>'.$aggregate_tag['AggregateTo'].'</b>] use <b>#PARENT#</b> as <b>AggregateTo</b> value, where AggregateTo is same as ParentPrefix', defined('E_USER_DEPRECATED') ? E_USER_DEPRECATED : E_USER_NOTICE);
}
if ($aggregate_tag['AggregateTo'] == '#PARENT#') {
$aggregate_tag['AggregateTo'] = $config['ParentPrefix'];
}
}
$aggregate_tag['LocalPrefix'] = $config['Prefix'];
$this->Application->delayUnitProcessing('registerAggregateTag', Array ($aggregate_tag));
}
}
function ValidateConfig($prefix)
{
global $debugger;
$config =& $this->configData[$prefix];
$tablename = $config['TableName'];
$float_types = Array ('float', 'double', 'numeric');
$table_found = $this->Conn->Query('SHOW TABLES LIKE "'.$tablename.'"');
if (!$table_found) {
// config present, but table missing, strange
kUtil::safeDefine('DBG_RAISE_ON_WARNINGS', 1);
$debugger->appendHTML("<b class='debug_error'>Config Warning: </b>Table <strong>$tablename</strong> missing, but prefix <b>".$config['Prefix']."</b> requires it!");
$debugger->WarningCount++;
return ;
}
$res = $this->Conn->Query('DESCRIBE '.$tablename);
$config_link = $debugger->getFileLink(FULL_PATH.$this->prefixFiles[$config['Prefix']], 1, $config['Prefix']);
$error_messages = Array (
'field_not_found' => 'Field <strong>%s</strong> exists in the database, but <strong>is not defined</strong> in config',
'default_missing' => 'Default value for field <strong>%s</strong> not set in config',
'not_null_error1' => 'Field <strong>%s</strong> is NOT NULL in the database, but is not configured as not_null', // or required',
'not_null_error2' => 'Field <strong>%s</strong> is described as NOT NULL in config, but <strong>does not have DEFAULT value</strong>',
'not_null_error3' => 'Field <strong>%s</strong> is described as <strong>NOT NULL in config</strong>, but is <strong>NULL in db</strong>',
'invalid_default' => '<strong>Default value</strong> for field %s<strong>%s</strong> not sync. to db (in config = %s, in db = %s)',
'date_column_not_null_error' => 'Field <strong>%s</strong> must be NULL in config and database, since it contains date',
'user_column_default_error' => 'Field <strong>%s</strong> must be have NULL as default value, since it holds user id',
'type_missing' => '<strong>Type definition</strong> for field <strong>%s</strong> missing in config',
'virtual_type_missing' => '<strong>Type definition</strong> for virtual field <strong>%s</strong> missing in config',
'virtual_default_missing' => 'Default value for virtual field <strong>%s</strong> not set in config',
'virtual_not_null_error' => 'Virtual field <strong>%s</strong> cannot be not null, since it doesn\'t exist in database',
'invalid_calculated_field' => 'Calculated field <strong>%s</strong> is missing corresponding virtual field',
);
$config_errors = Array ();
$tablename = preg_replace('/^'.preg_quote(TABLE_PREFIX, '/').'(.*)/', '\\1', $tablename); // remove table prefix
// validate unit config field declaration in relation to database table structure
foreach ($res as $field) {
$f_name = $field['Field'];
if (getArrayValue($config, 'Fields')) {
if (preg_match('/l[\d]+_[\w]/', $f_name)) {
// skip multilingual fields
continue;
}
if (!array_key_exists ($f_name, $config['Fields'])) {
$config_errors[] = sprintf($error_messages['field_not_found'], $f_name);
}
else {
$db_default = $field['Default'];
if (is_numeric($db_default)) {
$db_default = preg_match('/[\.,]/', $db_default) ? (float)$db_default : (int)$db_default;
}
$default_missing = false;
$options = $config['Fields'][$f_name];
$not_null = isset($options['not_null']) && $options['not_null'];
$formatter = array_key_exists('formatter', $options) ? $options['formatter'] : false;
if (!array_key_exists('default', $options)) {
$config_errors[] = sprintf($error_messages['default_missing'], $f_name);
$default_missing = true;
}
if ($field['Null'] != 'YES') {
// field is NOT NULL in database (MySQL5 for null returns "NO", but MySQL4 returns "")
if ( $f_name != $config['IDField'] && !isset($options['not_null']) /*&& !isset($options['required'])*/ ) {
$config_errors[] = sprintf($error_messages['not_null_error1'], $f_name);
}
if ($not_null && !isset($options['default']) ) {
$config_errors[] = sprintf($error_messages['not_null_error2'], $f_name);
}
}
elseif ($not_null) {
$config_errors[] = sprintf($error_messages['not_null_error3'], $f_name);
}
if (($formatter == 'kDateFormatter') && $not_null) {
$config_errors[] = sprintf($error_messages['date_column_not_null_error'], $f_name);
}
// columns, holding userid should have NULL as default value
if (array_key_exists('type', $options) && !$default_missing) {
// both type and default value set
if (preg_match('/ById$/', $f_name) && $options['default'] !== null) {
$config_errors[] = sprintf($error_messages['user_column_default_error'], $f_name);
}
}
if (!array_key_exists('type', $options)) {
$config_errors[] = sprintf($error_messages['type_missing'], $f_name);
}
if (!$default_missing && ($field['Type'] != 'text')) {
if ( is_null($db_default) && $not_null ) {
$db_default = $options['type'] == 'string' ? '' : 0;
}
if ($f_name == $config['IDField'] && $options['type'] != 'string' && $options['default'] !== 0) {
$config_errors[] = sprintf($error_messages['invalid_default'], '<span class="debug_error">IDField</span> ', $f_name, $this->varDump($options['default']), $this->varDump($field['Default']));
}
else if (((string)$options['default'] != '#NOW#') && ($db_default !== $options['default']) && !in_array($options['type'], $float_types)) {
$config_errors[] = sprintf($error_messages['invalid_default'], '', $f_name, $this->varDump($options['default']), $this->varDump($db_default));
}
}
}
}
}
// validate virtual fields
if ( array_key_exists('VirtualFields', $config) ) {
foreach ($config['VirtualFields'] as $f_name => $options) {
if (!array_key_exists('type', $options)) {
$config_errors[] = sprintf($error_messages['virtual_type_missing'], $f_name);
}
if (array_key_exists('not_null', $options)) {
$config_errors[] = sprintf($error_messages['virtual_not_null_error'], $f_name);
}
if (!array_key_exists('default', $options)) {
$config_errors[] = sprintf($error_messages['virtual_default_missing'], $f_name);
}
}
}
// validate calculated fields
if ( array_key_exists('CalculatedFields', $config) ) {
foreach ($config['CalculatedFields'] as $special => $calculated_fields) {
foreach ($calculated_fields as $calculated_field => $calculated_field_expr) {
if ( !isset($config['VirtualFields'][$calculated_field]) ) {
$config_errors[] = sprintf($error_messages['invalid_calculated_field'], $calculated_field);
}
}
}
$config_errors = array_unique($config_errors);
}
if ($config_errors) {
$error_prefix = '<strong class="debug_error">Config Error'.(count($config_errors) > 1 ? 's' : '').': </strong> for prefix <strong>'.$config_link.'</strong> ('.$tablename.') in unit config:<br />';
$config_errors = $error_prefix.'&nbsp;&nbsp;&nbsp;'.implode('<br />&nbsp;&nbsp;&nbsp;', $config_errors);
kUtil::safeDefine('DBG_RAISE_ON_WARNINGS', 1);
$debugger->appendHTML($config_errors);
$debugger->WarningCount++;
}
}
function varDump($value)
{
return '<strong>'.var_export($value, true).'</strong> of '.gettype($value);
}
function postProcessConfig($prefix, $config_key, $dst_prefix_var)
{
$main_config =& $this->configData[$prefix];
$sub_configs = isset($main_config[$config_key]) && $main_config[$config_key] ? $main_config[$config_key] : Array ();
if ( !$sub_configs ) {
return Array ();
}
unset($main_config[$config_key]);
$processed = array();
foreach ($sub_configs as $sub_prefix => $sub_config) {
if ($config_key == 'AggregateConfigs' && !isset($this->configData[$sub_prefix])) {
$this->loadConfig($sub_prefix);
}
$sub_config['Prefix'] = $sub_prefix;
$this->configData[$sub_prefix] = kUtil::array_merge_recursive($this->configData[$$dst_prefix_var], $sub_config);
// when merging empty array to non-empty results non-empty array, but empty is required
foreach ($sub_config as $sub_key => $sub_value) {
if (!$sub_value) {
unset($this->configData[$sub_prefix][$sub_key]);
}
}
if ($config_key == 'Clones') {
$this->prefixFiles[$sub_prefix] = $this->prefixFiles[$prefix];
}
$this->postProcessConfig($sub_prefix, $config_key, $dst_prefix_var);
if ($config_key == 'AggregateConfigs') {
$processed = array_merge($this->postProcessConfig($sub_prefix, 'Clones', 'prefix'), $processed);
}
elseif ($this->ProcessAllConfigs) {
$this->parseConfig($sub_prefix);
}
array_push($processed, $sub_prefix);
}
if (!$prefix) {
// configs, that used only for cloning & not used ifself
unset($this->configData[$prefix]);
}
return array_unique($processed);
}
function PreloadConfigFile($filename)
{
$config_found = file_exists(FULL_PATH . $filename) && $this->configAllowed($filename);
if (defined('DEBUG_MODE') && DEBUG_MODE && defined('DBG_PROFILE_INCLUDES') && DBG_PROFILE_INCLUDES) {
if ( in_array($filename, get_included_files()) ) {
return '';
}
global $debugger;
if ($config_found) {
$file = FULL_PATH . $filename;
$file_crc = crc32($file);
$debugger->ProfileStart('inc_' . $file_crc, $file);
include_once($file);
$debugger->ProfileFinish('inc_' . $file_crc);
$debugger->profilerAddTotal('includes', 'inc_' . $file_crc);
}
}
elseif ($config_found) {
include_once(FULL_PATH . $filename);
}
if ($config_found) {
if (isset($config) && $config) {
// config file is included for 1st time -> save it's content for future processing
$prefix = array_key_exists('Prefix', $config) ? $config['Prefix'] : '';
preg_match($this->_moduleFolderRegExp, $filename, $rets);
$config['ModuleFolder'] = str_replace(DIRECTORY_SEPARATOR, '/', $rets[1]);
$config['BasePath'] = dirname(FULL_PATH . $filename);
if (array_key_exists('AdminTemplatePath', $config)) {
// append template base folder for admin templates path of this prefix
$module_templates = $rets[1] == 'core' ? '' : substr($rets[1], 8) . '/';
$config['AdminTemplatePath'] = $module_templates . $config['AdminTemplatePath'];
}
if (array_key_exists($prefix, $this->prefixFiles) && ($this->prefixFiles[$prefix] != $filename)) {
trigger_error(
'Single unit config prefix "<strong>' . $prefix . '</strong>" ' .
'is used in multiple unit config files: ' .
'"<strong>' . $this->prefixFiles[$prefix] . '</strong>", "<strong>' . $filename . '</strong>"',
E_USER_WARNING
);
}
$this->configData[$prefix] = $config;
$this->prefixFiles[$prefix] = $filename;
return $prefix;
}
else {
$prefix = array_search($filename, $this->prefixFiles);
if ( $prefix ) {
// attempt is made to include config file twice or more, but include_once prevents that,
// but file exists on hdd, then it is already saved to all required arrays, just return it's prefix
return $prefix;
}
}
}
return 'dummy';
}
function loadConfig($prefix)
{
if ( !isset($this->prefixFiles[$prefix]) ) {
throw new Exception('Configuration file for prefix <strong>' . $prefix . '</strong> is unknown');
return ;
}
$file = $this->prefixFiles[$prefix];
$prefix = $this->PreloadConfigFile($file);
if ($this->FinalStage) {
// run prefix OnAfterConfigRead so all
// hooks to it can define their clonses
$this->runAfterConfigRead($prefix);
}
$clones = $this->postProcessConfig($prefix, 'AggregateConfigs', 'sub_prefix');
$clones = array_merge($this->postProcessConfig($prefix, 'Clones', 'prefix'), $clones);
if ($this->FinalStage) {
$clones = array_unique($clones);
foreach ($clones as $a_prefix) {
$this->runAfterConfigRead($a_prefix);
}
}
}
function runAfterConfigRead($prefix)
{
if (in_array($prefix, $this->AfterConfigProcessed)) {
return ;
}
$this->Application->HandleEvent( new kEvent($prefix . ':OnAfterConfigRead') );
if (!(defined('IS_INSTALL') && IS_INSTALL)) {
// allow to call OnAfterConfigRead multiple times during install
array_push($this->AfterConfigProcessed, $prefix);
}
}
/**
* Reads unit (specified by $prefix)
* option specified by $option
*
* @param string $prefix
* @param string $name
* @param mixed $default
* @return string
* @access public
*/
function getUnitOption($prefix, $name, $default = false)
{
if (preg_match('/(.*)\.(.*)/', $prefix, $rets)) {
if (!isset($this->configData[$rets[1]])) {
$this->loadConfig($rets[1]);
}
$ret = isset($this->configData[$rets[1]][$name][$rets[2]]) ? $this->configData[$rets[1]][$name][$rets[2]] : false;
// $ret = getArrayValue($this->configData, $rets[1], $name, $rets[2]);
}
else {
if (!isset($this->configData[$prefix])) {
$this->loadConfig($prefix);
}
$ret = isset($this->configData[$prefix][$name]) ? $this->configData[$prefix][$name] : false;
// $ret = getArrayValue($this->configData, $prefix, $name);
}
return $ret === false ? $default : $ret;
}
/**
* Read all unit with $prefix options
*
* @param string $prefix
* @return Array
* @access public
*/
function getUnitOptions($prefix)
{
if (!isset($this->configData[$prefix])) {
$this->loadConfig($prefix);
}
return $this->configData[$prefix];
}
/**
* Set's new unit option value
*
* @param string $prefix
* @param string $name
* @param string $value
* @access public
*/
function setUnitOption($prefix, $name, $value)
{
if ( preg_match('/(.*)\.(.*)/', $prefix, $rets) ) {
if ( !isset($this->configData[$rets[1]]) ) {
$this->loadConfig($rets[1]);
}
$this->configData[$rets[1]][$name][$rets[2]] = $value;
}
else {
if ( !isset($this->configData[$prefix]) ) {
$this->loadConfig($prefix);
}
$this->configData[$prefix][$name] = $value;
}
}
protected function getClasses($prefix)
{
$config =& $this->configData[$prefix];
$class_params = Array ('ItemClass', 'ListClass', 'EventHandlerClass', 'TagProcessorClass');
$register_classes = isset($config['RegisterClasses']) ? $config['RegisterClasses'] : Array ();
foreach ($class_params as $param_name) {
if ( !isset($config[$param_name]) ) {
continue;
}
$config[$param_name]['pseudo'] = $this->getPseudoByOptionName($param_name, $prefix);
$register_classes[] = $config[$param_name];
}
return $register_classes;
}
protected function getPseudoByOptionName($option_name, $prefix)
{
$pseudo_class_map = Array (
'ItemClass' => '%s',
'ListClass' => '%s_List',
'EventHandlerClass' => '%s_EventHandler',
'TagProcessorClass' => '%s_TagProcessor'
);
return sprintf($pseudo_class_map[$option_name], $prefix);
}
/**
* Get's config file name based
* on folder name supplied
*
* @param string $folderPath
* @return string
* @access private
*/
function getConfigName($folderPath)
{
return $folderPath . DIRECTORY_SEPARATOR . basename($folderPath) . '_config.php';
}
/**
* Checks if config file is allowed for includion (if module of config is installed)
*
* @param string $config_path relative path from in-portal directory
*/
function configAllowed($config_path)
{
static $module_paths = null;
if (defined('IS_INSTALL') && IS_INSTALL) {
// at installation start no modules in db and kernel configs could not be read
return true;
}
if (preg_match('#^' . $this->_directorySeparator . 'core#', $config_path)) {
// always allow to include configs from "core" module's folder
return true;
}
if (!$this->Application->ModuleInfo) {
return false;
}
if (!isset($module_paths)) {
$module_paths = Array ();
foreach ($this->Application->ModuleInfo as $module_name => $module_info) {
$module_paths[] = str_replace('/', DIRECTORY_SEPARATOR, rtrim($module_info['Path'], '/'));
}
$module_paths = array_unique($module_paths);
}
preg_match($this->_moduleFolderRegExp, $config_path, $rets);
// config file path starts with module folder path
return in_array($rets[1], $module_paths);
}
/**
* Returns true if config exists and is allowed for reading
*
* @param string $prefix
* @return bool
*/
function prefixRegistred($prefix)
{
return isset($this->prefixFiles[$prefix]) ? true : false;
}
/**
* Returns config file for given prefix
*
* @param string $prefix
* @return string
*/
function getPrefixFile($prefix)
{
return array_key_exists($prefix, $this->prefixFiles) ? $this->prefixFiles[$prefix] : false;
}
function iterateConfigs($callback_function, $params)
{
$this->includeConfigFiles(MODULES_PATH); //make sure to re-read all configs
$this->AfterConfigRead();
foreach ($this->configData as $prefix => $config_data) {
$callback_function[0]->$callback_function[1]($prefix, $config_data, $params);
}
}
}
\ No newline at end of file
Index: branches/5.2.x/core/units/helpers/category_helper.php
===================================================================
--- branches/5.2.x/core/units/helpers/category_helper.php (revision 15225)
+++ branches/5.2.x/core/units/helpers/category_helper.php (revision 15226)
@@ -1,650 +1,636 @@
<?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 CategoryHelper extends kHelper {
/**
* Structure tree for ParentId field in category or category items
*
* @var Array
*/
var $_structureTree = null;
/**
* ID of primary language (only for caching)
*
* @var int
*/
var $_primaryLanguageId = false;
/**
* Prints category path using given blocks. Also supports used defined path elements at the end.
*
* @param Array $params
* @return string
*/
function NavigationBar($params)
{
$params['is_first'] = 1;
$main_category_id = isset($params['cat_id']) ? $params['cat_id'] : $this->Application->GetVar('m_cat_id');
if (array_key_exists('shift', $params) && $params['shift']) {
$home_element = '';
$params['shift']--;
}
else {
$home_element = $this->getHomeCategoryPath($params, $main_category_id);
unset($params['is_first']);
}
if (!getArrayValue($params, 'titles') && !getArrayValue($params, 'templates')) {
// no static templates given, show only category path
return $home_element . $this->getCategoryPath($main_category_id, $params);
}
$navigation_parts = $this->getNavigationParts($params['titles'], $params['templates']);
$ret = '';
$block_params = Array (); //$params; // sort of TagProcessor:prepareTagParams
$block_params['no_editing'] = 1;
$block_params['category'] = 0;
$block_params['separator'] = $params['separator'];
$show_category = getArrayValue($params, 'show_category');
$current_template = $this->Application->GetVar('t');
$physical_template = $this->Application->getPhysicalTemplate($current_template);
if ($physical_template !== false) {
// replace menu template name with it's actual template name on disk
list ($current_template) = explode(':', $physical_template, 2);
}
foreach ($navigation_parts as $template => $title) {
$block_params['template'] = $template;
if ($title == '__item__') {
if ($show_category) {
$ret .= $this->getCategoryPath($main_category_id, $params);
$show_category = false;
}
$category_path = $this->getCategoryParentPath($main_category_id);
$module_info = $this->getCategoryModule($params, array_keys($category_path));
if (!$module_info) {
continue;
}
$module_prefix = $module_info['Var'];
$object = $this->Application->recallObject($module_prefix);
/* @var $object kCatDBItem */
$title_field = $this->Application->getUnitOption($module_prefix, 'TitleField');
$block_params['title'] = $object->GetField($title_field);
$block_params['prefix'] = $module_prefix;
$block_params['current'] = 0;
$block_params['name'] = $this->SelectParam($params, 'module_item_render_as,render_as');
}
else {
$block_params['current'] = ($template == $current_template);
if ($title == '__page__') {
$block_params['title'] = $this->Application->ProcessParsedTag('st', 'PageInfo', Array ('type' => 'title'));
}
else {
$block_params['title'] = $this->Application->Phrase($title);
}
$block_params['name'] = $template == $current_template ? $params['current_render_as'] : $params['render_as'];
}
$ret .= $this->Application->ParseBlock($block_params);
}
if ($show_category) {
$params['no_current'] = true;
return $home_element . ($show_category ? $this->getCategoryPath($main_category_id, $params) : '') . $ret;
}
return $home_element . $ret;
}
/**
* Get navigation parts
*
* @param Array $titles
* @param Array $templates
* @return Array
*/
function getNavigationParts($titles, $templates)
{
$titles = explode(',', $titles);
$templates = explode(',', $templates);
$ret = Array ();
foreach ($templates as $template_pos => $template) {
$ret[$template] = $titles[$template_pos];
}
return $ret;
}
/**
* Renders path to given category using given blocks.
*
* @param int $main_category_id
* @param Array $params
* @return string
*/
function getCategoryPath($main_category_id, $params)
{
$category_path = $this->getCategoryParentPath($main_category_id);
if (!$category_path) {
// in "Home" category
return '';
}
if (array_key_exists('shift', $params) && $params['shift']) {
array_splice($category_path, 0, $params['shift']);
}
$module_info = $this->getCategoryModule($params, array_keys($category_path));
$module_category_id = $module_info['RootCat'];
$module_item_id = $this->Application->GetVar($module_info['Var'].'_id');
$ret = '';
$block_params['category'] = 1;
$block_params['no_editing'] = 1;
if (array_key_exists('is_first', $params)) {
$block_params['is_first'] = $params['is_first'];
}
$block_params['separator'] = $params['separator'];
$no_current = isset($params['no_current']) && $params['no_current'];
$backup_category_id = $this->Application->GetVar('c_id');
foreach ($category_path as $category_id => $category_name) {
$block_params['cat_id'] = $category_id;
$block_params['cat_name'] = $block_params['title'] = $category_name;
if ($no_current) {
$block_params['current'] = 0;
}
else {
$block_params['current'] = ($main_category_id == $category_id) && !$module_item_id ? 1 : 0;
}
$block_params['is_module_root'] = $category_id == $module_category_id ? 1 : 0;
$block_params['name'] = $this->SelectParam($params, 'render_as,block');
// which block to parse as current ?
if ($block_params['is_module_root']) {
$block_params['name'] = $this->SelectParam($params, 'module_root_render_as,render_as');
$block_params['module_index'] = $module_info['TemplatePath'].'index';
}
if ($block_params['current']) {
$block_params['name'] = $this->SelectParam($params, 'current_render_as,render_as');
}
$this->Application->SetVar('c_id', $category_id);
$ret .= $this->Application->ParseBlock($block_params);
if (array_key_exists('is_first', $block_params)) {
unset($block_params['is_first']);
}
}
$this->Application->SetVar('c_id', $backup_category_id);
return $ret;
}
/**
* Returns module information based on given module name or current category (relative to module root categories)
*
* @param Array $params
* @param Array $category_ids category parent path (already as array)
* @return Array
*/
function getCategoryModule($params, $category_ids)
{
if (isset($params['module'])) {
// get module by name specified
$module_info = $this->Application->findModule('Name', $params['module']);
}
elseif ($category_ids) {
// get module by category path
$module_root_categories = $this->getModuleRootCategories();
$common_categories = array_intersect($category_ids, $module_root_categories);
$module_category_id = array_shift($common_categories); // get 1st common category
$module_info = $this->Application->findModule('RootCat', $module_category_id);
}
return $module_info;
}
/**
* Renders path to top catalog category
*
* @param Array $params
* @param int $current_category
* @return string
*/
function getHomeCategoryPath($params, $current_category)
{
$block_params['cat_id'] = $this->Application->getBaseCategory();
$block_params['no_editing'] = 1;
$block_params['current'] = $current_category == $block_params['cat_id'] ? 1 : 0;
$block_params['separator'] = $params['separator'];
$block_params['is_first'] = $params['is_first'];
$block_params['cat_name'] = $this->Application->Phrase(($this->Application->isAdmin ? 'la_' : 'lu_') . 'rootcategory_name');
$block_params['name'] = $this->SelectParam($params, 'root_cat_render_as,render_as');
return $this->Application->ParseBlock($block_params);
}
/**
* Returns root categories from all modules
*
* @return Array
*/
function getModuleRootCategories()
{
static $root_categories = null;
if (!isset($root_categories)) {
$root_categories = Array ();
foreach ($this->Application->ModuleInfo as $module_name => $module_info) {
array_push($root_categories, $module_info['RootCat']);
}
$root_categories = array_unique($root_categories);
}
return $root_categories;
}
/**
* Returns given category's parent path as array of id=>name elements
*
* @param int $main_category_id
* @return Array
*/
function getCategoryParentPath($main_category_id)
{
if ( $main_category_id == 0 ) {
// don't query path for "Home" category
return Array ();
}
$cache_key = 'parent_paths_named[%CIDSerial:' . $main_category_id . '%]';
$cached_path = $this->Application->getCache($cache_key);
if ( $cached_path === false ) {
$ml_formatter = $this->Application->recallObject('kMultiLanguage');
/* @var $ml_formatter kMultiLanguage */
$navbar_field = $ml_formatter->LangFieldName('CachedNavBar');
$id_field = $this->Application->getUnitOption('c', 'IDField');
$table_name = $this->Application->getUnitOption('c', 'TableName');
$this->Conn->nextQueryCachable = true;
$sql = 'SELECT ' . $navbar_field . ', ParentPath
FROM ' . $table_name . '
WHERE ' . $id_field . ' = ' . $main_category_id;
$category_data = $this->Conn->GetRow($sql);
$cached_path = Array ();
$skip_category = $this->Application->getBaseCategory();
if ( $category_data ) {
$category_names = explode('&|&', $category_data[$navbar_field]);
$category_ids = explode('|', substr($category_data['ParentPath'], 1, -1));
foreach ($category_ids as $category_index => $category_id) {
if ( $category_id == $skip_category ) {
continue;
}
$cached_path[$category_id] = $category_names[$category_index];
}
}
$this->Application->setCache($cache_key, $cached_path);
}
return $cached_path;
}
/**
* Not tag. Method for parameter selection from list in this TagProcessor
*
* @param Array $params
* @param Array $possible_names
*
* @return string
* @access protected
*/
protected function SelectParam($params, $possible_names)
{
if ( !is_array($params) ) {
return '';
}
if ( !is_array($possible_names) ) {
$possible_names = explode(',', $possible_names);
}
foreach ($possible_names as $name) {
if ( isset($params[$name]) ) {
return $params[$name];
}
}
return '';
}
/**
* Converts multi-dimensional category structure in one-dimensional option array (category_id=>category_name)
*
* @param Array $data
* @param int $parent_category_id
* @param int_type $language_id
* @param int $theme_id
* @param int $level
* @return Array
*/
function _printChildren(&$data, $parent_category_id, $language_id, $theme_id, $level = 0)
{
if ($data['ThemeId'] != $theme_id && $data['ThemeId'] != 0) {
// don't show system templates from different themes
return Array ();
}
$category_language = $data['l' . $language_id . '_Name'] ? $language_id : $this->_primaryLanguageId;
$ret = Array($parent_category_id => str_repeat('&mdash;', $level).' '.$data['l' . $category_language . '_Name']);
if ($data['children']) {
$level++;
foreach ($data['children'] as $category_id => $category_data) {
// numeric keys
$ret = kUtil::array_merge_recursive($ret, $this->_printChildren($data['children'][$category_id], $category_id, $language_id, $theme_id, $level));
}
}
return $ret;
}
/**
* Returns information about children under parent path (recursive)
*
* @param int $parent_category_id
* @param Array $languages
* @return Array
*/
function _getChildren($parent_category_id, $languages)
{
static $items_by_parent = null, $parent_mapping = null;
if ( !isset($items_by_parent) ) {
$fields = $items_by_parent = Array ();
foreach ($languages as $language_id) {
$fields[] = 'l' . $language_id . '_Name';
}
$sql = 'SELECT CategoryId AS id, ' . implode(', ', $fields) . ', ParentId, Template, ThemeId
FROM ' . TABLE_PREFIX . 'Categories
ORDER BY Priority DESC';
$items = $this->Conn->Query($sql, 'id');
foreach ($items as $item_id => $item_data) {
$item_parent_id = $item_data['ParentId'];
unset($item_data['ParentId']);
if ( !array_key_exists($item_parent_id, $items_by_parent) ) {
$items_by_parent[$item_parent_id] = Array ();
}
$item_data['children'] = false;
$parent_mapping[$item_id] = $item_parent_id;
$items_by_parent[$item_parent_id][$item_id] = $item_data;
}
$base_category = $this->Application->getBaseCategory(); // "Content" category
$index_category = $this->findIndexCategoryId($items_by_parent[$base_category]);
// rename "Content" into "Home" keeping it's ID
$items_by_parent[ $parent_mapping[$base_category] ][$base_category]['l1_Name'] = $this->Application->Phrase('la_rootcategory_name');
// remove category of "index.tpl" template
unset($items_by_parent[$base_category][$index_category]);
unset($parent_mapping[$index_category]);
}
$data = $items_by_parent[ $parent_mapping[$parent_category_id] ][$parent_category_id];
$categories = array_key_exists($parent_category_id, $items_by_parent) ? $items_by_parent[$parent_category_id] : Array ();
foreach ($categories as $category_id => $category_data) {
if ($category_id == $parent_category_id) {
// don't process myself - prevents recursion
continue;
}
$data['children'][$category_id] = $this->_getChildren($category_id, $languages);
}
return $data;
}
function findIndexCategoryId($top_categories)
{
foreach ($top_categories as $category_id => $category_info) {
if ($category_info['Template'] == 'index') {
return $category_id;
}
}
return false;
}
/**
* Generates OR retrieves from cache structure tree
*
* @return Array
*/
function &_getStructureTree()
{
// get cached version of structure tree
if ( $this->Application->isCachingType(CACHING_TYPE_MEMORY) ) {
$data = $this->Application->getCache('master:StructureTree', false, CacheSettings::$structureTreeRebuildTime);
}
else {
$data = $this->Application->getDBCache('StructureTree', CacheSettings::$structureTreeRebuildTime);
}
if ($data) {
$data = unserialize($data);
return $data;
}
- if ( $this->Application->isCachingType(CACHING_TYPE_MEMORY) ) {
- $this->Application->rebuildCache('master:StructureTree', kCache::REBUILD_NOW, CacheSettings::$structureTreeRebuildTime);
- }
- else {
- $this->Application->rebuildDBCache('StructureTree', kCache::REBUILD_NOW, CacheSettings::$structureTreeRebuildTime);
- }
-
// generate structure tree from scratch
$ml_helper = $this->Application->recallObject('kMultiLanguageHelper');
/* @var $ml_helper kMultiLanguageHelper */
$languages = $ml_helper->getLanguages();
$root_category = $this->Application->getBaseCategory();
$data = $this->_getChildren($root_category, $languages);
if ($this->Application->isCachingType(CACHING_TYPE_MEMORY)) {
$this->Application->setCache('master:StructureTree', serialize($data));
}
else {
$this->Application->setDBCache('StructureTree', serialize($data));
}
return $data;
}
function getTemplateMapping()
{
if ( $this->Application->isCachingType(CACHING_TYPE_MEMORY) ) {
$data = $this->Application->getCache('master:template_mapping', false, CacheSettings::$templateMappingRebuildTime);
}
else {
$data = $this->Application->getDBCache('template_mapping', CacheSettings::$templateMappingRebuildTime);
}
if ( $data ) {
return unserialize($data);
}
- if ( $this->Application->isCachingType(CACHING_TYPE_MEMORY) ) {
- $this->Application->rebuildCache('master:template_mapping', kCache::REBUILD_NOW, CacheSettings::$templateMappingRebuildTime);
- }
- else {
- $this->Application->rebuildDBCache('template_mapping', kCache::REBUILD_NOW, CacheSettings::$templateMappingRebuildTime);
- }
-
$sql = 'SELECT
IF(c.`Type` = ' . PAGE_TYPE_TEMPLATE . ', CONCAT(c.Template, ":", c.ThemeId), CONCAT("id:", c.CategoryId)) AS SrcTemplate,
LOWER(
IF(
c.SymLinkCategoryId IS NOT NULL,
(SELECT cc.NamedParentPath FROM ' . TABLE_PREFIX . 'Categories AS cc WHERE cc.CategoryId = c.SymLinkCategoryId),
c.NamedParentPath
)
) AS DstTemplate,
c.UseExternalUrl, c.ExternalUrl
FROM ' . TABLE_PREFIX . 'Categories AS c
WHERE c.Status = ' . STATUS_ACTIVE;
$pages = $this->Conn->Query($sql, 'SrcTemplate');
$mapping = Array ();
$base_url = $this->Application->BaseURL();
foreach ($pages as $src_template => $page) {
// process external url, before placing in cache
if ($page['UseExternalUrl']) {
$external_url = $page['ExternalUrl'];
if (!preg_match('/^(.*?):\/\/(.*)$/', $external_url)) {
// url without protocol will be relative url to our site
$external_url = $base_url . $external_url;
}
$dst_template = 'external:' . $external_url;
}
else {
$dst_template = preg_replace('/^Content\//i', '', $page['DstTemplate']);
}
$mapping[$src_template] = $dst_template;
}
if ($this->Application->isCachingType(CACHING_TYPE_MEMORY)) {
$data = $this->Application->setCache('master:template_mapping', serialize($mapping));
}
else {
$this->Application->setDBCache('template_mapping', serialize($mapping));
}
return $mapping;
}
/**
* Returns category structure as field option list
*
* @return Array
*/
function getStructureTreeAsOptions()
{
if ((defined('IS_INSTALL') && IS_INSTALL) || !$this->Application->isAdmin) {
// no need to create category structure during install
// OR on Front-End, because it's not used there
return Array ();
}
if (isset($this->_structureTree)) {
return $this->_structureTree;
}
$themes_helper = $this->Application->recallObject('ThemesHelper');
/* @var $themes_helper kThemesHelper */
$data = $this->_getStructureTree();
$theme_id = (int)$themes_helper->getCurrentThemeId();
$this->_primaryLanguageId = $this->Application->GetDefaultLanguageId();
$this->_structureTree = $this->_printChildren($data, $data['id'], $this->Application->GetVar('m_lang'), $theme_id);
return $this->_structureTree;
}
/**
* Replace links like "@@ID@@" to actual template names in given text
*
* @param string $text
* @return string
*/
function replacePageIds($text)
{
if (!preg_match_all('/@@(\\d+)@@/', $text, $regs)) {
return $text;
}
$page_ids = $regs[1];
$sql = 'SELECT NamedParentPath, CategoryId
FROM ' . TABLE_PREFIX . 'Categories
WHERE CategoryId IN (' . implode(',', $page_ids) . ')';
$templates = $this->Conn->GetCol($sql, 'CategoryId');
$base_category = $this->Application->getBaseCategory();
$templates[$base_category] .= '/Index'; // "Content" category will act as "Home Page"
foreach ($page_ids as $page_id) {
if ( !isset($templates[$page_id]) ) {
// internal page was deleted, but link to it was found in given content block data
continue;
}
$url_params = Array ('m_cat_id' => $page_id == $base_category ? 0 : $page_id, 'pass' => 'm');
$page_url = $this->Application->HREF(strtolower($templates[$page_id]), '', $url_params);
/*if ($this->Application->isAdmin) {
$page_url = preg_replace('/&(admin|editing_mode)=[\d]/', '', $page_url);
}*/
$text = str_replace('@@' . $page_id . '@@', $page_url, $text);
}
return $text;
}
}
\ No newline at end of file
Index: branches/5.2.x/core/units/helpers/menu_helper.php
===================================================================
--- branches/5.2.x/core/units/helpers/menu_helper.php (revision 15225)
+++ branches/5.2.x/core/units/helpers/menu_helper.php (revision 15226)
@@ -1,394 +1,387 @@
<?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 MenuHelper extends kHelper {
/**
* Cached version of site menu
*
* @var Array
*/
var $Menu = null;
/**
* Parent path mapping used in CachedMenu tag
*
* @var Array
*/
var $parentPaths = Array ();
/**
* Builds site menu
*
* @param string $prefix_special
* @param Array $params
*
* @return string
* @access public
*/
public function menuTag($prefix_special, $params)
{
list ($menu, $root_path) = $this->_prepareMenu();
$cat = $this->_getCategoryId($params);
$parent_path = array_key_exists($cat, $this->parentPaths) ? $this->parentPaths[$cat] : '';
$parent_path = str_replace($root_path, '', $parent_path); // menu starts from module path
$levels = explode('|', trim($parent_path, '|'));
if ($levels[0] === '') {
$levels = Array ();
}
if (array_key_exists('level', $params) && $params['level'] > count($levels)) {
// current level is deeper, then requested level
return '';
}
$level = max(array_key_exists('level', $params) ? $params['level'] - 1 : count($levels) - 1, 0);
$parent = array_key_exists($level, $levels) ? $levels[$level] : 0;
$cur_menu =& $menu;
$menu_path = array_slice($levels, 0, $level + 1);
foreach ($menu_path as $elem) {
$cur_menu =& $cur_menu['c' . $elem]['sub_items'];
}
$block_params = $this->prepareTagParams($prefix_special, $params);
$block_params['name'] = $params['render_as'];
$this->Application->SetVar('cur_parent_path', $parent_path);
$real_cat_id = $this->Application->GetVar('m_cat_id');
if (!is_array($cur_menu) || !$cur_menu) {
// no menus on this level
return '';
}
$ret = '';
$cur_item = 1;
$cur_menu = $this->_removeNonMenuItems($cur_menu);
$block_params['total_items'] = count($cur_menu);
foreach ($cur_menu as $page) {
$block_params = array_merge(
$block_params,
$this->_prepareMenuItem($page, $real_cat_id, $root_path)
);
$block_params['is_last'] = $cur_item == $block_params['total_items'];
$block_params['is_first'] = $cur_item == 1;
$ret .= $this->Application->ParseBlock($block_params);
$cur_item++;
}
$this->Application->SetVar('m_cat_id', $real_cat_id);
return $ret;
}
/**
* Builds cached menu version
*
* @return Array
*/
function _prepareMenu()
{
static $root_cat = null;
static $root_path = null;
if (!$root_cat) {
$root_cat = $this->Application->getBaseCategory();
$cache_key = 'parent_paths[%CIDSerial:' . $root_cat . '%]';
$root_path = $this->Application->getCache($cache_key);
if ($root_path === false) {
$this->Conn->nextQueryCachable = true;
$sql = 'SELECT ParentPath
FROM ' . TABLE_PREFIX . 'Categories
WHERE CategoryId = ' . $root_cat;
$root_path = $this->Conn->GetOne($sql);
$this->Application->setCache($cache_key, $root_path);
}
}
if ( !$this->Menu ) {
if ( $this->Application->isCachingType(CACHING_TYPE_MEMORY) ) {
$menu = $this->Application->getCache('master:cms_menu', false, CacheSettings::$cmsMenuRebuildTime);
}
else {
$menu = $this->Application->getDBCache('cms_menu', CacheSettings::$cmsMenuRebuildTime);
}
if ($menu) {
$menu = unserialize($menu);
$this->parentPaths = $menu['parentPaths'];
}
else {
- if ( $this->Application->isCachingType(CACHING_TYPE_MEMORY) ) {
- $this->Application->rebuildCache('master:cms_menu', kCache::REBUILD_NOW, CacheSettings::$cmsMenuRebuildTime);
- }
- else {
- $this->Application->rebuildDBCache('cms_menu', kCache::REBUILD_NOW, CacheSettings::$cmsMenuRebuildTime);
- }
-
$menu = $this->_altBuildMenuStructure(Array ('CategoryId' => $root_cat, 'ParentPath' => $root_path));
$menu['parentPaths'] = $this->parentPaths;
if ($this->Application->isCachingType(CACHING_TYPE_MEMORY)) {
$this->Application->setCache('master:cms_menu', serialize($menu));
}
else {
$this->Application->setDBCache('cms_menu', serialize($menu));
}
}
unset($menu['parentPaths']);
$this->Menu = $menu;
}
return Array ($this->Menu, $root_path);
}
/**
* Returns category id based tag parameters
*
* @param Array $params
* @return int
*/
function _getCategoryId($params)
{
$cat = isset($params['category_id']) && $params['category_id'] != '' ? $params['category_id'] : $this->Application->GetVar('m_cat_id');
if ("$cat" == 'parent') {
$this_category = $this->Application->recallObject('c');
/* @var $this_category kDBItem */
$cat = $this_category->GetDBField('ParentId');
}
elseif ($cat == 0) {
$cat = $this->Application->getBaseCategory();
}
return $cat;
}
/**
* Prepares cms menu item block parameters
*
* @param Array $page
* @param int $real_cat_id
* @param string $root_path
* @return Array
*/
function _prepareMenuItem($page, $real_cat_id, $root_path)
{
static $language_id = null;
static $primary_language_id = null;
static $template = null;
if (!isset($language_id)) {
$language_id = $this->Application->GetVar('m_lang');
$primary_language_id = $this->Application->GetDefaultLanguageId();
$template = $this->Application->GetVar('t');
}
$active = $category_active = false;
$title = $page['l' . $language_id . '_ItemName'] ? $page['l' . $language_id . '_ItemName'] : $page['l' . $primary_language_id . '_ItemName'];
if ($page['ItemType'] == 'cat') {
if (array_key_exists($real_cat_id, $this->parentPaths)) {
$active = strpos($this->parentPaths[$real_cat_id], $page['ParentPath']) !== false;
}
elseif ($page['ItemPath'] == $template) {
// physical template in menu
$active = true;
}
$category_active = $page['CategoryId'] == $real_cat_id;
}
/*if ($page['ItemType'] == 'cat_index') {
$check_path = str_replace($root_path, '', $page['ParentPath']);
$active = strpos($parent_path, $check_path) !== false;
}
if ($page['ItemType'] == 'page') {
$active = $page['ItemPath'] == preg_replace('/^Content\//i', '', $this->Application->GetVar('t'));
}*/
if ( substr($page['ItemPath'], 0, 3) == 'id:' ) {
// resolve ID path here, since it can be used directly without m_Link tag (that usually resolves it)
$page['ItemPath'] = $this->Application->getVirtualPageTemplate(substr($page['ItemPath'], 3));
}
$block_params = Array (
'title' => $title,
'template' => $page['ItemPath'],
'active' => $active,
'category_active' => $category_active, // new
'parent_path' => $page['ParentPath'],
'parent_id' => $page['ParentId'],
'cat_id' => $page['CategoryId'],
'item_type' => $page['ItemType'],
'page_id' => $page['ItemId'],
'use_section' => ($page['Type'] == PAGE_TYPE_TEMPLATE) && ($page['ItemPath'] != 'index'),
'has_sub_menu' => isset($page['sub_items']) && count($page['sub_items']) > 0,
'external_url' => $page['UseExternalUrl'] ? $page['ExternalUrl'] : false, // for backward compatibility
'menu_icon' => $page['UseMenuIconUrl'] ? $page['MenuIconUrl'] : false,
);
return $block_params;
}
/**
* Returns only items, that are visible in menu
*
* @param Array $menu
* @return Array
*/
function _removeNonMenuItems($menu)
{
$theme_id = $this->Application->GetVar('m_theme');
foreach ($menu as $menu_index => $menu_item) {
// $menu_index is in "cN" format, where N is category id
if (!$menu_item['IsMenu'] || $menu_item['Status'] != STATUS_ACTIVE || ($menu_item['ThemeId'] != $theme_id && $menu_item['ThemeId'] != 0)) {
// don't show sections, that are not from menu OR system templates from other themes
unset($menu[$menu_index]);
}
}
return $menu;
}
/**
* Builds cache for children of given category (no matter, what menu status is)
*
* @param Array $parent
* @return Array
*/
function _altBuildMenuStructure($parent)
{
static $lang_part = null;
if (!isset($lang_part)) {
$ml_helper = $this->Application->recallObject('kMultiLanguageHelper');
/* @var $ml_helper kMultiLanguageHelper */
$lang_part = '';
$languages = $ml_helper->getLanguages();
foreach ($languages as $language_id) {
$lang_part .= 'c.l' . $language_id . '_MenuTitle AS l' . $language_id . '_ItemName,' . "\n";
}
}
// Sub-categories from current category
$items = $this->getSubCategories( $parent['CategoryId'] );
// sort menu items
uasort($items, Array (&$this, '_menuSort'));
// store menu items
$the_items = Array();
foreach ($items as $index => $an_item) {
$the_items[ $an_item['ItemId'] ] = $an_item;
$this->parentPaths[ $an_item['CategoryId'] ] = $an_item['ParentPath'];
}
// process submenus of each menu
$items = $the_items;
foreach ($items as $key => $menu_item) {
if ($menu_item['CategoryId'] == $parent['CategoryId']) {
// don't process myself - prevents recursion
continue;
}
$sub_items = $this->_altBuildMenuStructure($menu_item);
if ($sub_items) {
$items[$key]['sub_items'] = $sub_items;
}
}
return $items;
}
function getSubCategories($parent_id)
{
static $items_by_parent = null;
if (!isset($items_by_parent)) {
$ml_helper = $this->Application->recallObject('kMultiLanguageHelper');
/* @var $ml_helper kMultiLanguageHelper */
$lang_part = '';
$items_by_parent = Array ();
$languages = $ml_helper->getLanguages();
foreach ($languages as $language_id) {
$lang_part .= 'c.l' . $language_id . '_MenuTitle AS l' . $language_id . '_ItemName,' . "\n";
}
// Sub-categories from current category
$sql = 'SELECT
c.CategoryId AS CategoryId,
CONCAT(\'c\', c.CategoryId) AS ItemId,
c.Priority AS ItemPriority,
' . $lang_part . '
IF(c.`Type` = ' . PAGE_TYPE_TEMPLATE . ', c.Template, CONCAT("id:", c.CategoryId)) AS ItemPath,
c.ParentPath AS ParentPath,
c.ParentId As ParentId,
\'cat\' AS ItemType,
c.IsMenu, c.Type, c.ThemeId, c.UseExternalUrl, c.ExternalUrl, c.UseMenuIconUrl, c.MenuIconUrl,
c.Status
FROM ' . TABLE_PREFIX . 'Categories AS c';
$items = $this->Conn->Query($sql, 'ItemId');
foreach ($items as $item_id => $item_data) {
$item_parent_id = $item_data['ParentId'];
if ( !array_key_exists($item_parent_id, $items_by_parent) ) {
$items_by_parent[$item_parent_id] = Array ();
}
$items_by_parent[$item_parent_id][$item_id] = $item_data;
}
}
return array_key_exists($parent_id, $items_by_parent) ? $items_by_parent[$parent_id] : Array ();
}
/**
* Method for sorting pages by priority in decending order
*
* @param Array $a
* @param Array $b
* @return int
*/
function _menuSort($a, $b)
{
if ($a['ItemPriority'] == $b['ItemPriority']) {
return 0;
}
return ($a['ItemPriority'] < $b['ItemPriority']) ? 1 : -1; //descending
}
}
Index: branches/5.2.x/core/units/helpers/site_helper.php
===================================================================
--- branches/5.2.x/core/units/helpers/site_helper.php (revision 15225)
+++ branches/5.2.x/core/units/helpers/site_helper.php (revision 15226)
@@ -1,154 +1,147 @@
<?php
/**
* @version $Id$
* @package In-Portal
* @copyright Copyright (C) 1997 - 2010 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 SiteHelper extends kHelper {
/**
* Returns default country
*
* @param string $country_prefix
* @param bool $iso_format
* @return int
*/
function getDefaultCountry($country_prefix = '', $iso_format = true)
{
$country = $this->Application->siteDomainField($country_prefix . 'Country');
if ($iso_format && !$country) {
$country = 'USA';
}
if (!$iso_format && strlen($country)) {
return $this->getCountryId($country);
}
return $country;
}
/**
* Returns country id based on it's ISO code
*
* @param string $iso_code
* @return int
*/
function getCountryId($iso_code)
{
static $cache = null;
if (!isset($cache)) {
$sql = 'SELECT CountryStateId, IsoCode
FROM ' . $this->Application->getUnitOption('country-state', 'TableName') . '
WHERE Type = ' . DESTINATION_TYPE_COUNTRY;
$cache = $this->Conn->GetCol($sql, 'IsoCode');
}
return $cache[$iso_code];
}
/**
* Gets site domains from cache
*
* @return Array
*/
function getSiteDomains()
{
static $cache = null;
if ( !isset($cache) ) {
if ( $this->Application->isCachingType(CACHING_TYPE_MEMORY) ) {
$cache = $this->Application->getCache('master:domains_parsed', false, CacheSettings::$domainsParsedRebuildTime);
}
else {
$cache = $this->Application->getDBCache('domains_parsed', CacheSettings::$domainsParsedRebuildTime);
}
if ($cache) {
$cache = unserialize($cache);
}
else {
- if ( $this->Application->isCachingType(CACHING_TYPE_MEMORY) ) {
- $this->Application->rebuildCache('master:domains_parsed', kCache::REBUILD_NOW, CacheSettings::$domainsParsedRebuildTime);
- }
- else {
- $this->Application->rebuildDBCache('domains_parsed', kCache::REBUILD_NOW, CacheSettings::$domainsParsedRebuildTime);
- }
-
$sql = 'SELECT *
FROM ' . TABLE_PREFIX . 'SiteDomains
ORDER BY Priority DESC';
$cache = $this->Conn->Query($sql, 'DomainId');
if ($this->Application->isCachingType(CACHING_TYPE_MEMORY)) {
$this->Application->setCache('master:domains_parsed', serialize($cache));
}
else {
$this->Application->setDBCache('domains_parsed', serialize($cache));
}
}
}
return $cache;
}
/**
* Try to match visited domain to any of existing
*
* @param string $field
* @param string $value
* @return int
*/
function getDomainByName($field, $value)
{
$site_domains = $this->getSiteDomains();
$name_fields = Array ('DomainName', 'SSLUrl');
foreach ($site_domains as $id => $site_domain) {
if ( in_array($field, $name_fields) ) {
if ( !$site_domain[$field . 'UsesRegExp'] ) {
// not regular expression -> escape manually
$site_domain[$field] = preg_quote($site_domain[$field], '/');
}
if ( $site_domain[$field] && preg_match('/^' . $site_domain[$field] . ($field == 'DomainName' ? '$' : '') . '/', $value) ) {
return $id;
}
}
elseif ( $site_domain[$field] == $value ) {
return $id;
}
}
return false;
}
/**
* Try to match domain settings based on visitor's IP address
*
* @return int
*/
function getDomainByIP()
{
$site_domains = $this->getSiteDomains();
foreach ($site_domains as $id => $site_domain) {
if (kUtil::ipMatch($site_domain['DomainIPRange'], "\n")) {
return $id;
}
}
return false;
}
}
Index: branches/5.2.x/core/units/helpers/sections_helper.php
===================================================================
--- branches/5.2.x/core/units/helpers/sections_helper.php (revision 15225)
+++ branches/5.2.x/core/units/helpers/sections_helper.php (revision 15226)
@@ -1,385 +1,378 @@
<?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!');
/**
* Processes sections info from the configs
*
*/
class kSectionsHelper extends kHelper {
/**
* Holds information about all sections
*
* @var Array
*/
var $Tree = Array();
/**
* Checks, that we are in debug mode
*
* @var bool
*/
var $debugMode = false;
/**
* Checks, that we are in super admin mode
*
* @var bool
*/
var $superAdminMode = false;
public function __construct()
{
parent::__construct();
$this->debugMode = $this->Application->isDebugMode();
$this->superAdminMode = $this->Application->RecallVar('super_admin');
}
/**
* Set's prefix and special
*
* @param string $prefix
* @param string $special
* @access public
*/
public function Init($prefix, $special)
{
parent::Init($prefix, $special);
$this->BuildTree();
}
/**
* Builds xml for tree in left frame in admin
*
* @return void
* @access public
*/
public function BuildTree()
{
if ( $this->Application->isCachingType(CACHING_TYPE_MEMORY) ) {
$data = $this->Application->getCache('master:sections_parsed', false, CacheSettings::$sectionsParsedRebuildTime);
}
else {
$data = $this->Application->getDBCache('sections_parsed', CacheSettings::$sectionsParsedRebuildTime);
}
if ( $data ) {
$this->Tree = unserialize($data);
return ;
}
- if ( $this->Application->isCachingType(CACHING_TYPE_MEMORY) ) {
- $this->Application->rebuildCache('master:sections_parsed', kCache::REBUILD_NOW, CacheSettings::$sectionsParsedRebuildTime);
- }
- else {
- $this->Application->rebuildDBCache('sections_parsed', kCache::REBUILD_NOW, CacheSettings::$sectionsParsedRebuildTime);
- }
-
if ( !defined('IS_INSTALL') || !IS_INSTALL ) {
// don't reread all configs during install, because they are reread on every install step
$this->Application->UnitConfigReader->ReReadConfigs();
}
$this->Tree = Array ();
// 1. build base tree (don't update parent with children list yet)
// 1.1. process prefixes without priority
$prioritized_prefixes = Array ();
$prefixes = array_keys($this->Application->UnitConfigReader->configData);
foreach ($prefixes as $prefix) {
$config =& $this->Application->UnitConfigReader->configData[$prefix];
if ( array_key_exists('ConfigPriority', $config) ) {
$prioritized_prefixes[$prefix] = $config['ConfigPriority'];
continue;
}
$this->_processPrefixSections($prefix);
}
// 2. process prefixes with priority
asort($prioritized_prefixes);
foreach ($prioritized_prefixes as $prefix => $priority) {
$this->_processPrefixSections($prefix);
}
// 2. apply section adjustments
foreach ($prefixes as $prefix) {
$config =& $this->Application->UnitConfigReader->configData[$prefix];
$section_adjustments = getArrayValue($config, 'SectionAdjustments');
/* @var $section_adjustments Array */
if ( !$section_adjustments ) {
continue;
}
foreach ($section_adjustments as $section_name => $adjustment_params) {
if ( is_array($adjustment_params) ) {
if ( !array_key_exists($section_name, $this->Tree) ) {
// don't process adjustments for non-existing sections
continue;
}
$this->Tree[$section_name] = kUtil::array_merge_recursive($this->Tree[$section_name], $adjustment_params);
}
else {
// then remove section
unset($this->Tree[$section_name]);
}
}
}
// 3.
foreach ($this->Tree as $section_name => $section_params) {
// 3.1. update parent -> children references
$parent_section = $section_params['parent'];
$section_order = "{$section_params['priority']}";
if ( !isset($parent_section) ) {
// don't process parent section of "in-portal:root" section
continue;
}
if ( !array_key_exists('children', $this->Tree[$parent_section]) ) {
$this->Tree[$parent_section]['children'] = Array ();
}
if ( array_key_exists($section_order, $this->Tree[$parent_section]['children']) ) {
trigger_error('Section "<strong>' . $section_name . '</strong>" has replaced section "<strong>' . $this->Tree[$parent_section]['children'][$section_order] . '</strong>" (parent section: "<strong>' . $parent_section . '</strong>"; duplicate priority: <strong>' . $section_order . '</strong>)', E_USER_WARNING);
}
$this->Tree[$parent_section]['children'][$section_order] = $section_name;
if ( $section_params['type'] == stTAB ) {
// if this is tab, then mark parent section as TabOnly
$this->Tree[$parent_section]['tabs_only'] = true;
}
// 3.2. process icons here, because they also can be adjusted
if ( isset($section_params['icon']) && preg_match('/([^:]+):(.*)/', $section_params['icon'], $regs) ) {
$this->Tree[$section_name]['icon'] = $regs[2];
$this->Tree[$section_name]['icon_module'] = $regs[1]; // set "icon_module" used in "combined_header" block
$module_folder = trim($this->Application->findModule('Name', $regs[1], 'Path'), '/');
if ( $module_folder == '' ) {
$module_folder = 'core';
}
}
else {
$module_folder = $this->Application->getUnitOption($section_params['SectionPrefix'], 'ModuleFolder');
if ( !array_key_exists('icon_module', $section_params) ) {
// set "icon_module" used in "combined_header" block
$this->Tree[$section_name]['icon_module'] = $this->Application->findModule('Path', $module_folder . '/', 'Name');
}
}
// this is to display HELP icon instead of missing one.. can be replaced with some other icon to draw attention
$icon_file = $module_folder . '/admin_templates/img/icons/icon24_' . $this->Tree[$section_name]['icon'];
/*$core_file = FULL_PATH.'/core/admin_templates/img/icons/icon24_' . $this->Tree[$section_name]['icon'].'.png';
if ($module_folder != 'core' && file_exists($core_file) && file_exists(FULL_PATH.'/'.$icon_file.'.png')) {
if (crc32(file_get_contents($core_file)) == crc32(file_get_contents(FULL_PATH.'/'.$icon_file.'.png'))) {
trigger_error('Section "<strong>' . $section_name . '</strong>" uses icon copy from "Core" module', E_USER_NOTICE);
}
}*/
if ( !file_exists(FULL_PATH . '/' . $icon_file . '.png') ) {
$this->Tree[$section_name]['icon'] = 'help';
$this->Tree[$section_name]['icon_module'] = 'core';
}
}
$this->Application->HandleEvent(new kEvent('adm:OnAfterBuildTree'));
if ( $this->Application->isCachingType(CACHING_TYPE_MEMORY) ) {
$this->Application->setCache('master:sections_parsed', serialize($this->Tree));
}
else {
$this->Application->setDBCache('sections_parsed', serialize($this->Tree));
}
}
function _processPrefixSections($prefix)
{
$config =& $this->Application->UnitConfigReader->configData[$prefix];
$sections = getArrayValue($config, 'Sections');
/* @var $sections Array */
if ( !$sections ) {
return ;
}
foreach ($sections as $section_name => $section_params) {
// we could also skip not allowed sections here in future
if ( isset($section_params['SectionPrefix']) ) {
$section_prefix = $section_params['SectionPrefix'];
}
elseif ( $this->Application->getUnitOption($prefix, 'SectionPrefix') ) {
$section_prefix = $this->Application->getUnitOption($prefix, 'SectionPrefix');
}
else {
$section_prefix = $prefix;
}
if ( is_float($section_params['priority']) ) {
$section_params['priority'] = (string)$section_params['priority'];
}
$section_params['SectionPrefix'] = $section_prefix;
$section_params['url']['m_opener'] = 'r';
$section_params['url']['no_pass_through'] = 1;
$pass_section = getArrayValue($section_params, 'url', 'pass_section');
if ( $pass_section ) {
unset($section_params['url']['pass_section']);
$section_params['url']['section'] = $section_name;
if ( !isset($section_params['url']['module']) ) {
$module_name = $this->Application->findModule('Path', $config['ModuleFolder'] . '/', 'Name');
$section_params['url']['module'] = $module_name;
}
}
if ( !isset($section_params['url']['t']) ) {
$section_params['url']['t'] = 'index';
}
if ( !isset($section_params['onclick']) ) {
$section_params['onclick'] = 'checkEditMode()';
}
if ( !isset($section_params['container']) ) {
$section_params['container'] = 0; // for js tree printing to xml
}
$current_data = isset($this->Tree[$section_name]) ? $this->Tree[$section_name] : Array ();
if ( $current_data ) {
trigger_error('Section "<strong>' . $section_name . '</strong>" declaration (originally defined in "<strong>' . $current_data['SectionPrefix'] . '</strong>") was overwriten from "<strong>' . $prefix . '</strong>"', E_USER_WARNING);
}
$this->Tree[$section_name] = kUtil::array_merge_recursive($current_data, $section_params);
}
}
/**
* Returns details information about section
*
* @param string $section_name
* @return Array
*/
function &getSectionData($section_name)
{
if (isset($this->Tree[$section_name])) {
$ret =& $this->Tree[$section_name];
}
else {
$ret = Array();
}
return $ret;
}
/**
* Returns first child, that is not a folder
*
* @param string $section_name
* @param bool $check_permission
* @return string
* @access public
*/
public function getFirstChild($section_name, $check_permission = false)
{
$section_data =& $this->getSectionData($section_name);
$children = isset($section_data['children']) && $section_data['children'] ? $section_data['children'] : false;
/* @var $children Array */
if ( $children ) {
// get 1st child
ksort($children, SORT_NUMERIC);
foreach ($children as $child_section) {
if ( !$this->sectionVisible($child_section, $check_permission) ) {
continue;
}
break;
}
return $this->getFirstChild($child_section, $check_permission);
}
return $section_name;
}
/**
* Checks if given section is visible by it's definition and optionally by user permission
*
* @param string $section_name
* @param bool $check_permission
* @return bool
*/
function sectionVisible($section_name, $check_permission = false)
{
$section_data =& $this->getSectionData($section_name);
if (isset($section_data['show_mode']) && is_numeric($section_data['show_mode'])) {
$show_mode = $section_data['show_mode'];
// if super admin section -> show in super admin mode & debug mode
$show_section = $show_mode == smNORMAL || ((($show_mode & smSUPER_ADMIN) == smSUPER_ADMIN) && ($this->superAdminMode || $this->debugMode));
if (!$show_section) {
// if section is in debug mode only && debug mode -> show
$show_section = (($show_mode & smDEBUG) == smDEBUG) && $this->debugMode;
}
if (!$show_section) {
// visibility by section definition
return false;
}
}
// visibility by section permission
if ($check_permission) {
$perm_section = $this->getPermSection($section_name);
return $this->Application->CheckPermission($perm_section.'.view');
}
return true;
}
/**
* Returns section for permission checking based on given section
*
* @param string $section_name
* @return string
*/
function getPermSection($section_name)
{
$ret = $section_name;
$section_data =& $this->getSectionData($section_name);
if ($section_data && isset($section_data['perm_prefix'])) {
// this section uses other section permissions
$ret = $this->Application->getUnitOption($section_data['perm_prefix'].'.main', 'PermSection');
}
return $ret;
}
}
\ No newline at end of file

Event Timeline