Page MenuHomeIn-Portal Phabricator

in-portal
No OneTemporary

File Metadata

Created
Sun, Feb 2, 4:15 PM

in-portal

Index: branches/5.0.x/core/kernel/event_manager.php
===================================================================
--- branches/5.0.x/core/kernel/event_manager.php (revision 13273)
+++ branches/5.0.x/core/kernel/event_manager.php (revision 13274)
@@ -1,811 +1,811 @@
<?php
/**
* @version $Id$
* @package In-Portal
* @copyright Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license GNU/GPL
* In-Portal is Open Source software.
* This means that this software may have been modified pursuant
* the GNU General Public License, and as distributed it includes
* or is derivative of works licensed under the GNU General Public License
* or other free or open source software licenses.
* See http://www.in-portal.org/license for copyright notices and details.
*/
defined('FULL_PATH') or die('restricted access!');
define('hBEFORE', 1);
define('hAFTER', 2);
define('reBEFORE', 1);
define('reAFTER', 2);
class kEventManager extends kBase {
/**
* Connection to database
*
* @var kDBConnection
* @access public
*/
var $Conn;
/**
* Cache of QueryString parameters
* from config, that are represented
* in enviroment variable
*
* @var Array
*/
var $queryMaps = Array();
/**
* Build events registred for
* pseudo classes. key - pseudo class
* value - event name
*
* @var Array
* @access private
*/
var $buildEvents=Array();
/**
* Events, that should be run before parser initialization
*
* @var Array
*/
var $beforeRegularEvents = Array();
/**
* Events, that should be run after parser initialization
*
* @var Array
*/
var $afterRegularEvents = Array();
/**
* Holds before hooks
* key - prefix.event (to link to)
* value - hooked event info
*
* @var Array
* @access private
*/
var $beforeHooks=Array();
/**
* Holds after hooks
* key - prefix.event (to link to)
* value - hooked event info
*
* @var Array
* @access private
*/
var $afterHooks = Array();
var $recursionStack = Array();
function kEventManager()
{
parent::kBase();
$this->Conn =& $this->Application->GetADODBConnection();
}
/**
* Returns information about registered regular events
*
* @param bool $from_cache
*
* @return Array
*/
function getRegularEvents($from_cache = false)
{
static $agents = null;
if ($from_cache) {
return Array (
reBEFORE => $this->beforeRegularEvents,
reAFTER => $this->afterRegularEvents,
);
}
else {
if (!isset($agents)) {
$sql = 'SELECT *
FROM ' . $this->Application->getUnitOption('agent', 'TableName') . '
WHERE Status = ' . STATUS_ACTIVE . ' AND LastRunStatus <> ' . AGENT_LAST_RUN_RUNNING;
$all_agents = $this->Conn->Query($sql);
$agents = Array (
reBEFORE => Array (),
reAFTER => Array (),
);
foreach ($all_agents as $agent_data) {
$agents[ $agent_data['RunMode'] ][ $agent_data['AgentName'] ] = Array (
'EventName' => $agent_data['Event'],
'RunInterval' => (int)$agent_data['RunInterval'],
'LastRunOn' => (int)$agent_data['LastRunOn'],
'NextRunOn' => (int)$agent_data['NextRunOn'],
'Status' => $agent_data['Status'],
);
}
}
return $agents;
}
}
/**
* Set's new enviroment parameter mappings
* between their names as application vars
*
* @param Array $new_query_maps
* @access public
*/
/*function setQueryMaps($new_query_maps)
{
$this->queryMaps = $new_query_maps;
}*/
/**
* Adds new query map to already parsed query maps
*
* @param string $prefix
*/
function setQueryMap($prefix_special)
{
list($prefix) = explode('.', $prefix_special);
$query_map = $this->getQueryMap($prefix);
if ($query_map) {
$this->queryMaps[$prefix_special] = $query_map;
}
else {
unset($this->queryMaps[$prefix]);
}
// 'passed' is set later in ProcessRequest - do we really need it here? (it breakes HTTPQuery initialization...)
// $this->Application->SetVar('passed', implode(',', array_keys($this->queryMaps)) );
return $query_map;
}
/**
* Returns QueryMap for requested unit config. In case if unit config is a clone, then get parent item's (from prefix) config to create clone
*
* @param string $prefix
* @return Array
*/
function getQueryMap($prefix)
{
$query_map = $this->Application->getUnitOption($prefix, 'QueryString');
if (!$query_map) {
if (preg_match('/(.*?)-(.*)/', $prefix, $regs)) {
// #prefix - format for configs, that are only cloned & optionally used for hooking (without # is old format)
$check_prefixes = Array ('#'.$regs[2], $regs[2]);
foreach ($check_prefixes as $check_prefix) {
if ($this->Application->UnitConfigReader->prefixRegistred($check_prefix)) {
return $this->Application->getUnitOption($check_prefix, 'QueryString');
}
}
}
}
return $query_map;
}
/**
* Registers new regular event
*
* @param string $short_name name to be used to store last maintenace run info
* @param string $event_name
* @param int $run_interval run interval in seconds
* @param int $type before or after regular event
*/
function registerRegularEvent($short_name, $event_name, $run_interval, $type = reBEFORE, $status = STATUS_ACTIVE)
{
if($type == reBEFORE)
{
$this->beforeRegularEvents[$short_name] = Array('EventName' => $event_name, 'RunInterval' => $run_interval, 'Status' => $status);
}
else
{
$this->afterRegularEvents[$short_name] = Array('EventName' => $event_name, 'RunInterval' => $run_interval, 'Status' => $status);
}
}
function registerBuildEvent($pseudo_class,$build_event_name)
{
$this->buildEvents[$pseudo_class]=$build_event_name;
}
/**
* Returns build event by pseudo class
* name if any defined in config
*
* @param string $pseudo_class
* @return kEvent
* @access public
*/
function &getBuildEvent($pseudo_class)
{
$false = false;
if( !isset($this->buildEvents[$pseudo_class]) ) return $false;
$event = new kEvent();
$event->Name=$this->buildEvents[$pseudo_class];
$event->MasterEvent=null;
return $event;
}
/**
* Check if event is called twice, that causes recursion
*
* @param kEvent $event
*/
function isRecursion(&$event)
{
$event_key = $event->getPrefixSpecial().':'.$event->Name;
return in_array($event_key, $this->recursionStack) ? true : false;
}
function pushEvent(&$event)
{
$event_key = $event->getPrefixSpecial().':'.$event->Name;
array_push($this->recursionStack, $event_key);
}
function popEvent()
{
array_pop($this->recursionStack);
}
/**
* Allows to process any type of event
*
* @param kEvent $event
* @access public
*/
function HandleEvent(&$event)
{
if ($this->isRecursion($event)) {
return true;
}
$this->pushEvent($event);
if( !$this->Application->prefixRegistred($event->Prefix) )
{
$unit_config_reader =& $this->Application->recallObject('kUnitConfigReader');
$unit_config_reader->loadConfig($event->Prefix);
if( !$this->Application->prefixRegistred($event->Prefix) )
{
trigger_error('Prefix <b>'.$event->Prefix.'</b> not registred (requested event <b>'.$event->Name.'</b>)', E_USER_NOTICE);
return false;
}
}
if (!$event->SkipBeforeHooks) {
$this->processHooks($event, hBEFORE);
if ($event->status == erFATAL) return true;
}
$event_handler =& $this->Application->recallObject($event->Prefix.'_EventHandler');
/* @var $event_handler kEventHandler */
$event_handler->processEvent($event);
if ($event->status == erFATAL) return true;
if (!$event->SkipAfterHooks) {
$this->processHooks($event, hAFTER);
}
$this->popEvent();
return true;
}
/**
* Returns event names given in POST
*
* @return Array
*/
function _getEventsFromPost()
{
$events = $this->Application->GetVar('events');
if ($events === false) {
return Array ();
}
$ret = Array ();
foreach ($events as $prefix_special => $event_name) {
if (!$event_name) {
continue;
}
if (is_array($event_name)) {
// HTML-input names like "events[prefix.special][event_name]", input value don't matter
$event_name = key($event_name);
$this->Application->SetVar($prefix_special . '_event', $event_name);
}
// HTML-input names like "events[prefix.special]", input value is event name
$ret[$prefix_special] = $event_name;
}
return $ret;
}
function ProcessRequest()
{
$this->processOpener();
// 1. get events from $_POST
$events = $this->_getEventsFromPost();
// 2. if nothing there, then try to find them in $_GET
if ($this->queryMaps && !$events) {
// if we got $_GET type submit (links, not javascript)
foreach ($this->queryMaps as $prefix_special => $query_map) {
$query_map = array_flip($query_map);
if (isset($query_map['event'])) {
$event_name = $this->Application->GetVar($prefix_special . '_event');
if ($event_name) {
$events[$prefix_special] = $event_name;
}
}
}
// used ?
$actions = $this->Application->GetVar('do');
if ($actions) {
list ($prefix, $event_name) = explode('_', $actions);
if ($event_name) {
$events[$prefix] = $event_name;
}
}
}
// 3. store all prefixes passed before event processing, because they are used by GetTopmostPrefix
$all_passed = explode(',', $this->Application->GetVar('passed'));
foreach ($events as $prefix_special => $event_name) {
if (!$event_name) {
continue;
}
if ($this->Application->isAdmin) {
array_push($all_passed, $prefix_special);
}
else {
// don't add special on front-end because of category item list special is autogenerated
$prefix_special = explode('.', $prefix_special);
array_push($all_passed, $prefix_special[0]);
}
}
$this->Application->SetVar('all_passed', implode(',', $all_passed));
foreach ($events as $prefix_special => $event_name) {
$event = new kEvent();
$event->Name = $event_name;
$event->Prefix_Special = $prefix_special;
$prefix_special = explode('.',$prefix_special);
$event->Prefix = $prefix_special[0];
// array_push($passed, $prefix_special[0]);
$event->Special = isset($prefix_special[1]) ? $prefix_special[1] : '';
$event->redirect_params = Array('opener' => 's', 'pass' => 'all');
$event->redirect = true;
$event_handler =& $this->Application->recallObject($event->Prefix.'_EventHandler');
/* @var $event_handler kEventHandler */
if (preg_match('/(.*?)-(.*)/', $event->Prefix, $regs) && $this->Application->UnitConfigReader->prefixRegistred($regs[1])) {
// this is event from cloned config -> load parent config to create valid clone
$this->Application->UnitConfigReader->loadConfig($regs[1]);
- $this->Application->HandleEvent( new kEvent($regs[1].':OnAfterConfigRead') );
+ $this->Application->UnitConfigReader->runAfterConfigRead($regs[1]);
}
$event->setEventParam('top_prefix', $this->Application->GetTopmostPrefix($event->Prefix, true));
if (($this->Application->RecallVar('user_id') == -1) || $event_handler->CheckPermission($event)) {
$this->HandleEvent($event);
}
if ($event->status == erSTOP) {
// event requested to stop processing at this point
safeDefine('DBG_SKIP_REPORTING', 1);
$this->Application->Session->SaveData();
exit;
}
if ($event->status == erPERM_FAIL) {
// should do redirect but to no_permissions template
$event->redirect = $this->Application->isAdmin ? 'no_permission' : $this->Application->ConfigValue('NoPermissionTemplate');
$event->redirect_params['pass'] = 'm';
$themes_helper =& $this->Application->recallObject('ThemesHelper');
/* @var $themes_helper kThemesHelper */
$event->redirect_params['m_cat_id'] = $themes_helper->getPageByTemplate($event->redirect);
// restore stuff, that processOpener() changed
$wid = $this->Application->GetVar('m_wid');
$this->Application->RestoreVar(rtrim('opener_stack_'.$wid, '_'));
// don't save last_template, because no_permission template does js history.back and could cause invalid opener_stack content
$this->Application->SetVar('skip_last_template', 1);
}
if ( ($event->status == erSUCCESS || $event->status == erPERM_FAIL) && ($event->redirect === true || strlen($event->redirect) > 0)) {
// we need to pass category if the action was submitted to self-template, with the category passed
// and it has not explicly set redirect template or pass_cateogry param
if ($event->redirect === true && !array_key_exists('pass_category', $event->redirect_params) && $this->Application->GetVar('m_cat_id')) {
$event->redirect_params['pass_category'] = 1;
}
$wid = $this->Application->GetVar('m_wid');
if ($wid && $event->redirect_params['opener'] == 'u') {
$event->redirect_params['opener'] = 's'; // because Application->HREF will react differently when 'opener' = 'u'
$event->redirect = defined('CLOSE_POPUP_TPL') ? CLOSE_POPUP_TPL : 'incs/close_popup';
}
$this->Application->Redirect($event->redirect, $event->redirect_params, null, $event->redirect_script);
}
}
$this->Application->SetVar('events', $events);
$this->Application->SetVar('passed', implode(',', $all_passed));
}
function processOpener()
{
$wid = $this->Application->GetVar('m_wid');
$opener_stack = $this->Application->RecallVar(rtrim('opener_stack_'.$wid, '_'));
$opener_stack = $opener_stack ? unserialize($opener_stack) : Array();
$opener_action = $this->Application->GetVar('m_opener');
switch ($opener_action) {
case 'r': // "reset" opener stack
$opener_stack = Array();
break;
case 'd': // "down/push" new template to opener stack, deeplevel++
if ($this->Application->GetVar('front')) {
$front_session =& $this->Application->recallObject('Session.front');
array_push($opener_stack, '../'.$front_session->RecallVar('last_template') );
}
else {
array_push($opener_stack, $this->Application->RecallVar('last_template') );
}
break;
case 'u': // "up/pop" last template from opener stack, deeplevel--
array_pop($opener_stack);
break;
case 'p': // pop-up - generate new wid
$parent_wid = $this->Application->GetVar('m_wid'); // window_id of popup's parent window
$popup_wid = (int)$this->Application->RecallVar('last_wid') + 1;
$this->Application->StoreVar('last_wid', $popup_wid);
$this->Application->SetVar('m_wid', $popup_wid);
if ($this->Application->GetVar('front')) {
$front_session =& $this->Application->recallObject('Session.front');
$last_template = $front_session->RecallVar(rtrim('last_template_popup_'.$parent_wid, '_'));
$last_template = '../'.$last_template;
}
else {
if ($this->Application->GetVar('merge_opener_stack')) {
// get last template from parent (that was closed) window opener stack
$parent_opener_stack_name = rtrim('opener_stack_' . $parent_wid, '_');
$parent_opener_stack = unserialize( $this->Application->RecallVar($parent_opener_stack_name) );
$last_template = array_pop($parent_opener_stack);
if ($parent_opener_stack) {
$this->Application->StoreVar($parent_opener_stack_name, serialize($parent_opener_stack));
}
else {
$this->Application->RemoveVar($parent_opener_stack_name);
}
}
else {
$last_template = $this->Application->RecallVar(rtrim('last_template_popup_'.$parent_wid, '_'));
}
}
$opener_stack = Array ( $last_template );
$this->Application->SetVar('m_opener', 's');
$wid = $popup_wid;
/*// store window relations
$window_relations = $this->Application->RecallVar('window_relations');
$window_relations = $window_relations ? unserialize($window_relations) : Array ();
$window_relations[$popup_wid] = $parent_wid;
$this->Application->StoreVar('window_relations', serialize($window_relations));*/
break;
default: // "s/0," stay on same deep level
break;
}
$this->Application->SetVar('m_opener', 's');
$this->Application->StoreVar(rtrim('opener_stack_'.$wid, '_'), serialize($opener_stack), !$opener_stack); // empty stack is optional
}
/**
* Allows to add new element to opener stack
*
* @param string $template
* @param Array $params
* @param string $pass
*/
function openerStackPush($template, $params, $pass = 'all', $wid = null)
{
if (!isset($wid)) {
$wid = $this->Application->GetVar('m_wid');
}
/*// get parent window wid, when this was popup
$window_relations = $this->Application->RecallVar('window_relations');
$window_relations = $window_relations ? unserialize($window_relations) : Array ();
$wid = array_key_exists($wid, $window_relations) ? $window_relations[$wid] : false;*/
// get opener stack
$stack_name = rtrim('opener_stack_' . $wid, '_');
$opener_stack = $this->Application->RecallVar($stack_name);
$opener_stack = $opener_stack ? unserialize($opener_stack) : Array ();
// change opener stack
$default_params = Array ('m_opener' => 'u', '__URLENCODE__' => 1);
if (!$this->Application->ConfigValue('UsePopups') && $wid) {
// remove wid to show combined header block in editing window
$default_params['m_wid'] = '';
// move last popup's opener stack elemenent to main window's opener stack
if ($opener_stack) {
list ($index_file, $env) = explode('|', $opener_stack[ count($opener_stack) - 1 ], 2);
$main_params = $this->Application->HttpQuery->processQueryString($env, 'pass');
$main_template = $main_params['t'];
unset($main_params['t']);
$main_params = array_merge($main_params, $default_params);
$this->openerStackPush($main_template, $main_params, $main_params['pass'], '');
}
}
$redirect_params = array_merge_recursive2($default_params, $params);
$new_level = $this->Application->BuildEnv($template, $redirect_params, $pass, true);
array_push($opener_stack, 'index.php|' . ltrim($new_level, ENV_VAR_NAME . '=') );
$this->Application->StoreVar($stack_name, serialize($opener_stack));
}
/**
* Allows to change last element in opener stack
*
* @param string $template
* @param Array $params
* @param string $pass
*/
function openerStackChange($params = Array(), $pass_events = true, $wid = null)
{
if (!isset($wid)) {
$wid = $this->Application->GetVar('m_wid');
}
// get opener stack
$stack_name = rtrim('opener_stack_' . $wid, '_');
$opener_stack = $this->Application->RecallVar($stack_name);
$opener_stack = $opener_stack ? unserialize($opener_stack) : Array ();
// change opener stack
list ($index_file, $env) = explode('|', $opener_stack[ count($opener_stack) - 1 ], 2);
$vars = $this->Application->HttpQuery->processQueryString($env, 'pass');
$vars = array_merge_recursive2($vars, $params);
// save opener stack
$new_level = $this->Application->BuildEnv($vars['t'], $vars, $vars['pass'], $pass_events, false);
$opener_stack[ count($opener_stack) - 1 ] = $index_file . '|' . $new_level;
$this->Application->StoreVar($stack_name, serialize($opener_stack));
}
function registerHook($hookto_prefix, $hookto_special, $hookto_event, $mode, $do_prefix, $do_special, $do_event, $conditional)
{
if ( !$this->Application->prefixRegistred($hookto_prefix) && $hookto_prefix != '*' ) {
if ($this->Application->isDebugMode()) {
trigger_error('Prefix <b>'.$hookto_prefix.'</b> doesn\'t exist when trying to hook from <b>'.$do_prefix.':'.$do_event.'</b>', E_USER_WARNING);
}
return;
}
$hookto_prefix_special = rtrim($hookto_prefix.'.'.$hookto_special, '.');
if ($mode == hBEFORE) {
$this->beforeHooks[strtolower($hookto_prefix_special.'.'.$hookto_event)][] = Array(
'DoPrefix' => $do_prefix,
'DoSpecial' => $do_special,
'DoEvent' => $do_event,
'Conditional' => $conditional,
);
}
elseif ($mode == hAFTER) {
$this->afterHooks[strtolower($hookto_prefix_special.'.'.$hookto_event)][] = Array(
'DoPrefix' => $do_prefix,
'DoSpecial' => $do_special,
'DoEvent' => $do_event,
'Conditional' => $conditional,
);
}
}
/**
* Enter description here...
*
* @param kEvent $event
* @param int $mode hBEFORE or hAFTER
* @param string $event_key
* @return Array
*/
function &_getHooks(&$event, $mode, $event_key = null)
{
$event_key = isset($event_key) ? $event_key : $event->Prefix_Special;
if ($mode == hBEFORE) {
$mode_hooks =& $this->beforeHooks;
}
else {
$mode_hooks =& $this->afterHooks;
}
if (!isset($mode_hooks[strtolower($event_key.'.'.$event->Name)])) {
$hooks = array();
return $hooks;
}
return $mode_hooks[strtolower($event_key.'.'.$event->Name)];
}
/**
* Enter description here...
*
* @param kEvent $event
* @param int $mode hBEFORE or hAFTER
*/
function processHooks(&$event, $mode)
{
// * - get hooks that are valid with any special of given prefix
$hooks = array_merge(
// given prefix, any special
$this->_getHooks($event, $mode, $event->Prefix.'.*'),
// given special, given special
$this->_getHooks($event, $mode),
// any prefix, any special
$this->_getHooks($event, $mode, '*.*'),
// any prefix, given special
$this->_getHooks($event, $mode, rtrim('*.' . $event->Special, '.'))
);
if ($hooks) {
foreach ($hooks as $hook) {
if ($hook['DoSpecial'] == '*') {
// use same special as master event
$hook['DoSpecial'] = $event->Special;
}
$prefix_special = rtrim($hook['DoPrefix'].'_'.$hook['DoSpecial'], '_');
if ( $hook['Conditional'] && !$this->Application->GetVar($prefix_special) ) {
continue;
}
if ($this->Application->prefixRegistred($hook['DoPrefix'])) {
// run hook only, when it's config is found
$hook_event = new kEvent( Array('name'=>$hook['DoEvent'],'prefix'=>$hook['DoPrefix'],'special'=>$hook['DoSpecial']) );
$hook_event->MasterEvent =& $event;
$this->HandleEvent($hook_event);
}
}
}
}
/**
* Set's new event for $prefix_special
* passed
*
* @param string $prefix_special
* @param string $event_name
* @access public
*/
function setEvent($prefix_special,$event_name)
{
$actions =& $this->Application->recallObject('kActions');
$actions->Set('events['.$prefix_special.']',$event_name);
}
/**
* Run registred regular events with specified event type
*
* @param int $event_type
*/
function RunRegularEvents($event_type = reBEFORE, $from_cron=false)
{
if (defined('IS_INSTALL')) return ;
// if RegularEvents are set to run from cron
if (!$from_cron && $this->Application->ConfigValue('UseCronForRegularEvent')) return ;
$agents = $this->getRegularEvents();
$events_source = $agents[$event_type];
$user_id = $this->Application->RecallVar('user_id');
$this->Application->StoreVar('user_id', -1, true); // to prevent permission checking inside events, true for optional storage
foreach ($events_source as $short_name => $event_data) {
$next_run = $event_data['NextRunOn'];
$last_run = $event_data['LastRunOn'];
if ($next_run && ($next_run > adodb_mktime())) {
continue;
}
else {
$event = new kEvent($event_data['EventName']);
if (!$this->Application->prefixRegistred($event->Prefix)) {
// don't process agents, left from disabled modules
continue;
}
$start_time = adodb_mktime();
$fields_hash = Array (
'LastRunOn' => $start_time,
'LastRunStatus' => AGENT_LAST_RUN_RUNNING,
'NextRunOn' => $start_time + $event_data['RunInterval'],
);
$this->Conn->doUpdate(
$fields_hash,
$this->Application->getUnitOption('agent', 'TableName'),
'AgentName = ' . $this->Conn->qstr($short_name)
);
$event->redirect = false;
$this->Application->HandleEvent($event);
$now = adodb_mktime();
$next_run = $event_data['RunInterval'] ? $start_time + $event_data['RunInterval'] : $now;
while ($next_run < $now) {
// in case event execution took longer, then RunInterval (don't use <=, because RunInterval can be 0)
$next_run += $event_data['RunInterval'];
}
$fields_hash = Array (
'NextRunOn' => $next_run,
'RunTime' => round(($now - $start_time) / 60),
'LastRunStatus' => $event->status == erSUCCESS ? AGENT_LAST_RUN_SUCCEDED : AGENT_LAST_RUN_FAILED,
);
$this->Conn->doUpdate(
$fields_hash,
$this->Application->getUnitOption('agent', 'TableName'),
'AgentName = ' . $this->Conn->qstr($short_name)
);
}
}
$this->Application->StoreVar('user_id', $user_id, true); // true for optional
}
/**
* Allows to determine, that required event is beeing processed right now
*
* @param string $event_key Event name in format prefix[.special]:event_name
* @return bool
*/
function eventRunning($event_key)
{
return array_search($event_key, $this->recursionStack) !== false;
}
}
\ No newline at end of file
Index: branches/5.0.x/core/kernel/utility/unit_config_reader.php
===================================================================
--- branches/5.0.x/core/kernel/utility/unit_config_reader.php (revision 13273)
+++ branches/5.0.x/core/kernel/utility/unit_config_reader.php (revision 13274)
@@ -1,992 +1,993 @@
<?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 {
/**
* Configs readed
*
* @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 = '';
/**
* Folders to skip during unit config search
*
* @var Array
*/
var $_skipFolders = Array ('CVS', '.svn', 'admin_templates', 'libchart');
/**
* Scan kernel and user classes
* for available configs
*
* @access protected
*/
function Init($prefix,$special)
{
parent::Init($prefix,$special);
$this->_directorySeparator = preg_quote( DIRECTORY_SEPARATOR );
$this->_skipFolders[] = trim(WRITEBALE_BASE, '/'); // system folder (where web server can write)
$editor_path = explode('/', trim(EDITOR_PATH, '/'));
$this->_skipFolders[] = array_pop($editor_path); // last of cmseditor folders
}
function CacheParsedData()
{
$event_manager =& $this->Application->recallObject('EventManager');
$aggregator =& $this->Application->recallObject('TagsAggregator', 'kArray');
$config_vars = Array (
'SessionTimeout',
'SessionCookieName',
'SessionBrowserSignatureCheck',
'SessionIPAddressCheck',
'CookieSessions',
'UseCronForRegularEvent',
'User_GuestGroup',
'User_LoggedInGroup',
'SessionTimeout',
'UseModRewrite',
'UseOutputCompression',
'OutputCompressionLevel',
'KeepSessionOnBrowserClose',
'Config_Server_Time',
'Config_Site_Time',
'UseChangeLog',
'UseVisitorTracking',
);
foreach ($config_vars as $var) {
$this->Application->ConfigValue($var);
}
$cache = Array(
'Factory.Files' => $this->Application->Factory->Files,
'Factory.realClasses' => $this->Application->Factory->realClasses,
'Factory.Dependencies' => $this->Application->Factory->Dependencies,
'ConfigReader.prefixFiles' => $this->prefixFiles,
'EventManager.buildEvents' => $event_manager->buildEvents,
'EventManager.beforeRegularEvents' => $event_manager->beforeRegularEvents,
'EventManager.afterRegularEvents' => $event_manager->afterRegularEvents,
'EventManager.beforeHooks' => $event_manager->beforeHooks,
'EventManager.afterHooks' => $event_manager->afterHooks,
'TagsAggregator.data' => $aggregator->_Array,
// the following caches should be reset based on admin interaction (adjusting config, enabling modules etc)
'Application.Caches.ConfigVariables' => $this->Application->Caches['ConfigVariables'],
'Application.ConfigCacheIds' => $this->Application->ConfigCacheIds,
'Application.ConfigHash' => $this->Application->ConfigHash,
'Application.ReplacementTemplates' => $this->Application->ReplacementTemplates,
'Application.RewriteListeners' => $this->Application->RewriteListeners,
'Application.ModuleInfo' => $this->Application->ModuleInfo,
);
$conn =& $this->Application->GetADODBConnection();
if (isset($this->Application->Memcached)) {
$this->Application->Memcached->set('master:configs_parsed', serialize($cache));
$this->Application->Memcached->set('master:config_files', serialize($this->configFiles));
}
else {
$conn->Query('REPLACE '.TABLE_PREFIX.'Cache (VarName, Data, Cached) VALUES ("configs_parsed", '.$conn->qstr(serialize($cache)).', '.adodb_mktime().')');
$conn->Query('REPLACE '.TABLE_PREFIX.'Cache (VarName, Data, Cached) VALUES ("config_files", '.$conn->qstr(serialize($this->configFiles)).', '.adodb_mktime().')');
}
$cache_rebuild_by = SERVER_NAME . ' (' . getenv('REMOTE_ADDR') . ') - ' . adodb_date('d/m/Y H:i:s');
$conn->Query('REPLACE ' . TABLE_PREFIX . 'Cache (VarName, Data, Cached) VALUES ("last_cache_rebuild", ' . $conn->qstr($cache_rebuild_by) . ', ' . adodb_mktime() . ')');
unset($this->configFiles);
}
function RestoreParsedData()
{
$conn =& $this->Application->GetADODBConnection();
if (!isset($this->Application->Memcached) || !($data = $this->Application->Memcached->get('master:configs_parsed'))) {
$data = $conn->GetOne('SELECT Data FROM '.TABLE_PREFIX.'Cache WHERE VarName = "configs_parsed"');
}
if ($data) {
$cache = unserialize($data);
$this->Application->Factory->Files = $cache['Factory.Files'];
$this->Application->Factory->realClasses = $cache['Factory.realClasses'];
$this->Application->Factory->Dependencies = $cache['Factory.Dependencies'];
$this->prefixFiles = $cache['ConfigReader.prefixFiles'];
$event_manager =& $this->Application->recallObject('EventManager');
$event_manager->buildEvents = $cache['EventManager.buildEvents'];
$event_manager->beforeRegularEvents = $cache['EventManager.beforeRegularEvents'];
$event_manager->afterRegularEvents = $cache['EventManager.afterRegularEvents'];
$event_manager->beforeHooks = $cache['EventManager.beforeHooks'];
$event_manager->afterHooks = $cache['EventManager.afterHooks'];
$aggregator =& $this->Application->recallObject('TagsAggregator', 'kArray');
$aggregator->_Array = $cache['TagsAggregator.data'];
$this->Application->ConfigHash = $cache['Application.ConfigHash'];
$this->Application->Caches['ConfigVariables'] = $cache['Application.ConfigCacheIds'];
$this->Application->ConfigCacheIds = $cache['Application.ConfigCacheIds'];
$this->Application->ReplacementTemplates = $cache['Application.ReplacementTemplates'];
$this->Application->RewriteListeners = $cache['Application.RewriteListeners'];
$this->Application->ModuleInfo = $cache['Application.ModuleInfo'];
return true;
}
else return false;
}
function ResetParsedData($include_sections = false)
{
$conn =& $this->Application->GetADODBConnection();
$conn->Query('DELETE FROM '.TABLE_PREFIX.'Cache WHERE VarName = "configs_parsed"');
if (isset($this->Application->Memcached)) {
$this->Application->Memcached->delete('master:configs_parsed');
}
if ($include_sections) {
$conn->Query('DELETE FROM '.TABLE_PREFIX.'Cache WHERE VarName = "sections_parsed"');
if (isset($this->Application->Memcached)) {
$this->Application->Memcached->delete('master:sections_parsed');
}
}
}
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->RestoreParsedData();
if ($restored) return;
}
$this->ProcessAllConfigs = true;
$this->includeConfigFiles($folderPath, $cache);
$this->ParseConfigs();
// tell AfterConfigRead to store cache if neede
// can't store it here beacuse AfterConfigRead needs ability to change config data
$this->StoreCache = $cache;
}
function findConfigFiles($folderPath, $level = 0)
{
/*if ($level == 0) {
if ($this->Application->isDebugMode()) {
$start_time = getmicrotime();
$this->Application->Debugger->appendHTML('kUnitConfigReader::findConfigFiles("' . $folderPath . '")');
$this->Application->Debugger->appendTrace();
}
}*/
// 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);
}
/*if ($level == 0) {
if ($this->Application->isDebugMode()) {
$this->Application->Debugger->appendHTML('kUnitConfigReader::findConfigFiles("' . FULL_PATH . $folderPath . '"): ' . (getmicrotime() - $start_time));
}
}*/
}
function includeConfigFiles($folderPath, $cache = true)
{
$this->Application->refreshModuleInfo();
$conn =& $this->Application->GetADODBConnection();
if (!isset($this->Application->Memcached) || !($data = $this->Application->Memcached->get('master:config_files'))) {
$data = $conn->GetOne('SELECT Data FROM ' . TABLE_PREFIX . 'Cache WHERE VarName = "config_files"');
}
if ($cache && $data) {
$this->configFiles = unserialize($data);
shuffle($this->configFiles);
}
else {
$this->findConfigFiles($folderPath); // search from base directory
}
foreach ($this->configFiles as $filename)
{
$prefix = $this->PreloadConfigFile($filename);
if (!$prefix) {
trigger_error('Prefix not defined in config file ' . $filename, E_USER_ERROR);
}
}
}
/**
* Process all read config files - called ONLY when there is no cache!
*
*/
function ParseConfigs()
{
// 1. process normal configs and their dependencies
$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->ProcessDependencies($prefix);
$this->postProcessConfig($prefix, 'AggregateConfigs', 'sub_prefix');
$clones = $this->postProcessConfig($prefix, 'Clones', 'prefix');
}
// 2. process prioritized configs and their dependencies
asort($prioritized_configs);
foreach ($prioritized_configs as $prefix => $priority) {
$this->parseConfig($prefix);
}
foreach ($prioritized_configs as $prefix => $priority) {
$this->ProcessDependencies($prefix);
}
}
function AfterConfigRead($store_cache = null)
{
// if (!$this->ProcessAllConfigs) return ;
$this->FinalStage = true;
foreach ($this->configData as $prefix => $config) {
- if (in_array($prefix, $this->AfterConfigProcessed)) {
- continue;
- }
-
- $this->Application->HandleEvent( new kEvent($prefix.':OnAfterConfigRead') );
- $this->AfterConfigProcessed[] = $prefix;
+ $this->runAfterConfigRead($prefix);
}
if (!isset($store_cache)) {
// store cache not overrided -> 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->CacheParsedData();
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);
}
}
$after_event = new kEvent('adm:OnAfterCacheRebuild');
$this->Application->HandleEvent($after_event);
}
}
/**
* 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()
{
// clear restored cache (not in db)
$this->Application->Factory->Files = Array ();
$this->Application->Factory->realClasses = Array ();
$this->Application->Factory->Dependencies = Array ();
$this->Application->EventManager->beforeRegularEvents = Array ();
$this->Application->EventManager->afterRegularEvents = Array ();
$this->Application->EventManager->beforeHooks = Array ();
$this->Application->EventManager->afterHooks = Array ();
// otherwise ModulesHelper indirectly used from includeConfigFiles won't work
$this->Application->RegisterDefaultClasses();
// parse all configs
$this->ProcessAllConfigs = true;
+ $this->AfterConfigProcessed = Array ();
$this->includeConfigFiles(MODULES_PATH, false);
$this->ParseConfigs();
$this->AfterConfigRead(false);
$this->processDynamicClones();
$this->retrieveCollections();
}
/**
* 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);
}
}
// call OnAfterConfigRead for cloned configs
$new_clones = array_unique($new_clones);
foreach ($new_clones as $prefix) {
- if (in_array($prefix, $this->AfterConfigProcessed)) {
- continue;
- }
-
- $this->Application->HandleEvent( new kEvent($prefix.':OnAfterConfigRead') );
- $this->AfterConfigProcessed[] = $prefix;
+ $this->runAfterConfigRead($prefix);
}
}
/**
* Process all collectable 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_listener = $config['RewriteListener'];
if (strpos($rewrite_listener, ':') === false) {
$rewrite_listener = $prefix . '_EventHandler:' . $rewrite_listener;
}
$rewrite_priority = array_key_exists('RewritePriority', $config) ? $config['RewritePriority'] : false;
$this->Application->RewriteListeners[$prefix] = Array ('listener' => $rewrite_listener, 'priority' => $rewrite_priority);
}
}
}
/**
* Register nessasary classes
* This method should only process the data which is cached!
*
* @param string $prefix
* @access private
*/
function parseConfig($prefix)
{
$config =& $this->configData[$prefix];
$event_manager =& $this->Application->recallObject('EventManager');
/* @var $event_manager kEventManager */
$register_classes = getArrayValue($config,'RegisterClasses');
if (!$register_classes) $register_classes = Array();
$class_params=Array('ItemClass','ListClass','EventHandlerClass','TagProcessorClass');
foreach($class_params as $param_name)
{
if ( !(isset($config[$param_name]) ) ) continue;
$config[$param_name]['pseudo'] = $this->getPrefixByParamName($param_name,$prefix);
$register_classes[] = $config[$param_name];
}
foreach($register_classes as $class_info)
{
$require_classes = getArrayValue($class_info, 'require_classes');
if ($require_classes) {
if (!is_array($require_classes)) {
$require_classes = array($require_classes);
}
if (!isset($config['_Dependencies'][$class_info['class']])) {
$config['_Dependencies'][$class_info['class']] = array();
}
$config['_Dependencies'][$class_info['class']] = array_merge($config['_Dependencies'][$class_info['class']], $require_classes);
}
$this->Application->registerClass(
$class_info['class'],
$config['BasePath'] . DIRECTORY_SEPARATOR . $class_info['file'],
$class_info['pseudo']/*,
getArrayValue($class_info, 'require_classes')*/
);
if (getArrayValue($class_info, 'build_event')) {
$event_manager->registerBuildEvent($class_info['pseudo'],$class_info['build_event']);
}
}
$regular_events = getArrayValue($config, 'RegularEvents');
if ($regular_events) {
foreach ($regular_events as $short_name => $regular_event_info) {
$event_status = array_key_exists('Status', $regular_event_info) ? $regular_event_info['Status'] : STATUS_ACTIVE;
$event_manager->registerRegularEvent( $short_name, $config['Prefix'].':'.$regular_event_info['EventName'], $regular_event_info['RunInterval'], $regular_event_info['Type'], $event_status);
}
}
$hooks = getArrayValue($config, 'Hooks');
if (is_array($hooks) && count($hooks) > 0) {
foreach ($hooks as $hook) {
if (isset($config['ParentPrefix']) && $hook['HookToPrefix'] == $config['ParentPrefix']) {
trigger_error('Depricated Hook Usage [prefix: <b>'.$config['Prefix'].'</b>; do_prefix: <b>'.$hook['DoPrefix'].'</b>] use <b>#PARENT#</b> as <b>HookToPrefix</b> value, where HookToPrefix is same as ParentPrefix', E_USER_NOTICE);
}
if ($hook['HookToPrefix'] == '') {
$hook['HookToPrefix'] = $config['Prefix']; // new: set hooktoprefix to current prefix if not set
}
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#') {
continue; // we need parent prefix but it's not set !
}
$do_prefix = $hook['DoPrefix'] == '' ? $config['Prefix'] : $hook['DoPrefix'];
if ( !is_array($hook['HookToEvent']) ) {
$hook_events = Array( $hook['HookToEvent'] );
}
else {
$hook_events = $hook['HookToEvent'];
}
foreach ($hook_events as $hook_event) {
$this->Application->registerHook($hook['HookToPrefix'], $hook['HookToSpecial'], $hook_event, $hook['Mode'], $do_prefix, $hook['DoSpecial'], $hook['DoEvent'], $hook['Conditional']);
}
}
}
if ( is_array(getArrayValue($config, 'AggregateTags')) ) {
foreach ($config['AggregateTags'] 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', E_USER_NOTICE);
}
if ($aggregate_tag['AggregateTo'] == '#PARENT#') {
$aggregate_tag['AggregateTo'] = $config['ParentPrefix'];
}
}
$aggregate_tag['LocalPrefix'] = $config['Prefix'];
$this->Application->registerAggregateTag($aggregate_tag);
}
}
}
function ValidateConfig($prefix)
{
global $debugger;
$config =& $this->configData[$prefix];
$tablename = $config['TableName'];
$float_types = Array ('float', 'double', 'numeric');
$conn =& $this->Application->GetADODBConnection();
$table_found = $conn->Query('SHOW TABLES LIKE "'.$tablename.'"');
if (!$table_found) {
// config present, but table missing, strange
$debugger->appendHTML("<b class='debug_error'>Config Warning: </b>Table <strong>$tablename</strong> missing, but prefix <b>".$config['Prefix']."</b> requires it!");
safeDefine('DBG_RAISE_ON_WARNINGS', 1);
return ;
}
$res = $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)',
'type_missing' => '<strong>Type definition</strong> for field <strong>%s</strong> missing in config',
);
$config_errors = Array ();
$tablename = preg_replace('/^'.preg_quote(TABLE_PREFIX, '/').'(.*)/', '\\1', $tablename); // remove table prefix
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 {
if (is_numeric($field['Default'])) {
$field['Default'] = preg_match('/[\.,]/', $field['Default']) ? (float)$field['Default'] : (int)$field['Default'];
}
$options = $config['Fields'][$f_name];
$default_missing = 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 (isset($options['not_null']) && $options['not_null'] && !isset($options['default']) ) {
$config_errors[] = sprintf($error_messages['not_null_error2'], $f_name);
}
}
else {
if (isset($options['not_null']) && $options['not_null']) {
$config_errors[] = sprintf($error_messages['not_null_error3'], $f_name);
}
}
if (!array_key_exists('type', $options)) {
$config_errors[] = sprintf($error_messages['type_missing'], $f_name);
}
if (!$default_missing) {
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 ($options['default'] != '#NOW#' && $field['Default'] !== $options['default'] && !in_array($options['type'], $float_types)) {
$config_errors[] = sprintf($error_messages['invalid_default'], '', $f_name, $this->varDump($options['default']), $this->varDump($field['Default']));
}
}
}
}
}
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);
$debugger->appendHTML($config_errors);
safeDefine('DBG_RAISE_ON_WARNINGS', 1);
}
}
function varDump($value)
{
return '<strong>'.var_export($value, true).'</strong> of '.gettype($value);
}
function ProcessDependencies($prefix)
{
$config =& $this->configData[$prefix];
$deps = getArrayValue($config, '_Dependencies');
if (!$deps) return ;
foreach ($deps as $real_class => $requires) {
foreach ($requires as $class) {
$this->Application->registerDependency($real_class, $class);
}
}
unset($config['_Dependencies']);
}
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] : false; // getArrayValue($main_config, $config_key);
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] = array_merge_recursive2($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_required_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->_directorySeparator . '(.*)' . $this->_directorySeparator . '#U', $filename, $rets);
$config['ModuleFolder'] = $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' ? '' : $rets[1] . '/';
$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;
}
elseif ($prefix = array_search($filename, $this->prefixFiles)) {
// 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])) {
if ($this->Application->isDebugMode()) $this->Application->Debugger->appendTrace();
trigger_error('Configuration file for prefix <b>'.$prefix.'</b> is unknown', E_USER_ERROR);
return ;
}
$file = $this->prefixFiles[$prefix];
$prefix = $this->PreloadConfigFile($file);
$clones = $this->postProcessConfig($prefix, 'AggregateConfigs', 'sub_prefix');
$clones = array_merge($this->postProcessConfig($prefix, 'Clones', 'prefix'), $clones);
if ($this->FinalStage) {
array_unshift($clones, $prefix);
$clones = array_unique($clones);
foreach ($clones as $a_prefix) {
- $this->Application->HandleEvent( new kEvent($a_prefix.':OnAfterConfigRead') );
+ $this->runAfterConfigRead($a_prefix);
}
}
}
+ function runAfterConfigRead($prefix)
+ {
+ if (in_array($prefix, $this->AfterConfigProcessed)) {
+ return ;
+ }
+
+ $this->Application->HandleEvent( new kEvent($prefix . ':OnAfterConfigRead') );
+ 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;
}
}
function getPrefixByParamName($paramName,$prefix)
{
$pseudo_class_map=Array(
'ItemClass'=>'%s',
'ListClass'=>'%s_List',
'EventHandlerClass'=>'%s_EventHandler',
'TagProcessorClass'=>'%s_TagProcessor'
);
return sprintf($pseudo_class_map[$paramName],$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)
{
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 . 'plugins' . $this->_directorySeparator . '|' . $this->_directorySeparator . 'core#', $config_path)) {
// always allow to include configs from core and plugins folder
return true;
}
$module_found = false;
if (!$this->Application->ModuleInfo) {
return false;
}
foreach ($this->Application->ModuleInfo as $module_name => $module_info) {
$module_path = DIRECTORY_SEPARATOR . trim($module_info['Path'], '/') . DIRECTORY_SEPARATOR;
// config file path starts with module folder path
if (substr($config_path, 0, strlen($module_path)) == $module_path) {
// if (preg_match('#^' . preg_quote($module_path, '/') . '#', $config_path)) {
$module_found = true;
break;
}
}
return $module_found;
}
/**
* 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.0.x/core/units/helpers/multilanguage_helper.php
===================================================================
--- branches/5.0.x/core/units/helpers/multilanguage_helper.php (revision 13273)
+++ branches/5.0.x/core/units/helpers/multilanguage_helper.php (revision 13274)
@@ -1,304 +1,304 @@
<?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!');
/**
* Performs action on multilingual fields
*
*/
class kMultiLanguageHelper extends kHelper {
/**
* Maximal language id
*
* @var int
*/
var $languageCount = 0;
/**
* Languages created in system
*
* @var Array
*/
var $languagesIDs = Array ();
/**
* Structure of table, that is currently processed
*
* @var Array
*/
var $curStructure = Array();
/**
* Field, to get structure information from
*
* @var string
*/
var $curSourceField = false;
/**
* Indexes used in table of 32
*
* @var int
*/
var $curIndexCount = 0;
/**
* Fields from config, that are currently used
*
* @var Array
*/
var $curFields = Array();
function kMultiLanguageHelper()
{
parent::kHelper();
$this->languageCount = $this->getLanguageCount();
}
/**
* Checks if language with specified id is created
*
* @param int $language_id
* @return bool
*/
function LanguageFound($language_id)
{
return in_array($language_id, $this->languagesIDs) || $language_id <= 5;
}
/**
* Returns language count in system (always is divisible by 5)
*
*/
function getLanguageCount()
{
$id_field = $this->Application->getUnitOption('lang', 'IDField');
$table_name = $this->Application->getUnitOption('lang', 'TableName');
$this->languagesIDs = $this->Conn->GetCol('SELECT '.$id_field.' FROM '.$table_name);
$languages_count = $this->Conn->GetOne('SELECT MAX('.$id_field.') FROM '.$table_name);
return max($languages_count, 5);
}
function scanTable($mask)
{
$i = 0;
$fields_found = 0;
$fields = array_keys($this->curStructure);
foreach ($fields as $field_name) {
if (preg_match($mask, $field_name)) {
$fields_found++;
}
}
return $fields_found;
}
function readTableStructure($table_name, $refresh = false)
{
// if ($refresh || !getArrayValue($structure_status, $prefix.'.'.$table_name)) {
$this->curStructure = $this->Conn->Query('DESCRIBE '.$table_name, 'Field');
$this->curIndexCount = count($this->Conn->Query('SHOW INDEXES FROM '.$table_name));
// }
}
/**
* Creates missing multilanguage fields in table by specified prefix
*
* @param string $prefix
* @param bool $refresh Forces config field structure to be re-read from database
*/
function createFields($prefix, $refresh = false)
{
if ($refresh && preg_match('/(.*)-cdata$/', $prefix, $regs)) {
// call main item config to clone cdata table
$this->Application->UnitConfigReader->loadConfig($regs[1]);
- $this->Application->HandleEvent( new kEvent($prefix.':OnAfterConfigRead') );
+ $this->Application->UnitConfigReader->runAfterConfigRead($prefix);
}
$table_name = $this->Application->getUnitOption($prefix, 'TableName');
$this->curFields = $this->Application->getUnitOption($prefix, 'Fields');
if (!($table_name && $this->curFields) || ($table_name && !$this->Conn->TableFound($table_name))) {
// invalid config found or prefix not found
return true;
}
$sqls = Array();
$this->readTableStructure($table_name, $refresh);
foreach($this->curFields as $field_name => $field_options)
{
if (getArrayValue($field_options, 'formatter') == 'kMultiLanguage') {
if (isset($field_options['master_field'])) {
unset($this->curFields[$field_name]);
continue;
}
$this->setSourceField($field_name);
if ($this->languageCount > 0) {
// `l77_Name` VARCHAR( 255 ) NULL DEFAULT '0';
$field_mask = Array();
$field_mask['name'] = 'l%s_'.$field_name;
$field_mask['null'] = getArrayValue($field_options, 'not_null') ? 'NOT NULL' : 'NULL';
if ($this->curSourceField) {
$default_value = $this->getFieldParam('Default') != 'NULL' ? $this->Conn->qstr($this->getFieldParam('Default')) : $this->getFieldParam('Default');
$field_mask['type'] = $this->getFieldParam('Type');
}
else {
$default_value = is_null($field_options['default']) ? 'NULL' : $this->Conn->qstr($field_options['default']);
$field_mask['type'] = $field_options['db_type'];
}
$field_mask['default'] = 'DEFAULT '.$default_value;
if (strtoupper($field_mask['type']) == 'TEXT') {
// text fields in mysql doesn't have default value
$field_mask = $field_mask['name'].' '.$field_mask['type'].' '.$field_mask['null'];
}
else {
$field_mask = $field_mask['name'].' '.$field_mask['type'].' '.$field_mask['null'].' '.$field_mask['default'];
}
$alter_sqls = $this->generateAlterSQL($field_mask, 1, $this->languageCount);
if ($alter_sqls) {
$sqls[] = 'ALTER TABLE '.$table_name.' '.$alter_sqls;
}
}
}
}
foreach ($sqls as $sql_query) {
$this->Conn->Query($sql_query);
}
}
function deleteField($prefix, $custom_id)
{
$table_name = $this->Application->getUnitOption($prefix, 'TableName');
$sql = 'DESCRIBE '.$table_name.' "l%_cust_'.$custom_id.'"';
$fields = $this->Conn->GetCol($sql);
$sql = 'ALTER TABLE '.$table_name.' ';
$sql_template = 'DROP COLUMN %s, ';
foreach ($fields as $field_name) {
$sql .= sprintf($sql_template, $field_name);
}
$this->Conn->Query( substr($sql, 0, -2) );
}
/**
* Returns parameter requested of current source field
*
* @param string $param_name
* @return string
*/
function getFieldParam($param_name)
{
return $this->curStructure[$this->curSourceField][$param_name];
}
/**
* Detects field name to create other fields from
*
* @param string $field_name
*/
function setSourceField($field_name)
{
$ret = $this->scanTable('/^l[\d]+_'.preg_quote($field_name, '/').'$/');
if (!$ret) {
// no multilingual fields at all (but we have such field without language prefix)
$original_found = $this->scanTable('/'.preg_quote($field_name, '/').'/');
$this->curSourceField = $original_found ? $field_name : false;
}
else {
$this->curSourceField = 'l1_'.$field_name;
}
}
/**
* Returns ALTER statement part for adding required fields to table
*
* @param string $field_mask sql mask for creating field with correct definition (type & size)
* @param int $start_index add new fields starting from this index
* @param int $create_count create this much new multilingual field translations
* @return string
*/
function generateAlterSQL($field_mask, $start_index, $create_count)
{
static $single_lang = null;
if (!isset($single_lang)) {
// if single language mode, then create indexes only on primary columns
$table_name = $this->Application->getUnitOption('lang', 'TableName');
$sql = 'SELECT COUNT(*)
FROM '.$table_name.'
WHERE Enabled = 1';
// if language count = 0, then assume it's multi language mode
$single_lang = $this->Conn->GetOne($sql) == 1;
}
$ret = '';
$ml_field = preg_replace('/l(.*?)_(.*?) (.*)/', '\\2', $field_mask);
$i_count = $start_index + $create_count;
while ($start_index < $i_count) {
if (isset($this->curStructure['l'.$start_index.'_'.$ml_field]) || (!$this->LanguageFound($start_index)) ) {
$start_index++;
continue;
}
$prev_index = $start_index - 1;
do {
list($prev_field,$type) = explode(' ', sprintf($field_mask, $prev_index) );
} while ($prev_index > 0 && !$this->LanguageFound($prev_index--));
if (substr($prev_field, 0, 3) == 'l0_') {
$prev_field = substr($prev_field, 3, strlen($prev_field));
if (!$this->curSourceField) {
// get field name before this one
$fields = array_keys($this->curFields);
// $prev_field = key(end($this->curStructure));
$prev_field = $fields[array_search($prev_field, $fields) - 1];
if (getArrayValue($this->curFields[$prev_field], 'formatter') == 'kMultiLanguage') {
$prev_field = 'l'.$this->languageCount.'_'.$prev_field;
}
}
}
$field_expression = sprintf($field_mask, $start_index);
$ret .= 'ADD COLUMN '.$field_expression.' AFTER `'.$prev_field.'`, ';
if ($this->curIndexCount < 32 && ($start_index == $this->Application->GetDefaultLanguageId() || !$single_lang)) {
// create index for primary language column + for all others (if multiple languages installed)
list($field_name, $field_params) = explode(' ', $field_expression, 2);
$index_type = isset($this->curFields[$ml_field]['index_type']) ? $this->curFields[$prev_field]['index_type'] : 'string';
$ret .= $index_type == 'string' ? 'ADD INDEX (`'.$field_name.'` (5) ), ' : 'ADD INDEX (`'.$field_name.'`), ';
$this->curIndexCount++;
}
$start_index++;
}
return preg_replace('/, $/', ';', $ret);
}
}

Event Timeline