Page MenuHomeIn-Portal Phabricator

in-portal
No OneTemporary

File Metadata

Created
Mon, Feb 3, 6:39 AM

in-portal

Index: branches/5.0.x/core/kernel/utility/http_query.php
===================================================================
--- branches/5.0.x/core/kernel/utility/http_query.php (revision 12952)
+++ branches/5.0.x/core/kernel/utility/http_query.php (revision 12953)
@@ -1,681 +1,686 @@
<?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 kHTTPQuery extends Params {
/**
* $_POST vars
*
* @var Array
* @access private
*/
var $Post;
/**
* $_GET vars
*
* @var Array
* @access private
*/
var $Get;
/**
* $_COOKIE vars
*
* @var Array
* @access private
*/
var $Cookie;
/**
* $_SERVER vars
*
* @var Array
* @access private
*/
var $Server;
/**
* $_ENV vars
*
* @var Array
* @access private
*/
var $Env;
/**
* Order in what write
* all vars together in
* the same array
*
* @var string
*/
var $Order;
/**
* Uploaded files info
*
* @var Array
* @access private
*/
var $Files;
var $specialsToRemove = Array();
/**
* Description
*
* @var kDBConnection
* @access public
*/
var $Conn;
/**
* SessionID is given via "sid" variable in query string
*
* @var bool
*/
var $_sidInQueryString = false;
/**
* Loads info from $_POST, $_GET and
* related arrays into common place
*
* @param string $order
* @return HTTPQuery
* @access public
*/
function kHTTPQuery($order = 'CGPF')
{
parent::Params();
$this->Conn =& $this->Application->GetADODBConnection();
$this->Order = $order;
if (array_key_exists('HTTP_X_REQUESTED_WITH', $_SERVER) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
// when AJAX request is made from jQuery, then create ajax variable,
// so any logic based in it (like redirects) will not break down
$_GET['ajax'] = 'yes';
}
}
function Init($prefix, $special)
{
$this->AddAllVars();
$this->specialsToRemove = $this->Get('remove_specials');
if ($this->specialsToRemove) {
foreach ($this->specialsToRemove as $prefix_special => $flag) {
if ($flag && strpos($prefix_special, '.') === false) {
unset($this->specialsToRemove[$prefix_special]);
trigger_error('Incorrect usage of "<strong>remove_specials['.$prefix_special.']</strong>" field (no special found)', E_USER_WARNING);
}
}
$this->_Params = $this->removeSpecials($this->_Params);
}
ini_set('magic_quotes_gpc', 0);
}
function removeSpecials($array)
{
$ret = Array();
$removed = false;
foreach ($this->specialsToRemove as $prefix_special => $flag) {
if ($flag) {
$removed = true;
list ($prefix,$special) = explode('.', $prefix_special, 2);
foreach ($array as $key => $val) {
$new_key = preg_match("/^".$prefix."[._]{1}".$special."(.*)/", $key, $regs) ? $prefix.$regs[1] : $key;
$ret[$new_key] = is_array($val) ? $this->removeSpecials($val) : $val;
}
}
}
return $removed ? $ret : $array;
}
/**
* All all requested vars to
* common storage place
*
* @access private
*/
function AddAllVars()
{
for ($i=0; $i < strlen($this->Order); $i++)
{
$current = $this->Order[$i];
switch ($current) {
case 'G':
$this->Get = $this->AddVars($_GET);
if (array_key_exists('sid', $_GET)) {
$this->_sidInQueryString = true;
}
$vars = $this->processQueryString( $this->Get(ENV_VAR_NAME) );
if (array_key_exists('sid', $vars)) {
// used by Session::GetPassedSIDValue
$this->Get['sid'] = $vars['sid'];
}
$this->AddParams($vars);
break;
case 'P':
$this->Post = $this->AddVars($_POST);
$this->convertPostEvents();
$this->_processPostEnvVariables();
break;
case 'C':
$this->Cookie = $this->AddVars($_COOKIE);
break;
case 'E';
$this->Env = $this->AddVars($_ENV);
break;
case 'S';
$this->Server = $this->AddVars($_SERVER);
break;
case 'F';
$this->convertFiles();
$this->Files = $this->MergeVars($_FILES, false); //do not strip slashes!
break;
}
}
// $this->AfterInit();
}
/**
* Allow POST variables, that names were transformed by PHP ("." replaced with "_") to
* override variables, that were virtually created through enviroment variable parsing
*
*/
function _processPostEnvVariables()
{
$passed = $this->Get('passed');
if (!$passed) {
return ;
}
$passed = explode(',', $passed);
foreach ($passed as $prefix_special) {
if (strpos($prefix_special, '.') === false) {
continue;
}
list ($prefix, $special) = explode('.', $prefix_special);
$query_map = $this->Application->EventManager->getQueryMap($prefix);
$post_prefix_special = $prefix . '_' . $special;
foreach ($query_map as $index => $var_name) {
if (array_key_exists($post_prefix_special . '_' . $var_name, $this->Post)) {
$this->Set($prefix_special . '_' . $var_name, $this->Post[$post_prefix_special . '_' . $var_name]);
}
}
}
}
function AfterInit()
{
// $vars = $this->processQueryString($this->Get(ENV_VAR_NAME));
// $this->AddParams($vars);
// $this->convertPostEvents();
// if ($this->Application->RewriteURLs()) {
if ($this->Application->RewriteURLs() || $this->Get('_mod_rw_url_')) {
if (defined('DEBUG_MODE') && $this->Application->isDebugMode()) {
$this->Application->Debugger->profileStart('url_parsing');
$this->processRewriteURL();
$description = 'Parsing <b>MOD_REWRITE</b> url (template: <b>'.$this->Get('t').'</b>)';
$this->Application->Debugger->profileFinish('url_parsing', $description);
}
else {
$this->processRewriteURL();
}
}
else {
$this->Application->VerifyLanguageId();
$this->Application->VerifyThemeId();
}
}
function convertFiles()
{
if (!$_FILES)
{
return false;
}
$file_keys = Array('error','name','size','tmp_name','type');
$tmp = Array();
foreach($_FILES as $file_name => $file_info)
{
if( is_array($file_info['error']) )
{
$tmp[$file_name] = $this->getArrayLevel( $file_info['error'], $file_name );
}
else
{
$normal_files[$file_name] = $file_info;
}
}
if(!$tmp) return false;
$files = $_FILES;
$_FILES = Array();
foreach($tmp as $prefix => $prefix_files)
{
$anchor =& $_FILES;
foreach($prefix_files['keys'] as $key)
{
$anchor =& $anchor[$key];
}
foreach($prefix_files['value'] as $field_name)
{
unset($inner_anchor);
unset($copy);
$work_copy = $prefix_files['keys'];
foreach($file_keys as $file_key)
{
$inner_anchor =& $files[$prefix][$file_key];
if (isset($copy))
{
$work_copy = $copy;
}
else
{
$copy = $work_copy;
}
array_shift($work_copy);
foreach($work_copy as $prefix_file_key)
{
$inner_anchor =& $inner_anchor[$prefix_file_key];
}
$anchor[$field_name][$file_key] = $inner_anchor[$field_name];
}
}
}
// keys: img_temp, 0, values: LocalPath, ThumbPath
}
function getArrayLevel(&$level, $prefix='')
{
$ret['keys'] = $prefix ? Array($prefix) : Array();
$ret['value'] = Array();
foreach($level as $level_key => $level_value)
{
if( is_array($level_value) )
{
$ret['keys'][] = $level_key;
$tmp = $this->getArrayLevel($level_value);
$ret['keys'] = array_merge($ret['keys'], $tmp['keys']);
$ret['value'] = array_merge($ret['value'], $tmp['value']);
}
else
{
$ret['value'][] = $level_key;
}
}
return $ret;
}
/**
* Owerwrites GET events with POST events in case if they are set and not empty
*
*/
function convertPostEvents()
{
$events = $this->Get('events');
if (is_array($events)) {
foreach ($events as $prefix_special => $event_name) {
if ($event_name) {
$this->Set($prefix_special.'_event', $event_name);
}
}
}
}
function finalizeParsing($passed = Array(), $module_params = Array() )
{
if ($passed) {
$event_manger =& $this->Application->recallObject('EventManager');
foreach ($passed as $passed_prefix) {
$event_manger->setQueryMap($passed_prefix);
}
$this->Set('passed', implode(',', array_keys($event_manger->queryMaps)));
}
// get joined version (env var + mod rewrite parsed)
$passed = $this->Application->GetVar('passed');
+
+ if (!array_key_exists('editing_mode', $module_params)) {
+ $module_params['editing_mode'] = '';
+ }
+
$env = $this->Application->BuildEnv( $this->Get('t'), $module_params, $passed, false, false );
$this->Set(ENV_VAR_NAME, $env);
$_REQUEST['env'] = $_GET['env'] = $env; // for capability with old in-portal code
}
function processRewriteURL()
{
$mod_rw_helper = $this->Application->recallObject('ModRewriteHelper');
$mod_rw_helper->processRewriteURL();
}
function getDefaultTemplate($t)
{
$t = $this->getTemplateName( trim($t, '/') );
if (!$t) $t = 'index';
return trim($t, '/');
}
function extractSIDAndTemplate(&$parts)
{
$vars = Array ();
$sub_parts = array_shift($parts);
list ($sid, $t) = explode('-', $sub_parts, 2);
if ($sid) {
// Save Session ID
$this->Set('sid', $sid);
$vars['sid'] = $sid;
}
// Save Template Name
$vars['t'] = $this->getDefaultTemplate($t);
return $vars;
}
/**
* Process QueryString only, create
* events, ids, based on config
* set template name and sid in
* desired application variables.
*
* @param string $env_var enviroment string value
*
* @access public
*/
function processQueryString($env_var, $pass_name = 'passed')
{
// env=SID:TEMPLATE:m-1-1-1-1:l0-0-0:n-0-0-0:bb-0-0-1-1-1-0
$vars = Array ();
if ($env_var) {
$more_vars = strpos($env_var, '&');
if ($more_vars !== false) {
parse_str(substr($env_var, $more_vars + 1), $vars);
$env_var = substr($env_var, 0, $more_vars);
}
// replace escaped ":" symbol not to explode by it
$env_var = str_replace('\:','_&+$$+&_', $env_var); // replace escaped "=" with spec-chars :)
$parts = explode(':', $env_var);
if (!$this->Application->RewriteURLs() || ($this->Application->RewriteURLs() && $this->Get('rewrite') != 'on')) {
$vars = array_merge_recursive2($vars, $this->extractSIDAndTemplate($parts));
}
if ($parts) {
$passed = Array ();
foreach ($parts as $mixed_part) {
list ($passed[], $processed_vars) = $this->_parseEnvPart($mixed_part);
$vars = array_merge_recursive2($vars, $processed_vars);
}
$vars[$pass_name] = implode(',', array_unique($passed));
}
}
else {
$t = $this->getTemplateName('index');
$vars['t'] = $t;
}
return $vars;
}
/**
* Converts enviroment part into variable array (based on query map for given prefix)
*
* @param string $mixed_part
* @return Array
*/
function _parseEnvPart($mixed_part)
{
// In-portal old style env conversion - adds '-' between prefix and first var
$mixed_part = str_replace('_&+$$+&_', ':', $mixed_part);
$mixed_part = preg_replace("/^([a-zA-Z]+)([0-9]+)-(.*)/", "$1-$2-$3", $mixed_part);
// replace escaped "-" symbol not to explode by it
$escaped_part = str_replace('\-', '_&+$$+&_', $mixed_part);
$escaped_part = explode('-', $escaped_part);
$mixed_part = Array();
foreach ($escaped_part as $escaped_val) {
$mixed_part[] = str_replace('_&+$$+&_', '-', $escaped_val);
}
$prefix_special = array_shift($mixed_part); // l.pick, l
$query_map = $this->Application->EventManager->setQueryMap($prefix_special);
$vars = Array ();
// if config is not defined for prefix in QueryString, then don't process it
if ($query_map) {
foreach ($query_map as $index => $var_name) {
// l_id, l_page, l_bla-bla-bla
$val = $mixed_part[$index - 1];
if ($val == '') $val = false;
$vars[$prefix_special.'_'.$var_name] = $val;
}
}
return Array ($prefix_special, $vars);
}
/**
* Removes tpl part from template name + resolved template ID to name
*
* @param string $t
* @return string
* @access private
*/
function getTemplateName($t)
{
if (array_key_exists('t', $this->Get) && $this->Get['t']) {
// template name is passed directly in url (GET method)
$t = $this->Get['t'];
}
// if t was set through env, even in mod_rewrite mode!
if ($this->Get('env') && $this->Application->RewriteURLs() && $this->Get('t')) {
$t = $this->Get('t');
}
return preg_replace('/\.tpl$/', '', $t);
}
/**
* Saves variables from array specified
* into common variable storage place
*
* @param Array $array
* @return Array
* @access private
*/
function AddVars($array)
{
$array = $this->StripSlashes($array);
foreach($array as $key => $value)
{
$this->Set($key,$value);
}
return $array;
}
function MergeVars($array, $strip_slashes=true)
{
if ($strip_slashes) $array = $this->StripSlashes($array);
foreach($array as $key => $value)
{
$this->_Params = array_merge_recursive2($this->_Params, Array($key=>$value));
}
return $array;
}
function StripSlashes($array)
{
static $magic_quotes = null;
if (!isset($magic_quotes)) {
$magic_quotes = get_magic_quotes_gpc();
}
foreach ($array as $key => $value) {
if (is_array($value)) {
$array[$key] = $this->StripSlashes($value);
}
else {
if ($magic_quotes) {
$value = stripslashes($value);
}
if (!$this->Application->isAdmin) {
$value = htmlspecialchars($value);
}
$array[$key] = $value;
}
}
return $array;
}
/**
* Returns all $_GET array excluding system parameters, that are not allowed to be passed through generated urls
*
* @param bool $access_error Method is called during no_permission, require login, session expiration link preparation
* @return Array
*/
function getRedirectParams($access_error = false)
{
$vars = $this->Get;
$unset_vars = Array (ENV_VAR_NAME, 'rewrite', '_mod_rw_url_', 'Action');
if (!$this->_sidInQueryString) {
$unset_vars[] = 'sid';
}
// remove system variables
foreach ($unset_vars as $var_name) {
if (array_key_exists($var_name, $vars)) {
unset($vars[$var_name]);
}
}
if ($access_error) {
// place 1 of 2 (also in UsersEventHandler::OnSessionExpire)
$vars = $this->_removePassThroughVariables($vars);
}
// transform arrays
return $this->_transformArrays($vars);
}
/**
* Removes all pass_though variables from redirect params
*
* @param Array $url_params
* @return Array
*/
function _removePassThroughVariables($url_params)
{
$pass_through = array_key_exists('pass_through', $url_params) ? $url_params['pass_through'] : '';
if (!$pass_through) {
return $url_params;
}
$pass_through = explode(',', $pass_through . ',pass_through');
foreach ($pass_through as $pass_through_var) {
unset($url_params[$pass_through_var]);
}
$url_params['no_pass_through'] = 1; // this way kApplication::HREF won't add them again
return $url_params;
}
function _transformArrays($array, $level_prefix = '')
{
$ret = Array ();
foreach ($array as $var_name => $var_value) {
$new_var_name = $level_prefix ? $level_prefix . '[' . $var_name . ']' : $var_name;
if (is_array($var_value)) {
$ret = array_merge($ret, $this->_transformArrays($var_value, $new_var_name));
}
else {
$ret[$new_var_name] = $var_value;
}
}
return $ret;
}
function writeRequestLog($filename)
{
$folder_path = dirname(FULL_PATH.'/'.$filename);
if (is_writable($folder_path)) {
$fp = fopen(FULL_PATH.'/'.$filename, 'a');
if ($fp) {
$session =& $this->Application->recallObject('Session');
$user_id = $session->GetField('PortalUserId');
$admin_mark = $this->Application->isAdmin ? 'ADMIN' : 'FRONT';
$data = '['.date('D M d H:i:s Y').'] '.$admin_mark.'; ip: '.$_SERVER['REMOTE_ADDR'].'; user_id: '.$user_id.'; sid: '.$this->Application->GetSID().'; request: '."\n";
if ($this->Get) {
$data .= "_GET:\n".print_r($this->Get, true);
}
if ($this->Post) {
$data .= "_POST:\n".print_r($this->Post, true);
}
if ($this->Cookie) {
$data .= "_COOKIE:\n".print_r($this->Cookie, true);
}
$data .= str_repeat('=', 100)."\n";
fwrite($fp, $data);
fclose($fp);
}
else {
trigger_error('Requrest Log directory not writable', E_USER_WARNING);
}
}
else {
trigger_error('Requrest Log directory not writable', E_USER_WARNING);
}
}
}
\ No newline at end of file
Index: branches/5.0.x/core/kernel/application.php
===================================================================
--- branches/5.0.x/core/kernel/application.php (revision 12952)
+++ branches/5.0.x/core/kernel/application.php (revision 12953)
@@ -1,3002 +1,2999 @@
<?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.
*/
/**
* Basic class for Kernel4-based Application
*
* This class is a Facade for any other class which needs to deal with Kernel4 framework.<br>
* The class incapsulates the main run-cycle of the script, provide access to all other objects in the framework.<br>
* <br>
* The class is a singleton, which means that there could be only one instance of kApplication in the script.<br>
* This could be guranteed by NOT calling the class constuctor directly, but rather calling kApplication::Instance() method,
* which returns an instance of the application. The method gurantees that it will return exactly the same instance for any call.<br>
* See singleton pattern by GOF.
* @package kernel4
*/
defined('FULL_PATH') or die('restricted access!');
class kApplication {
/**
* Is true, when Init method was called already, prevents double initialization
*
* @var bool
*/
var $InitDone = false;
/**
* Holds internal NParser object
* @access private
* @var NParser
*/
var $Parser;
/**
* Holds parser output buffer
* @access private
* @var string
*/
var $HTML;
/**
* Prevents request from beeing proceeded twice in case if application init is called mere then one time
*
* @var bool
* @todo This is not good anyway (by Alex)
*/
var $RequestProcessed = false;
/**
* The main Factory used to create
* almost any class of kernel and
* modules
*
* @access private
* @var kFactory
*/
var $Factory;
/**
* All ConfigurationValues table content (hash) here
*
* @var Array
* @access private
*/
var $ConfigHash = Array();
/**
* Ids of config variables used in current run (for caching)
*
* @var Array
* @access private
*/
var $ConfigCacheIds = array();
/**
* Template names, that will be used instead of regular templates
*
* @var Array
*/
var $ReplacementTemplates = Array ();
/**
* Mod-Rewrite listeners used during url building and parsing
*
* @var Array
*/
var $RewriteListeners = Array ();
/**
* Reference to debugger
*
* @var Debugger
*/
var $Debugger = null;
/**
* Holds all phrases used
* in code and template
*
* @var PhrasesCache
*/
var $Phrases;
/**
* Modules table content, key - module name
*
* @var Array
*/
var $ModuleInfo = Array();
/**
* Holds DBConnection
*
* @var kDBConnection
*/
var $Conn = null;
/**
* Maintains list of user-defined error handlers
*
* @var Array
*/
var $errorHandlers = Array();
// performance needs:
/**
* Holds a refererence to httpquery
*
* @var kHttpQuery
*/
var $HttpQuery = null;
/**
* Holds a reference to UnitConfigReader
*
* @var kUnitConfigReader
*/
var $UnitConfigReader = null;
/**
* Holds a reference to Session
*
* @var Session
*/
var $Session = null;
/**
* Holds a ref to kEventManager
*
* @var kEventManager
*/
var $EventManager = null;
/**
* Ref to itself, needed because everybody used to write $this->Application, even inside kApplication
*
* @var kApplication
*/
var $Application = null;
/**
* Ref for TemplatesChache
*
* @var TemplatesCache
*/
var $TemplatesCache = null;
/**
* Physical template name mapping to their template names based on structure
*
* @var Array
*/
var $structureTemplateMapping = Array ();
var $CompilationCache = array(); //used when compiling templates
var $CachedProcessors = array(); //used when running compiled templates
var $LambdaElements = 1; // for autonumbering unnamed RenderElements [any better place for this prop? KT]
/**
* Holds current NParser tag while parsing, can be used in error messages to display template file and line
*
* @var _BlockTag
*/
var $CurrentNTag = null;
/**
* Memcache object pointer
*
* @var Memcache
*/
var $Memcached = null;
/**
* Tells, that administrator has authentificated in administrative console
* Should be used to manipulate data change OR data restrictioning!
*
* @var bool
*/
var $isAdminUser = false;
/**
* Tells, that admin version of "index.php" was used, nothing more!
* Should be used to manipulate data display!
*
* @var bool
*/
var $isAdmin = false;
/**
* Returns kApplication instance anywhere in the script.
*
* This method should be used to get single kApplication object instance anywhere in the
* Kernel-based application. The method is guranteed to return the SAME instance of kApplication.
* Anywhere in the script you could write:
* <code>
* $application =& kApplication::Instance();
* </code>
* or in an object:
* <code>
* $this->Application =& kApplication::Instance();
* </code>
* to get the instance of kApplication. Note that we call the Instance method as STATIC - directly from the class.
* To use descendand of standard kApplication class in your project you would need to define APPLICATION_CLASS constant
* BEFORE calling kApplication::Instance() for the first time. If APPLICATION_CLASS is not defined the method would
* create and return default KernelApplication instance.
* @static
* @access public
* @return kApplication
*/
function &Instance()
{
static $instance = false;
if(!$instance)
{
safeDefine('APPLICATION_CLASS', 'kApplication');
$class = APPLICATION_CLASS;
$instance = new $class();
$instance->Application =& $instance;
}
return $instance;
}
function InitMemcached()
{
return ;
$memcached_servers = 'localhost:11211'; // $this->Application->ConfigValue('MemcachedServers');
if ($memcached_servers && class_exists('Memcache')) {
$this->Memcached = new Memcache();
$servers = explode(';', $memcached_servers);
foreach ($servers as $server) {
list ($server, $port) = strpos($server, ':') !== false ? explode(':', $server, 2) : Array ($server, 11211);
$this->Memcached->addServer($server, $port);
}
}
//try to set something to cache, if not working - set $this->Memcached to null
}
function CacheSet($name, $value, $expiration)
{
if (isset($this->Memcached)) {
return $this->Memcached->set($name, $value, 0, $expiration);
}
return false;
}
function CacheGet($name)
{
if (isset($this->Memcached)) {
return $this->Memcached->get($name);
}
return false;
}
/**
* Initializes the Application
*
* @access public
* @see kHTTPQuery
* @see Session
* @see TemplatesCache
* @return bool Was Init actually made now or before
*/
function Init()
{
if($this->InitDone) {
return false;
}
$this->isAdmin = constOn('ADMIN');
$this->InitMemcached();
if (!constOn('SKIP_OUT_COMPRESSION')) {
ob_start(); // collect any output from method (other then tags) into buffer
}
if (defined('DEBUG_MODE') && $this->isDebugMode() && constOn('DBG_PROFILE_MEMORY')) {
$this->Debugger->appendMemoryUsage('Application before Init:');
}
if (!$this->isDebugMode() && !constOn('DBG_ZEND_PRESENT')) {
error_reporting(0);
ini_set('display_errors', 0);
}
if (!constOn('DBG_ZEND_PRESENT')) {
$error_handler = set_error_handler( Array (&$this, 'handleError') );
if ($error_handler) {
// wrap around previous error handler, if any was set
$this->errorHandlers[] = $error_handler;
}
}
$this->Conn = new kDBConnection(SQL_TYPE, Array(&$this, 'handleSQLError') );
$this->Conn->debugMode = $this->isDebugMode();
$this->Conn->Connect(SQL_SERVER, SQL_USER, SQL_PASS, SQL_DB);
$this->Factory = new kFactory();
$this->registerDefaultClasses();
$this->Phrases = new PhrasesCache();
$this->EventManager =& $this->Factory->makeClass('EventManager');
$this->Factory->Storage['EventManager'] =& $this->EventManager;
$this->RegisterDefaultBuildEvents();
$this->SetDefaultConstants();
if (defined('DEBUG_MODE') && $this->isDebugMode()) {
$this->Debugger->appendTimestamp('Before UnitConfigReader');
}
$this->UnitConfigReader =& $this->recallObject('kUnitConfigReader');
$this->UnitConfigReader->scanModules(MODULES_PATH);
$this->registerModuleConstants();
if (defined('DEBUG_MODE') && $this->isDebugMode()) {
$this->Debugger->appendTimestamp('After UnitConfigReader');
}
- $rewrite_on = $this->ConfigValue('UseModRewrite');
- // admin=1 - when front is browsed using admin session
- $admin_on = getArrayValue($_REQUEST, 'admin') || $this->isAdmin;
- define('MOD_REWRITE', $rewrite_on && !$admin_on ? 1 : 0);
+ define('MOD_REWRITE', $this->ConfigValue('UseModRewrite') && !$this->isAdmin ? 1 : 0);
$this->HttpQuery =& $this->recallObject('HTTPQuery');
if (defined('DEBUG_MODE') && $this->isDebugMode()) {
$this->Debugger->appendTimestamp('Processed HTTPQuery initial');
}
$this->Session =& $this->recallObject('Session');
if (defined('DEBUG_MODE') && $this->isDebugMode()) {
$this->Debugger->appendTimestamp('Processed Session');
}
if (!$this->RecallVar('UserGroups')) {
$user_groups = trim($this->Session->GetField('GroupList'), ',');
if (!$user_groups) {
$user_groups = $this->ConfigValue('User_GuestGroup');
}
$this->Session->SetField('GroupList', $user_groups);
$this->StoreVar('UserGroups', $user_groups, true); // true for optional
}
$this->LoadStructureTemplateMapping();
$this->HttpQuery->AfterInit();
$this->Session->ValidateExpired();
if (defined('DEBUG_MODE') && $this->isDebugMode()) {
$this->Debugger->appendTimestamp('Processed HTTPQuery AfterInit');
}
$this->LoadCache();
$this->InitConfig();
$this->Phrases->Init('phrases');
if (defined('DEBUG_MODE') && $this->isDebugMode()) {
$this->Debugger->appendTimestamp('Loaded cache and phrases');
}
$this->UnitConfigReader->AfterConfigRead();
if (defined('DEBUG_MODE') && $this->isDebugMode()) {
$this->Debugger->appendTimestamp('Processed AfterConfigRead');
}
/*// Module items are recalled during url parsing & PhrasesCache is needed already there,
// because it's used in their build events. That's why phrases cache initialization is
// called from kHTTPQuery in case when mod_rewrite is used
if (!$this->RewriteURLs()) {
$this->Phrases = new PhrasesCache();
}*/
if ($this->GetVar('m_cat_id') === false) $this->SetVar('m_cat_id', 0);
if (!$this->RecallVar('curr_iso')) {
$this->StoreVar('curr_iso', $this->GetPrimaryCurrency(), true); // true for optional
}
$this->SetVar('visits_id', $this->RecallVar('visit_id') );
$language =& $this->recallObject( 'lang.current', null, Array('live_table' => true) );
if (preg_match('/utf-8/', $language->GetDBField('Charset'))) {
setlocale(LC_ALL, 'en_US.UTF-8');
mb_internal_encoding('UTF-8');
}
$this->ValidateLogin();
if (defined('DEBUG_MODE') && $this->isDebugMode()) {
$this->Debugger->profileFinish('kernel4_startup');
}
$this->InitDone = true;
$this->HandleEvent( new kEvent('adm:OnStartup') );
return true;
}
/**
* Returns module information. Searches module by requested field
*
* @param string $field
* @param mixed $value
* @param string field value to returns, if not specified, then return all fields
* @param string field to return
* @return Array
*/
function findModule($field, $value, $return_field = null)
{
$found = false;
foreach ($this->ModuleInfo as $module_name => $module_info) {
if (strtolower($module_info[$field]) == strtolower($value)) {
$found = true;
break;
}
}
if ($found) {
return isset($return_field) ? $module_info[$return_field] : $module_info;
}
return false;
}
function refreshModuleInfo()
{
if (defined('IS_INSTALL') && IS_INSTALL && !$this->TableFound('Modules')) {
$this->registerModuleConstants();
return false;
}
$modules_helper =& $this->recallObject('ModulesHelper');
/* @var $modules_helper kModulesHelper */
$sql = 'SELECT *
FROM ' . TABLE_PREFIX . 'Modules
WHERE Loaded = 1
ORDER BY LoadOrder';
$this->ModuleInfo = $this->Conn->Query($sql, 'Name');
$sql = 'SELECT *
FROM '.TABLE_PREFIX.'Modules
WHERE '.$modules_helper->getWhereClause().'
ORDER BY LoadOrder';
$this->ModuleInfo = $this->Conn->Query($sql, 'Name');
$this->registerModuleConstants();
}
/**
* Checks if passed language id if valid and sets it to primary otherwise
*
*/
function VerifyLanguageId()
{
$language_id = $this->GetVar('m_lang');
if (!$language_id) {
$language_id = 'default';
}
$this->SetVar('lang.current_id', $language_id );
$this->SetVar('m_lang', $language_id );
$lang_mode = $this->GetVar('lang_mode');
$this->SetVar('lang_mode', '');
$lang =& $this->recallObject('lang.current');
/* @var $lang kDBItem */
if (!$lang->isLoaded() || (!$this->isAdmin && !$lang->GetDBField('Enabled'))) {
if (!defined('IS_INSTALL')) {
$this->ApplicationDie('Unknown or disabled language');
}
}
$this->SetVar('lang_mode',$lang_mode);
}
/**
* Checks if passed theme id if valid and sets it to primary otherwise
*
*/
function VerifyThemeId()
{
if ($this->isAdmin) {
safeDefine('THEMES_PATH', '/core/admin_templates');
return;
}
$path = $this->GetFrontThemePath();
if ($path === false) {
$this->ApplicationDie('No Primary Theme Selected or Current Theme is Unknown or Disabled');
}
safeDefine('THEMES_PATH', $path);
/*$theme_id = $this->GetVar('m_theme');
if (!$theme_id) {
$theme_id = $this->GetDefaultThemeId();
if (!$theme_id) {
if (!defined('IS_INSTALL')) $this->ApplicationDie('No Primary Theme Selected');
}
}
$this->SetVar('m_theme', $theme_id);
$this->SetVar('theme.current_id', $theme_id ); // KOSTJA: this is to fool theme' getPassedId
$theme =& $this->recallObject('theme.current');
if (!$theme->IsLoaded() || !$theme->GetDBField('Enabled')) {
if (!defined('IS_INSTALL')) $this->ApplicationDie('Unknown or disabled theme');
}
safeDefine('THEMES_PATH', '/themes/'.$theme->GetDBField('Name'));*/
}
function GetFrontThemePath($force=0)
{
static $path=null;
if (!$force && isset($path)) return $path;
$theme_id = $this->GetVar('m_theme');
if (!$theme_id) {
// $theme_id = $this->GetDefaultThemeId(1); //1 to force front-end mode!
$theme_id = 'default';
}
$this->SetVar('m_theme', $theme_id);
$this->SetVar('theme.current_id', $theme_id ); // KOSTJA: this is to fool theme' getPassedId
$theme =& $this->recallObject('theme.current');
if (!$theme->IsLoaded() || !$theme->GetDBField('Enabled')) {
return false;
}
$path = '/themes/'.$theme->GetDBField('Name');
return $path;
}
function GetDefaultLanguageId()
{
static $language_id = 0;
if ($language_id > 0) {
return $language_id;
}
$table = $this->getUnitOption('lang', 'TableName');
$id_field = $this->getUnitOption('lang', 'IDField');
$sql = 'SELECT '.$id_field.'
FROM '.$table.'
WHERE (PrimaryLang = 1) AND (Enabled = 1)';
$language_id = $this->Conn->GetOne($sql);
if (!$language_id && defined('IS_INSTALL') && IS_INSTALL) {
$language_id = 1;
}
return $language_id;
}
function GetDefaultThemeId($force_front=0)
{
static $theme_id = 0;
if ($theme_id > 0) {
return $theme_id;
}
if (constOn('DBG_FORCE_THEME')) {
$theme_id = DBG_FORCE_THEME;
}
elseif (!$force_front && $this->isAdmin) {
$theme_id = 999;
}
else {
$table = $this->getUnitOption('theme','TableName');
$id_field = $this->getUnitOption('theme','IDField');
$sql = 'SELECT '.$id_field.'
FROM '.$table.'
WHERE (PrimaryTheme = 1) AND (Enabled = 1)';
$theme_id = $this->Conn->GetOne($sql);
}
return $theme_id;
}
function GetPrimaryCurrency()
{
if ($this->isModuleEnabled('In-Commerce')) {
$table = $this->getUnitOption('curr', 'TableName');
return $this->Conn->GetOne('SELECT ISO FROM '.$table.' WHERE IsPrimary = 1');
}
else {
return 'USD';
}
}
/**
* Registers default classes such as ItemController, GridController and LoginController
*
* Called automatically while initializing Application
* @access private
* @return void
*/
function RegisterDefaultClasses()
{
$this->registerClass('kTempTablesHandler', KERNEL_PATH . '/utility/temp_handler.php');
$this->registerClass('kEventManager', KERNEL_PATH . '/event_manager.php', 'EventManager');
$this->registerClass('kUnitConfigReader', KERNEL_PATH . '/utility/unit_config_reader.php');
$this->registerClass('kArray', KERNEL_PATH . '/utility/params.php');
$this->registerClass('Params', KERNEL_PATH . '/utility/params.php');
$this->registerClass('Params', KERNEL_PATH . '/utility/params.php', 'kActions');
$this->registerClass('kCache', KERNEL_PATH . '/utility/cache.php', 'Cache', 'Params');
$this->registerClass('kHTTPQuery', KERNEL_PATH . '/utility/http_query.php', 'HTTPQuery', 'Params');
$this->registerClass('kHelper', KERNEL_PATH . '/kbase.php');
$this->registerClass('kMultipleFilter', KERNEL_PATH . '/utility/filters.php');
$this->registerClass('Session', KERNEL_PATH . '/session/session.php');
$this->registerClass('SessionStorage', KERNEL_PATH . '/session/session.php');
$this->registerClass('InpSession', KERNEL_PATH . '/session/inp_session.php', 'Session');
$this->registerClass('InpSessionStorage', KERNEL_PATH . '/session/inp_session.php', 'SessionStorage');
$this->registerClass('kTagProcessor', KERNEL_PATH . '/processors/tag_processor.php');
$this->registerClass('kMainTagProcessor', KERNEL_PATH . '/processors/main_processor.php','m_TagProcessor', 'kTagProcessor');
$this->registerClass('kDBList', KERNEL_PATH . '/db/dblist.php');
$this->registerClass('kDBItem', KERNEL_PATH . '/db/dbitem.php');
$this->registerClass('kDBEventHandler', KERNEL_PATH . '/db/db_event_handler.php');
$this->registerClass('kDBTagProcessor', KERNEL_PATH . '/db/db_tag_processor.php', null, 'kTagProcessor');
$this->registerClass('kCatDBItem', KERNEL_PATH . '/db/cat_dbitem.php');
$this->registerClass('kCatDBList', KERNEL_PATH . '/db/cat_dblist.php');
$this->registerClass('kCatDBEventHandler', KERNEL_PATH . '/db/cat_event_handler.php');
$this->registerClass('kCatDBTagProcessor', KERNEL_PATH . '/db/cat_tag_processor.php');
$this->registerClass('NParser', KERNEL_PATH . '/nparser/nparser.php');
$this->registerClass('TemplatesCache', KERNEL_PATH . '/nparser/template_cache.php', null, Array ('kHelper', 'kDBTagProcessor'));
$this->registerClass('kEmailSendingHelper', KERNEL_PATH . '/utility/email_send.php', 'EmailSender', 'kHelper');
$this->registerClass('kSocket', KERNEL_PATH . '/utility/socket.php', 'Socket');
if (file_exists(MODULES_PATH . '/in-commerce/units/currencies/currency_rates.php')) {
$this->registerClass('kCurrencyRates', MODULES_PATH . '/in-commerce/units/currencies/currency_rates.php');
}
// do not move to config - this helper is used before configs are read
$this->registerClass('kModulesHelper', KERNEL_PATH . '/../units/helpers/modules_helper.php', 'ModulesHelper');
}
function RegisterDefaultBuildEvents()
{
$event_manager =& $this->recallObject('EventManager');
$event_manager->registerBuildEvent('kTempTablesHandler', 'OnTempHandlerBuild');
}
/**
* Returns item's filename that corresponds id passed. If possible, then get it from cache
*
* @param string $prefix
* @param int $id
* @return string
*/
function getFilename($prefix, $id, $category_id=null)
{
$filename = $this->getCache('filenames', $prefix.'_'.$id);
if ($filename === false) {
$table = $this->getUnitOption($prefix, 'TableName');
$id_field = $this->getUnitOption($prefix, 'IDField');
if ($prefix == 'c') {
if(!$id) {
$this->setCache('filenames', $prefix.'_'.$id, '');
return '';
}
// this allows to save 2 sql queries for each category
$sql = 'SELECT NamedParentPath, CachedTemplate, TreeLeft, TreeRight
FROM '.$table.'
WHERE '.$id_field.' = '.$this->Conn->qstr($id);
$category_data = $this->Conn->GetRow($sql);
// only direct links to category pages work (symlinks, container pages and so on won't work)
$filename = $category_data['NamedParentPath'];
$this->setCache('category_templates', $id, $filename);
$this->setCache('category_designs', $id, ltrim($category_data['CachedTemplate'], '/'));
$this->setCache('category_tree', $id, $category_data['TreeLeft'] . ';' . $category_data['TreeRight']);
}
else {
$sql = 'SELECT ResourceId
FROM ' . $table . '
WHERE ' . $id_field . ' = ' . $this->Conn->qstr($id);
$resource_id = $this->Conn->GetOne($sql);
if (is_null($category_id)) {
$category_id = $this->GetVar('m_cat_id');
}
$sql = 'SELECT Filename
FROM ' . TABLE_PREFIX . 'CategoryItems
WHERE (ItemResourceId = ' . $resource_id . ') AND (CategoryId = ' . (int)$category_id . ')';
$filename = $this->Conn->GetOne($sql);
/*if (!$filename) {
$sql = 'SELECT Filename
FROM ' . TABLE_PREFIX . 'CategoryItems
WHERE ItemResourceId = ' . $resource_id . ' AND PrimaryCat = 1';
$filename = $this->Conn->GetOne($sql);
}
$sql = 'SELECT Filename
FROM ' . $table . '
WHERE ' . $id_field . ' = ' . $this->Conn->qstr($id);
$filename = $this->Conn->GetOne($sql);*/
}
$this->setCache('filenames', $prefix.'_'.$id, $filename);
}
return $filename;
}
/**
* Adds new value to cache $cache_name and identified by key $key
*
* @param string $cache_name cache name
* @param int $key key name to add to cache
* @param mixed $value value of chached record
*/
function setCache($cache_name, $key, $value, $expiration=3600)
{
$cache =& $this->recallObject('Cache');
/* @var $cache kCache */
return $cache->setCache($cache_name, $key, $value, $expiration);
}
/**
* Returns cached $key value from cache named $cache_name
*
* @param string $cache_name cache name
* @param int $key key name from cache
* @return mixed
*/
function getCache($cache_name, $key)
{
$cache =& $this->recallObject('Cache');
return $cache->getCache($cache_name, $key);
}
/**
* Defines default constants if it's not defined before - in config.php
*
* @access private
*/
function SetDefaultConstants() // it's defined in startup.php - can be removed??
{
safeDefine('SERVER_NAME', $_SERVER['HTTP_HOST']);
}
/**
* Registers each module specific constants if any found
*
*/
function registerModuleConstants()
{
if (file_exists(KERNEL_PATH.'/constants.php')) {
k4_include_once(KERNEL_PATH.'/constants.php');
}
if (!$this->ModuleInfo) return false;
foreach($this->ModuleInfo as $module_name => $module_info)
{
$module_path = '/'.$module_info['Path'];
$contants_file = FULL_PATH.$module_path.'constants.php';
if( file_exists($contants_file) ) k4_include_once($contants_file);
}
return true;
}
function ProcessRequest()
{
$event_manager =& $this->recallObject('EventManager');
/* @var $event_manager kEventManager */
if (defined('DEBUG_MODE') && $this->isDebugMode() && constOn('DBG_SHOW_HTTPQUERY')) {
$this->Debugger->appendHTML('HTTPQuery:');
$this->Debugger->dumpVars($this->HttpQuery->_Params);
}
$event_manager->ProcessRequest();
$event_manager->RunRegularEvents(reBEFORE);
$this->RequestProcessed = true;
}
/**
* Actually runs the parser against current template and stores parsing result
*
* This method gets t variable passed to the script, loads the template given in t variable and
* parses it. The result is store in {@link $this->HTML} property.
* @access public
* @return void
*/
function Run()
{
if (defined('DEBUG_MODE') && $this->isDebugMode() && constOn('DBG_PROFILE_MEMORY')) {
$this->Debugger->appendMemoryUsage('Application before Run:');
}
if ($this->isAdminUser) {
// for permission checking in events & templates
$this->LinkVar('module'); // for common configuration templates
$this->LinkVar('module_key'); // for common search templates
$this->LinkVar('section'); // for common configuration templates
if ($this->GetVar('m_opener') == 'p') {
$this->LinkVar('main_prefix'); // window prefix, that opened selector
$this->LinkVar('dst_field'); // field to set value choosed in selector
}
if ($this->GetVar('ajax') == 'yes' && !$this->GetVar('debug_ajax')) {
// hide debug output from ajax requests automatically
define('DBG_SKIP_REPORTING', 1);
}
}
elseif ($this->GetVar('admin')) {
// viewing front-end through admin's frame
$admin_session =& $this->Application->recallObject('Session.admin');
$user = (int)$admin_session->RecallVar('user_id'); // in case, when no valid admin session found
$perm_helper =& $this->recallObject('PermissionsHelper');
/* @var $perm_helper kPermissionsHelper */
if ($perm_helper->CheckUserPermission($user, 'CATEGORY.MODIFY', 0, $this->ModuleInfo['Core']['RootCat'])) {
// user can edit cms blocks
$editing_mode = $this->GetVar('editing_mode');
define('EDITING_MODE', $editing_mode ? $editing_mode : EDITING_MODE_BROWSE);
$this->Phrases->setPhraseEditing();
}
}
safeDefine('EDITING_MODE', ''); // user can't edit anything
if (!$this->RequestProcessed) $this->ProcessRequest();
$this->InitParser();
$t = $this->GetVar('t');
if (!$this->TemplatesCache->TemplateExists($t) && !$this->isAdmin) {
$cms_handler =& $this->recallObject('st_EventHandler');
/* @var $cms_handler CategoriesEventHandler */
$t = ltrim($cms_handler->GetDesignTemplate(), '/');
if (defined('DEBUG_MODE') && $this->isDebugMode()) {
$this->Debugger->appendHTML('<strong>Design Template</strong>: ' . $t . '; <strong>CategoryID</strong>: ' . $this->GetVar('m_cat_id'));
}
}
/*else {
$cms_handler->SetCatByTemplate();
}*/
if (defined('DEBUG_MODE') && $this->isDebugMode() && constOn('DBG_PROFILE_MEMORY')) {
$this->Debugger->appendMemoryUsage('Application before Parsing:');
}
$this->HTML = $this->Parser->Run($t);
if (defined('DEBUG_MODE') && $this->isDebugMode() && constOn('DBG_PROFILE_MEMORY')) {
$this->Debugger->appendMemoryUsage('Application after Parsing:');
}
}
function InitParser($theme_name = false)
{
if( !is_object($this->Parser) ) {
$this->Parser =& $this->recallObject('NParser');
$this->TemplatesCache =& $this->recallObject('TemplatesCache');
}
$this->TemplatesCache->forceThemeName = $theme_name;
}
/**
* Send the parser results to browser
*
* Actually send everything stored in {@link $this->HTML}, to the browser by echoing it.
* @access public
* @return void
*/
function Done()
{
$this->HandleEvent( new kEvent('adm:OnBeforeShutdown') );
if (defined('DEBUG_MODE') && $this->isDebugMode() && constOn('DBG_PROFILE_MEMORY')) {
$this->Debugger->appendMemoryUsage('Application before Done:');
}
if (defined('DEBUG_MODE') && $this->isDebugMode()) {
$this->EventManager->RunRegularEvents(reAFTER);
$this->Session->SaveData();
if (constOn('DBG_CACHE')) {
$cache =& $this->recallObject('Cache');
$cache->printStatistics();
}
$this->HTML = ob_get_clean() . $this->HTML . $this->Debugger->printReport(true);
}
else {
$this->HTML = ob_get_clean().$this->HTML;
}
if ($this->UseOutputCompression()) {
header('Content-Encoding: gzip');
$compression_level = $this->ConfigValue('OutputCompressionLevel');
if ($compression_level < 0 || $compression_level > 9) $compression_level = 7;
echo gzencode($this->HTML, $compression_level);
}
else {
echo $this->HTML;
}
$this->UpdateCache();
flush();
if (!$this->isDebugMode()) {
$this->EventManager->RunRegularEvents(reAFTER);
$this->Session->SaveData();
}
if (defined('DBG_CAPTURE_STATISTICS') && DBG_CAPTURE_STATISTICS && !$this->isAdmin) {
$this->_storeStatistics();
}
}
/**
* Stores script execution statistics to database
*
*/
function _storeStatistics()
{
global $start;
$script_time = getmicrotime() - $start;
$query_statistics = $this->Conn->getQueryStatistics(); // time & count
$sql = 'SELECT *
FROM ' . TABLE_PREFIX . 'StatisticsCapture
WHERE TemplateName = ' . $this->Conn->qstr( $this->GetVar('t') );
$data = $this->Conn->GetRow($sql);
if ($data) {
$this->_updateAverageStatistics($data, 'ScriptTime', $script_time);
$this->_updateAverageStatistics($data, 'SqlTime', $query_statistics['time']);
$this->_updateAverageStatistics($data, 'SqlCount', $query_statistics['count']);
$data['Hits']++;
$data['LastHit'] = adodb_mktime();
$this->Conn->doUpdate($data, TABLE_PREFIX . 'StatisticsCapture', 'StatisticsId = ' . $data['StatisticsId']);
}
else {
$data['ScriptTimeMin'] = $data['ScriptTimeAvg'] = $data['ScriptTimeMax'] = $script_time;
$data['SqlTimeMin'] = $data['SqlTimeAvg'] = $data['SqlTimeMax'] = $query_statistics['time'];
$data['SqlCountMin'] = $data['SqlCountAvg'] = $data['SqlCountMax'] = $query_statistics['count'];
$data['TemplateName'] = $this->GetVar('t');
$data['Hits'] = 1;
$data['LastHit'] = adodb_mktime();
$this->Conn->doInsert($data, TABLE_PREFIX . 'StatisticsCapture');
}
}
/**
* Calculates average time for statistics
*
* @param Array $data
* @param string $field_prefix
* @param float $current_value
*/
function _updateAverageStatistics(&$data, $field_prefix, $current_value)
{
$data[$field_prefix . 'Avg'] = (($data['Hits'] * $data[$field_prefix . 'Avg']) + $current_value) / ($data['Hits'] + 1);
if ($current_value < $data[$field_prefix . 'Min']) {
$data[$field_prefix . 'Min'] = $current_value;
}
if ($current_value > $data[$field_prefix . 'Max']) {
$data[$field_prefix . 'Max'] = $current_value;
}
}
function logSlowQuery($slow_sql, $time)
{
$query_crc = crc32($slow_sql);
$sql = 'SELECT *
FROM ' . TABLE_PREFIX . 'SlowSqlCapture
WHERE QueryCrc = ' . $query_crc;
$data = $this->Conn->Query($sql, null, true);
if ($data) {
$this->_updateAverageStatistics($data, 'Time', $time);
$template_names = explode(',', $data['TemplateNames']);
array_push($template_names, $this->GetVar('t'));
$data['TemplateNames'] = implode(',', array_unique($template_names));
$data['Hits']++;
$data['LastHit'] = adodb_mktime();
$this->Conn->doUpdate($data, TABLE_PREFIX . 'SlowSqlCapture', 'CaptureId = ' . $data['CaptureId']);
}
else {
$data['TimeMin'] = $data['TimeAvg'] = $data['TimeMax'] = $time;
$data['SqlQuery'] = $slow_sql;
$data['QueryCrc'] = $query_crc;
$data['TemplateNames'] = $this->GetVar('t');
$data['Hits'] = 1;
$data['LastHit'] = adodb_mktime();
$this->Conn->doInsert($data, TABLE_PREFIX . 'SlowSqlCapture');
}
}
/**
* Checks if output compression options is available
*
* @return string
*/
function UseOutputCompression()
{
if (constOn('IS_INSTALL') || constOn('DBG_ZEND_PRESENT') || constOn('SKIP_OUT_COMPRESSION')) return false;
return $this->ConfigValue('UseOutputCompression') && function_exists('gzencode') && strstr($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip');
}
// Facade
/**
* Returns current session id (SID)
* @access public
* @return longint
*/
function GetSID()
{
$session =& $this->recallObject('Session');
return $session->GetID();
}
function DestroySession()
{
$session =& $this->recallObject('Session');
$session->Destroy();
}
/**
* Returns variable passed to the script as GET/POST/COOKIE
*
* @access public
* @param string $name Name of variable to retrieve
* @param int $default default value returned in case if varible not present
* @return mixed
*/
function GetVar($name, $default = false)
{
return isset($this->HttpQuery->_Params[$name]) ? $this->HttpQuery->_Params[$name] : $default;
}
/**
* Returns ALL variables passed to the script as GET/POST/COOKIE
*
* @access public
* @return array
*/
function GetVars()
{
return $this->HttpQuery->GetParams();
}
/**
* Set the variable 'as it was passed to the script through GET/POST/COOKIE'
*
* This could be useful to set the variable when you know that
* other objects would relay on variable passed from GET/POST/COOKIE
* or you could use SetVar() / GetVar() pairs to pass the values between different objects.<br>
*
* This method is formerly known as $this->Session->SetProperty.
* @param string $var Variable name to set
* @param mixed $val Variable value
* @access public
* @return void
*/
function SetVar($var,$val)
{
return $this->HttpQuery->Set($var, $val);
}
/**
* Deletes kHTTPQuery variable
*
* @param string $var
* @todo think about method name
*/
function DeleteVar($var)
{
return $this->HttpQuery->Remove($var);
}
/**
* Deletes Session variable
*
* @param string $var
*/
function RemoveVar($var)
{
return $this->Session->RemoveVar($var);
}
function RemovePersistentVar($var)
{
return $this->Session->RemovePersistentVar($var);
}
/**
* Restores Session variable to it's db version
*
* @param string $var
*/
function RestoreVar($var)
{
return $this->Session->RestoreVar($var);
}
/**
* Returns session variable value
*
* Return value of $var variable stored in Session. An optional default value could be passed as second parameter.
*
* @see SimpleSession
* @access public
* @param string $var Variable name
* @param mixed $default Default value to return if no $var variable found in session
* @return mixed
*/
function RecallVar($var,$default=false)
{
return $this->Session->RecallVar($var,$default);
}
function RecallPersistentVar($var, $default = false)
{
return $this->Session->RecallPersistentVar($var, $default);
}
/**
* Stores variable $val in session under name $var
*
* Use this method to store variable in session. Later this variable could be recalled.
* @see RecallVar
* @access public
* @param string $var Variable name
* @param mixed $val Variable value
*/
function StoreVar($var, $val, $optional = false)
{
$session =& $this->recallObject('Session');
$this->Session->StoreVar($var, $val, $optional);
}
function StorePersistentVar($var, $val)
{
$this->Session->StorePersistentVar($var, $val);
}
function StoreVarDefault($var, $val, $optional=false)
{
$session =& $this->recallObject('Session');
$this->Session->StoreVarDefault($var, $val, $optional);
}
/**
* Links HTTP Query variable with session variable
*
* If variable $var is passed in HTTP Query it is stored in session for later use. If it's not passed it's recalled from session.
* This method could be used for making sure that GetVar will return query or session value for given
* variable, when query variable should overwrite session (and be stored there for later use).<br>
* This could be used for passing item's ID into popup with multiple tab -
* in popup script you just need to call LinkVar('id', 'current_id') before first use of GetVar('id').
* After that you can be sure that GetVar('id') will return passed id or id passed earlier and stored in session
* @access public
* @param string $var HTTP Query (GPC) variable name
* @param mixed $ses_var Session variable name
* @param mixed $default Default variable value
*/
function LinkVar($var, $ses_var = null, $default = '', $optional = false)
{
if (!isset($ses_var)) $ses_var = $var;
if ($this->GetVar($var) !== false) {
$this->StoreVar($ses_var, $this->GetVar($var), $optional);
}
else {
$this->SetVar($var, $this->RecallVar($ses_var, $default));
}
}
/**
* Returns variable from HTTP Query, or from session if not passed in HTTP Query
*
* The same as LinkVar, but also returns the variable value taken from HTTP Query if passed, or from session if not passed.
* Returns the default value if variable does not exist in session and was not passed in HTTP Query
*
* @see LinkVar
* @access public
* @param string $var HTTP Query (GPC) variable name
* @param mixed $ses_var Session variable name
* @param mixed $default Default variable value
* @return mixed
*/
function GetLinkedVar($var, $ses_var = null, $default = '')
{
$this->LinkVar($var, $ses_var, $default);
return $this->GetVar($var);
}
function AddBlock($name, $tpl)
{
$this->cache[$name] = $tpl;
}
function ProcessParsedTag($prefix, $tag, $params)
{
$processor = $this->Parser->GetProcessor($prefix);
return $processor->ProcessParsedTag($tag, $params, $prefix);
}
/**
* Return ADODB Connection object
*
* Returns ADODB Connection object already connected to the project database, configurable in config.php
* @access public
* @return kDBConnection
*/
function &GetADODBConnection()
{
return $this->Conn;
}
/**
* Allows to parse given block name or include template
*
* @param Array $params Parameters to pass to block. Reserved parameter "name" used to specify block name.
* @param Array $pass_params Forces to pass current parser params to this block/template. Use with cauntion, because you can accidently pass "block_no_data" parameter.
* @param bool $as_template
* @return string
*/
function ParseBlock($params, $pass_params = 0, $as_template = false)
{
if (substr($params['name'], 0, 5) == 'html:') {
return substr($params['name'], 6);
}
return $this->Parser->ParseBlock($params, $pass_params, $as_template);
}
/**
* Allows to include template with a given name and given parameters
*
* @param Array $params Parameters to pass to template. Reserved parameter "name" used to specify template name.
* @return string
*/
function IncludeTemplate($params)
{
return $this->Parser->IncludeTemplate($params, isset($params['is_silent']) ? 1 : 0);
}
/**
* Returns index file, that could be passed as parameter to method, as parameter to tag and as constant or not passed at all
*
* @param string $prefix
* @param string $index_file
* @param Array $params
* @return string
*/
function getIndexFile($prefix, $index_file, &$params)
{
if (isset($params['index_file'])) {
$index_file = $params['index_file'];
unset($params['index_file']);
return $index_file;
}
if (isset($index_file)) {
return $index_file;
}
if (defined('INDEX_FILE')) {
return INDEX_FILE;
}
$cut_prefix = trim(BASE_PATH, '/').'/'.trim($prefix, '/');
return trim(preg_replace('/'.preg_quote($cut_prefix, '/').'(.*)/', '\\1', $_SERVER['PHP_SELF']), '/');
}
/**
* Return href for template
*
* @access public
* @param string $t Template path
* @var string $prefix index.php prefix - could be blank, 'admin'
*/
function HREF($t, $prefix = '', $params = null, $index_file = null)
{
static $theme_id = null;
if (!isset($theme_id)) {
$theme_id = $this->GetVar('m_theme');
}
if (!$t) {
// when template not specified, use current
$t = $this->GetVar('t');
}
$t = preg_replace('/^Content\//i', '', $t);
if (substr($t, -4) == '.tpl') {
// cut template extension (deprecated link format)
$t = substr($t, 0, strlen($t) - 4);
}
if (substr($t, 0, 3) == 'id:') {
// link to structure page using it's id
$params['m_cat_id'] = substr($t, 3);
$t = $this->structureTemplateMapping[$t];
}
if (array_key_exists('use_section', $params)) {
$use_section = $params['use_section'];
unset($params['use_section']);
}
if (isset($use_section) && $use_section && array_key_exists($t . ':' . $theme_id, $this->structureTemplateMapping)) {
// structure template corresponding to given physical template
$t = $this->structureTemplateMapping[$t . ':' . $theme_id];
unset($params['use_section']);
}
if (preg_match('/external:(.*)/', $t, $rets)) {
// external url
return $rets[1];
}
if ($this->isAdmin && $prefix == '') $prefix = ADMIN_DIRECTORY;
if ($this->isAdmin && $prefix == '_FRONT_END_') $prefix = '';
$index_file = $this->getIndexFile($prefix, $index_file, $params);
if (isset($params['_auto_prefix_'])) {
unset($params['_auto_prefix_']); // this is parser-related param, do not need to pass it here
}
$ssl = isset($params['__SSL__']) ? $params['__SSL__'] : null;
if ($ssl !== null) {
$session =& $this->recallObject('Session');
$cookie_url = trim($session->CookieDomain.$session->CookiePath, '/.');
if ($ssl) {
$target_url = defined('ADMIN') && ADMIN ? $this->ConfigValue('AdminSSL_URL') : false;
if (!$target_url) {
$target_url = $this->ConfigValue('SSL_URL');
}
}
else {
$target_url = 'http://'.DOMAIN.$this->ConfigValue('Site_Path');
}
if (!preg_match('#'.preg_quote($cookie_url).'#', $target_url)) {
$session->SetMode(smGET_ONLY);
}
}
if (isset($params['opener']) && $params['opener'] == 'u') {
$wid = $this->Application->GetVar('m_wid');
$stack_name = rtrim('opener_stack_'.$wid, '_');
$opener_stack = $this->RecallVar($stack_name);
if ($opener_stack && $opener_stack != serialize(Array())) {
$opener_stack = unserialize($opener_stack);
list($index_file, $env) = explode('|', $opener_stack[count($opener_stack) - 1]);
$ret = $this->BaseURL($prefix, $ssl).$index_file.'?'.ENV_VAR_NAME.'='.$env;
if ( getArrayValue($params,'escape') ) $ret = addslashes($ret);
if (isset($params['m_opener']) && $params['m_opener'] == 'u') {
array_pop($opener_stack);
if (!$opener_stack) {
$this->RemoveVar($stack_name);
// remove popups last templates, because popup is closing now
$this->RemoveVar('last_template_'.$wid);
$this->RemoveVar('last_template_popup_'.$wid);
// don't save popups last templates again :)
$this->SetVar('skip_last_template', 1);
}
else {
$this->StoreVar($stack_name, serialize($opener_stack));
}
/*// store window relations
$window_relations = $this->Application->RecallVar('window_relations');
$window_relations = $window_relations ? unserialize($window_relations) : Array ();
if (array_key_exists($wid, $window_relations)) {
unset($window_relations[$wid]);
$this->Application->StoreVar('window_relations', serialize($window_relations));
}*/
}
return $ret;
}
else {
//define('DBG_REDIRECT', 1);
$t = $this->GetVar('t');
}
}
$pass = isset($params['pass']) ? $params['pass'] : '';
$pass_events = isset($params['pass_events']) ? $params['pass_events'] : false; // pass events with url
$map_link = '';
if( isset($params['anchor']) )
{
$map_link = '#'.$params['anchor'];
unset($params['anchor']);
}
if ( isset($params['no_amp']) )
{
$params['__URLENCODE__'] = $params['no_amp'];
unset($params['no_amp']);
}
$no_rewrite = false;
if( isset($params['__NO_REWRITE__']) )
{
$no_rewrite = true;
unset($params['__NO_REWRITE__']);
}
$force_rewrite = false;
if( isset($params['__MOD_REWRITE__']) )
{
$force_rewrite = true;
unset($params['__MOD_REWRITE__']);
}
$force_no_sid = false;
if( isset($params['__NO_SID__']) )
{
$force_no_sid = true;
unset($params['__NO_SID__']);
}
// append pass through variables to each link to be build
// $params = array_merge_recursive2($this->getPassThroughVariables($params), $params);
$params = array_merge($this->getPassThroughVariables($params), $params);
if ($force_rewrite || ($this->RewriteURLs($ssl) && !$no_rewrite)) {
static $rewrite_listeners_done = false;
if (!$rewrite_listeners_done) {
$mod_rewrite_helper =& $this->recallObject('ModRewriteHelper');
/* @var $mod_rewrite_helper kModRewriteHelper */
$mod_rewrite_helper->initRewriteListeners();
$rewrite_listeners_done = true;
}
$session =& $this->recallObject('Session');
if ($session->NeedQueryString() && !$force_no_sid) {
$params['sid'] = $this->GetSID();
}
$url = $this->BuildEnv_NEW($t, $params, $pass, $pass_events);
$ret = $this->BaseURL($prefix, $ssl).$url.$map_link;
}
else {
unset($params['pass_category']); // we don't need to pass it when mod_rewrite is off
$env = $this->BuildEnv($t, $params, $pass, $pass_events);
$ret = $this->BaseURL($prefix, $ssl).$index_file.'?'.$env.$map_link;
}
return $ret;
}
/**
* Returns variables with values that should be passed throught with this link + variable list
*
* @param Array $params
* @return Array
*/
function getPassThroughVariables(&$params)
{
static $cached_pass_through = null;
if (isset($params['no_pass_through']) && $params['no_pass_through']) {
unset($params['no_pass_through']);
return Array();
}
// because pass through is not changed during script run, then we can cache it
if (is_null($cached_pass_through)) {
$cached_pass_through = Array();
$pass_through = $this->Application->GetVar('pass_through');
if ($pass_through) {
// names of variables to pass to each link
$cached_pass_through['pass_through'] = $pass_through;
$pass_through = explode(',', $pass_through);
foreach ($pass_through as $pass_through_var) {
$cached_pass_through[$pass_through_var] = $this->Application->GetVar($pass_through_var);
}
}
}
return $cached_pass_through;
}
/**
* Returns sorted array of passed prefixes (to build url from)
*
* @param string $pass
* @return Array
*/
function getPassInfo($pass = 'all')
{
if (!$pass) $pass = 'all';
$pass = trim(
preg_replace(
'/(?<=,|\\A)all(?=,|\\z)/',
trim($this->GetVar('passed'), ','),
trim($pass, ',')
),
',');
if (!$pass) {
return Array();
}
$pass_info = array_unique( explode(',', $pass) ); // array( prefix[.special], prefix[.special] ...
// we need to keep that sorting despite the sorting below, because this sorts prefixes with same priority by name
sort($pass_info, SORT_STRING); // to be prefix1,prefix1.special1,prefix1.special2,prefix3.specialX
foreach ($pass_info as $prefix) {
list($prefix_only) = explode('.', $prefix, 1);
$sorted[$prefix] = $this->getUnitOption($prefix_only, 'RewritePriority', 0);
}
arsort($sorted);
$pass_info = array_keys($sorted);
// ensure that "m" prefix is at the beginning
$main_index = array_search('m', $pass_info);
if ($main_index !== false) {
unset($pass_info[$main_index]);
array_unshift($pass_info, 'm');
}
return $pass_info;
}
function BuildEnv_NEW($t, $params, $pass='all', $pass_events = false)
{
// $session =& $this->recallObject('Session');
$force_admin = getArrayValue($params,'admin') || $this->GetVar('admin');
// if($force_admin) $sid = $this->GetSID();
$ret = '';
$env = '';
$encode = false;
if (isset($params['__URLENCODE__'])) {
$encode = $params['__URLENCODE__'];
unset($params['__URLENCODE__']);
}
if (isset($params['__SSL__'])) {
unset($params['__SSL__']);
}
$catalog_item_found = false;
$pass_info = $this->getPassInfo($pass);
if ($pass_info) {
if ($pass_info[0] == 'm') {
array_shift($pass_info);
}
$inject_parts = Array (); // url parts for beginning of url
$params['t'] = $t; // make template available for rewrite listeners
$params['pass_template'] = true; // by default we keep given template in resulting url
if (!array_key_exists('pass_category', $params)) {
$params['pass_category'] = false; // by default we don't keep categories in url
}
foreach ($pass_info as $pass_index => $pass_element) {
list ($prefix) = explode('.', $pass_element);
$catalog_item = $this->findModule('Var', $prefix) && $this->getUnitOption($prefix, 'CatalogItem');
if (array_key_exists($prefix, $this->RewriteListeners)) {
// if next prefix is same as current, but with special => exclude current prefix from url
$next_prefix = array_key_exists($pass_index + 1, $pass_info) ? $pass_info[$pass_index + 1] : false;
if ($next_prefix) {
$next_prefix = substr($next_prefix, 0, strlen($prefix) + 1);
if ($prefix . '.' == $next_prefix) {
continue;
}
}
// rewrited url part
$url_part = $this->BuildModuleEnv_NEW($pass_element, $params, $pass_events);
if (is_string($url_part) && $url_part) {
$ret .= $url_part . '/';
if ($catalog_item) {
// pass category later only for catalog items
$catalog_item_found = true;
}
}
elseif (is_array($url_part)) {
// rewrite listener want to insert something at the beginning of url too
if ($url_part[0]) {
$inject_parts[] = $url_part[0];
}
if ($url_part[1]) {
$ret .= $url_part[1] . '/';
}
if ($catalog_item) {
// pass category later only for catalog items
$catalog_item_found = true;
}
} elseif ($url_part === false) {
// rewrite listener decided not to rewrite given $pass_element
$env .= ':' . $this->BuildModuleEnv($pass_element, $params, $pass_events);
}
}
else {
$env .= ':' . $this->BuildModuleEnv($pass_element, $params, $pass_events);
}
}
if ($catalog_item_found || preg_match('/c\.[-\d]*/', implode(',', $pass_info))) {
// "c" prefix is present -> keep category
$params['pass_category'] = true;
}
$params['inject_parts'] = $inject_parts;
$ret = $this->BuildModuleEnv_NEW('m', $params, $pass_events) . '/' . $ret;
$cat_processed = array_key_exists('category_processed', $params) && $params['category_processed'];
// remove tempporary parameters used by listeners
unset($params['t'], $params['inject_parts'], $params['pass_template'], $params['pass_category'], $params['category_processed']);
if ($catalog_item_found || !$cat_processed || !defined('EXP_DIR_URLS')) {
// this catalog item detail page OR there is no category given
$ret = trim($ret, '/') . '.html';
}
else {
// url ends with "/" and not with ".html"
$ret = trim($ret, '/') . '/';
}
if ($env) {
$params[ENV_VAR_NAME] = ltrim($env, ':');
}
}
unset($params['pass'], $params['opener'], $params['m_event']);
if ($force_admin) {
$params['admin'] = 1;
}
if (array_key_exists('escape', $params) && $params['escape']) {
$ret = addslashes($ret);
unset($params['escape']);
}
$ret = str_replace('%2F', '/', urlencode($ret));
$params_str = '';
$join_string = $encode ? '&' : '&amp;';
foreach ($params as $param => $value) {
$params_str .= $join_string . $param . '=' . $value;
}
if ($params_str) {
$ret .= '?' . substr($params_str, strlen($join_string));
}
if ($encode) {
$ret = str_replace('\\', '%5C', $ret);
}
return $ret;
}
function BuildModuleEnv_NEW($prefix_special, &$params, $keep_events = false)
{
list ($prefix) = explode('.', $prefix_special);
$url_parts = Array ();
$listener = $this->RewriteListeners[$prefix];
$ret = $listener[0]->$listener[1](REWRITE_MODE_BUILD, $prefix_special, $params, $url_parts, $keep_events);
return $ret;
}
/**
* Builds env part that corresponds prefix passed
*
* @param string $prefix_special item's prefix & [special]
* @param Array $params url params
* @param bool $pass_events
*/
function BuildModuleEnv($prefix_special, &$params, $pass_events = false)
{
list($prefix) = explode('.', $prefix_special);
$query_vars = $this->getUnitOption($prefix, 'QueryString');
//if pass events is off and event is not implicity passed
if( !$pass_events && !isset($params[$prefix_special.'_event']) ) {
$params[$prefix_special.'_event'] = ''; // remove event from url if requested
//otherwise it will use value from get_var
}
if(!$query_vars) return '';
$tmp_string = Array(0 => $prefix_special);
foreach($query_vars as $index => $var_name)
{
//if value passed in params use it, otherwise use current from application
$var_name = $prefix_special.'_'.$var_name;
$tmp_string[$index] = isset( $params[$var_name] ) ? $params[$var_name] : $this->GetVar($var_name);
if ( isset($params[$var_name]) ) unset( $params[$var_name] );
}
$escaped = array();
foreach ($tmp_string as $tmp_val) {
$escaped[] = str_replace(Array('-',':'), Array('\-','\:'), $tmp_val);
}
$ret = implode('-', $escaped);
if ($this->getUnitOption($prefix, 'PortalStyleEnv') == true)
{
$ret = preg_replace('/^([a-zA-Z]+)-([0-9]+)-(.*)/','\\1\\2-\\3', $ret);
}
return $ret;
}
function BuildEnv($t, $params, $pass='all', $pass_events = false, $env_var = true)
{
$session =& $this->recallObject('Session');
$ssl = isset($params['__SSL__']) ? $params['__SSL__'] : 0;
$sid = $session->NeedQueryString() && !$this->RewriteURLs($ssl) ? $this->GetSID() : '';
// if (getArrayValue($params,'admin') == 1) $sid = $this->GetSID();
$ret = '';
if ($env_var) {
$ret = ENV_VAR_NAME.'=';
}
$ret .= $sid . '-'; // SID-TEMPLATE
$encode = false;
if (isset($params['__URLENCODE__'])) {
$encode = $params['__URLENCODE__'];
unset($params['__URLENCODE__']);
}
if (isset($params['__SSL__'])) {
unset($params['__SSL__']);
}
$env_string = '';
$category_id = isset($params['m_cat_id']) ? $params['m_cat_id'] : $this->GetVar('m_cat_id');
$item_id = false;
$pass_info = $this->getPassInfo($pass);
if ($pass_info) {
if ($pass_info[0] == 'm') array_shift($pass_info);
foreach ($pass_info as $pass_element) {
list($prefix) = explode('.', $pass_element);
$require_rewrite = $this->findModule('Var', $prefix);
if ($require_rewrite) {
$item_id = isset($params[$pass_element.'_id']) ? $params[$pass_element.'_id'] : $this->GetVar($pass_element.'_id');
}
$env_string .= ':'.$this->BuildModuleEnv($pass_element, $params, $pass_events);
}
}
if (strtolower($t) == '__default__') {
// to put category & item templates into cache
$filename = $this->getFilename('c', $category_id);
if (is_numeric($item_id)) {
$mod_rw_helper =& $this->Application->recallObject('ModRewriteHelper');
/* @var $mod_rw_helper kModRewriteHelper */
$t = $mod_rw_helper->GetItemTemplate($category_id, $pass_element); // $pass_element should be the last processed element
// $t = $this->getCache('item_templates', $category_id);
}
elseif ($category_id) {
$t = strtolower( preg_replace('/^Content\//i', '', $this->getCache('category_templates', $category_id)) );
}
else {
$t = 'index';
}
}
$ret .= $t.':'.$this->BuildModuleEnv('m', $params, $pass_events).$env_string;
unset($params['pass'], $params['opener'], $params['m_event']);
if ($this->GetVar('admin') && !isset($params['admin'])) {
$params['admin'] = 1;
if (!array_key_exists('editing_mode', $params)) {
$params['editing_mode'] = EDITING_MODE;
}
}
if (array_key_exists('escape', $params) && $params['escape']) {
$ret = addslashes($ret);
unset($params['escape']);
}
$join_string = $encode ? '&' : '&amp;';
$params_str = '';
foreach ($params as $param => $value)
{
$params_str .= $join_string.$param.'='.$value;
}
$ret .= $params_str;
if ($encode) {
$ret = str_replace('\\', '%5C', $ret);
}
return $ret;
}
function BaseURL($prefix='', $ssl=null)
{
if ($ssl === null) {
return PROTOCOL.SERVER_NAME.(defined('PORT')?':'.PORT : '').rtrim(BASE_PATH, '/').$prefix.'/';
}
else {
if ($ssl) {
$base_url = defined('ADMIN') && ADMIN ? $this->ConfigValue('AdminSSL_URL') : false;
if (!$base_url) {
$base_url = $this->ConfigValue('SSL_URL');
}
return rtrim($base_url, '/').$prefix.'/';
}
else {
return 'http://'.DOMAIN.(defined('PORT')?':'.PORT : '').rtrim( $this->ConfigValue('Site_Path'), '/').$prefix.'/';
}
}
}
function Redirect($t='', $params=null, $prefix='', $index_file=null)
{
$js_redirect = getArrayValue($params, 'js_redirect');
if ($t == '' || $t === true) {
$t = $this->GetVar('t');
}
// pass prefixes and special from previous url
if (array_key_exists('js_redirect', $params)) {
unset($params['js_redirect']);
}
if (!array_key_exists('pass', $params)) {
$params['pass'] = 'all';
}
if ($this->GetVar('ajax') == 'yes' && $t == $this->GetVar('t')) {
// redirects to the same template as current
$params['ajax'] = 'yes';
}
$params['__URLENCODE__'] = 1;
$location = $this->HREF($t, $prefix, $params, $index_file);
$a_location = $location;
$location = "Location: $location";
if ($this->isDebugMode() && constOn('DBG_REDIRECT')) {
$this->Debugger->appendTrace();
echo "<b>Debug output above!!!</b> Proceed to redirect: <a href=\"$a_location\">$a_location</a><br>";
}
else {
if ($js_redirect) {
$this->SetVar('t', 'redirect');
$this->SetVar('redirect_to_js', addslashes($a_location) );
$this->SetVar('redirect_to', $a_location);
return true;
}
else {
if ($this->GetVar('ajax') == 'yes' && $t != $this->GetVar('t')) {
// redirection to other then current template during ajax request
echo '#redirect#'.$a_location;
}
elseif (headers_sent() != '') {
// some output occured -> redirect using javascript
echo '<script type="text/javascript">window.location.href = \''.$a_location.'\';</script>';
}
else {
// no output before -> redirect using HTTP header
// header('HTTP/1.1 302 Found');
header("$location");
}
}
}
ob_end_flush();
// session expiration is called from session initialization,
// that's why $this->Session may be not defined here
$session =& $this->Application->recallObject('Session');
/* @var $session Session */
$this->HandleEvent( new kEvent('adm:OnBeforeShutdown') );
$session->SaveData();
exit;
}
function Phrase($label, $allow_editing = true, $use_admin = false)
{
return $this->Phrases->GetPhrase($label, $allow_editing, $use_admin);
}
/**
* Replace language tags in exclamation marks found in text
*
* @param string $text
* @param bool $force_escape force escaping, not escaping of resulting string
* @return string
* @access public
*/
function ReplaceLanguageTags($text, $force_escape=null)
{
// !!!!!!!!
// if( !is_object($this->Phrases) ) $this->Debugger->appendTrace();
return $this->Phrases->ReplaceLanguageTags($text,$force_escape);
}
/**
* Checks if user is logged in, and creates
* user object if so. User object can be recalled
* later using "u.current" prefix_special. Also you may
* get user id by getting "u.current_id" variable.
*
* @access private
*/
function ValidateLogin()
{
$session =& $this->recallObject('Session');
$user_id = $session->GetField('PortalUserId');
if (!$user_id && $user_id != -1) {
$user_id = -2;
}
$this->SetVar('u.current_id', $user_id);
if (!$this->isAdmin) {
// needed for "profile edit", "registration" forms ON FRONT ONLY
$this->SetVar('u_id', $user_id);
}
$this->StoreVar('user_id', $user_id, $user_id == -2); // storing Guest user_id (-2) is optional
$this->isAdminUser = $this->isAdmin && $this->LoggedIn();
if ($this->GetVar('expired') == 1) {
// this parameter is set only from admin
$user =& $this->recallObject('u.current');
$user->SetError('ValidateLogin', 'session_expired', 'la_text_sess_expired');
}
if (($user_id != -2) && constOn('DBG_REQUREST_LOG') ) {
$http_query =& $this->recallObject('HTTPQuery');
$http_query->writeRequestLog(DBG_REQUREST_LOG);
}
if ($user_id != -2) {
// normal users + root
$this->LoadPersistentVars();
}
}
/**
* Loads current user persistent session data
*
*/
function LoadPersistentVars()
{
$this->Session->LoadPersistentVars();
}
function LoadCache() {
$cache_key = $this->GetVar('t').$this->GetVar('m_theme').$this->GetVar('m_lang').$this->isAdmin;
$query = sprintf("SELECT PhraseList, ConfigVariables FROM %s WHERE Template = %s",
TABLE_PREFIX.'PhraseCache',
$this->Conn->qstr(md5($cache_key)));
$res = $this->Conn->GetRow($query);
if ($res) {
$this->Caches['PhraseList'] = $res['PhraseList'] ? explode(',', $res['PhraseList']) : array();
$config_ids = $res['ConfigVariables'] ? explode(',', $res['ConfigVariables']) : array();
if (isset($this->Caches['ConfigVariables'])) {
$config_ids = array_diff($config_ids, $this->Caches['ConfigVariables']);
}
}
else {
$config_ids = array();
}
$this->Caches['ConfigVariables'] = $config_ids;
$this->ConfigCacheIds = $config_ids;
}
function LoadStructureTemplateMapping()
{
// get template mapping
$sql = 'SELECT Data
FROM ' . TABLE_PREFIX . 'Cache
WHERE VarName = "template_mapping"';
$template_mapping = $this->Conn->GetOne($sql);
if (!$this->isAdmin && $template_mapping) {
// template mappings only for Front-End
$this->structureTemplateMapping = unserialize($template_mapping);
}
}
function UpdateCache()
{
$update = false;
//something changed
$update = $update || $this->Phrases->NeedsCacheUpdate();
$update = $update || (count($this->ConfigCacheIds) && $this->ConfigCacheIds != $this->Caches['ConfigVariables']);
if ($update) {
$cache_key = $this->GetVar('t').$this->GetVar('m_theme').$this->GetVar('m_lang').$this->isAdmin;
$query = sprintf("REPLACE %s (PhraseList, CacheDate, Template, ConfigVariables)
VALUES (%s, %s, %s, %s)",
TABLE_PREFIX.'PhraseCache',
$this->Conn->Qstr(join(',', $this->Phrases->Ids)),
adodb_mktime(),
$this->Conn->Qstr(md5($cache_key)),
$this->Conn->qstr(implode(',', array_unique($this->ConfigCacheIds))));
$this->Conn->Query($query);
}
}
function InitConfig()
{
if (isset($this->Caches['ConfigVariables']) && count($this->Caches['ConfigVariables']) > 0) {
$this->ConfigHash = array_merge($this->ConfigHash, $this->Conn->GetCol(
'SELECT VariableValue, VariableName FROM '.TABLE_PREFIX.'ConfigurationValues
WHERE VariableId IN ('.implode(',', $this->Caches['ConfigVariables']).')', 'VariableName'));
}
}
/**
* Returns configuration option value by name
*
* @param string $name
* @return string
*/
function ConfigValue($name)
{
$res = array_key_exists($name, $this->ConfigHash) ? $this->ConfigHash[$name] : false;
if ($res !== false) {
return $res;
}
if (defined('IS_INSTALL') && IS_INSTALL && !$this->TableFound('ConfigurationValues')) {
return false;
}
$sql = 'SELECT VariableId, VariableValue
FROM '.TABLE_PREFIX.'ConfigurationValues
WHERE VariableName = '.$this->Conn->qstr($name);
$res = $this->Conn->GetRow($sql);
if ($res !== false) {
$this->ConfigHash[$name] = $res['VariableValue'];
$this->ConfigCacheIds[] = $res['VariableId'];
return $res['VariableValue'];
}
return false;
}
function UpdateConfigCache()
{
if ($this->ConfigCacheIds) {
}
}
/**
* Allows to process any type of event
*
* @param kEvent $event
* @access public
* @author Alex
*/
function HandleEvent(&$event, $params=null, $specificParams=null)
{
if ( isset($params) ) {
$event = new kEvent( $params, $specificParams );
}
if (!isset($this->EventManager)) {
$this->EventManager =& $this->recallObject('EventManager');
}
$this->EventManager->HandleEvent($event);
}
/**
* Registers new class in the factory
*
* @param string $real_class Real name of class as in class declaration
* @param string $file Filename in what $real_class is declared
* @param string $pseudo_class Name under this class object will be accessed using getObject method
* @param Array $dependecies List of classes required for this class functioning
* @access public
* @author Alex
*/
function registerClass($real_class, $file, $pseudo_class = null, $dependecies = Array() )
{
$this->Factory->registerClass($real_class, $file, $pseudo_class, $dependecies);
}
/**
* Add $class_name to required classes list for $depended_class class.
* All required class files are included before $depended_class file is included
*
* @param string $depended_class
* @param string $class_name
* @author Alex
*/
function registerDependency($depended_class, $class_name)
{
$this->Factory->registerDependency($depended_class, $class_name);
}
/**
* Registers Hook from subprefix event to master prefix event
*
* @param string $hookto_prefix
* @param string $hookto_special
* @param string $hookto_event
* @param string $mode
* @param string $do_prefix
* @param string $do_special
* @param string $do_event
* @param string $conditional
* @access public
* @todo take care of a lot parameters passed
* @author Kostja
*/
function registerHook($hookto_prefix, $hookto_special, $hookto_event, $mode, $do_prefix, $do_special, $do_event, $conditional)
{
$event_manager =& $this->recallObject('EventManager');
$event_manager->registerHook($hookto_prefix, $hookto_special, $hookto_event, $mode, $do_prefix, $do_special, $do_event, $conditional);
}
/**
* Allows one TagProcessor tag act as other TagProcessor tag
*
* @param Array $tag_info
* @author Kostja
*/
function registerAggregateTag($tag_info)
{
$aggregator =& $this->recallObject('TagsAggregator', 'kArray');
$aggregator->SetArrayValue($tag_info['AggregateTo'], $tag_info['AggregatedTagName'], Array($tag_info['LocalPrefix'], $tag_info['LocalTagName'], getArrayValue($tag_info, 'LocalSpecial')));
}
/**
* Returns object using params specified,
* creates it if is required
*
* @param string $name
* @param string $pseudo_class
* @param Array $event_params
* @return Object
* @author Alex
*/
function &recallObject($name,$pseudo_class=null,$event_params=Array())
{
$result =& $this->Factory->getObject($name, $pseudo_class, $event_params);
return $result;
}
/**
* Returns object using Variable number of params,
* all params starting with 4th are passed to object consturctor
*
* @param string $name
* @param string $pseudo_class
* @param Array $event_params
* @return Object
* @author Alex
*/
function &recallObjectP($name,$pseudo_class=null,$event_params=Array())
{
$func_args = func_get_args();
$result =& ref_call_user_func_array( Array(&$this->Factory, 'getObjectP'), $func_args );
return $result;
}
/**
* Returns tag processor for prefix specified
*
* @param string $prefix
* @return kDBTagProcessor
*/
function &recallTagProcessor($prefix)
{
$this->InitParser(); // because kDBTagProcesor is in NParser dependencies
$result =& $this->recallObject($prefix . '_TagProcessor');
return $result;
}
/**
* Checks if object with prefix passes was already created in factory
*
* @param string $name object presudo_class, prefix
* @return bool
* @author Kostja
*/
function hasObject($name)
{
return isset($this->Factory->Storage[$name]);
}
/**
* Removes object from storage by given name
*
* @param string $name Object's name in the Storage
* @author Kostja
*/
function removeObject($name)
{
$this->Factory->DestroyObject($name);
}
/**
* Get's real class name for pseudo class,
* includes class file and creates class
* instance
*
* @param string $pseudo_class
* @return Object
* @access public
* @author Alex
*/
function &makeClass($pseudo_class)
{
$func_args = func_get_args();
$result =& ref_call_user_func_array( Array(&$this->Factory, 'makeClass'), $func_args);
return $result;
}
/**
* Checks if application is in debug mode
*
* @param bool $check_debugger check if kApplication debugger is initialized too, not only for defined DEBUG_MODE constant
* @return bool
* @author Alex
* @access public
*/
function isDebugMode($check_debugger = true)
{
$debug_mode = defined('DEBUG_MODE') && DEBUG_MODE;
if ($check_debugger) {
$debug_mode = $debug_mode && is_object($this->Debugger);
}
return $debug_mode;
}
/**
* Apply url rewriting used by mod_rewrite or not
*
* @param bool $ssl Force ssl link to be build
* @return bool
*/
function RewriteURLs($ssl = false)
{
// case #1,#4:
// we want to create https link from http mode
// we want to create https link from https mode
// conditions: ($ssl || PROTOCOL == 'https://') && $this->ConfigValue('UseModRewriteWithSSL')
// case #2,#3:
// we want to create http link from https mode
// we want to create http link from http mode
// conditions: !$ssl && (PROTOCOL == 'https://' || PROTOCOL == 'http://')
$allow_rewriting =
(!$ssl && (PROTOCOL == 'https://' || PROTOCOL == 'http://')) // always allow mod_rewrite for http
|| // or allow rewriting for redirect TO httpS or when already in httpS
(($ssl || PROTOCOL == 'https://') && $this->ConfigValue('UseModRewriteWithSSL')); // but only if it's allowed in config!
return constOn('MOD_REWRITE') && $allow_rewriting;
}
/**
* Reads unit (specified by $prefix)
* option specified by $option
*
* @param string $prefix
* @param string $option
* @param mixed $default
* @return string
* @access public
* @author Alex
*/
function getUnitOption($prefix, $option, $default = false)
{
/*if (!isset($this->UnitConfigReader)) {
$this->UnitConfigReader =& $this->recallObject('kUnitConfigReader');
}*/
return $this->UnitConfigReader->getUnitOption($prefix, $option, $default);
}
/**
* Set's new unit option value
*
* @param string $prefix
* @param string $name
* @param string $value
* @author Alex
* @access public
*/
function setUnitOption($prefix, $option, $value)
{
// $unit_config_reader =& $this->recallObject('kUnitConfigReader');
return $this->UnitConfigReader->setUnitOption($prefix,$option,$value);
}
/**
* Read all unit with $prefix options
*
* @param string $prefix
* @return Array
* @access public
* @author Alex
*/
function getUnitOptions($prefix)
{
// $unit_config_reader =& $this->recallObject('kUnitConfigReader');
return $this->UnitConfigReader->getUnitOptions($prefix);
}
/**
* Returns true if config exists and is allowed for reading
*
* @param string $prefix
* @return bool
*/
function prefixRegistred($prefix)
{
/*if (!isset($this->UnitConfigReader)) {
$this->UnitConfigReader =& $this->recallObject('kUnitConfigReader');
}*/
return $this->UnitConfigReader->prefixRegistred($prefix);
}
/**
* Splits any mixing of prefix and
* special into correct ones
*
* @param string $prefix_special
* @return Array
* @access public
* @author Alex
*/
function processPrefix($prefix_special)
{
return $this->Factory->processPrefix($prefix_special);
}
/**
* Set's new event for $prefix_special
* passed
*
* @param string $prefix_special
* @param string $event_name
* @access public
*/
function setEvent($prefix_special,$event_name)
{
$event_manager =& $this->recallObject('EventManager');
$event_manager->setEvent($prefix_special,$event_name);
}
/**
* SQL Error Handler
*
* @param int $code
* @param string $msg
* @param string $sql
* @return bool
* @access private
* @author Alex
*/
function handleSQLError($code, $msg, $sql)
{
if ( isset($this->Debugger) )
{
$errorLevel = constOn('DBG_SQL_FAILURE') && !defined('IS_INSTALL') ? E_USER_ERROR : E_USER_WARNING;
$this->Debugger->appendTrace();
$error_msg = '<span class="debug_error">'.$msg.' ('.$code.')</span><br><a href="javascript:$Debugger.SetClipboard(\''.htmlspecialchars($sql).'\');"><b>SQL</b></a>: '.$this->Debugger->formatSQL($sql);
$long_id = $this->Debugger->mapLongError($error_msg);
trigger_error( mb_substr($msg.' ('.$code.') ['.$sql.']',0,1000).' #'.$long_id, $errorLevel);
return true;
}
else
{
//$errorLevel = constOn('IS_INSTALL') ? E_USER_WARNING : E_USER_ERROR;
$errorLevel = E_USER_WARNING;
trigger_error('<b>SQL Error</b> in sql: '.$sql.', code <b>'.$code.'</b> ('.$msg.')', $errorLevel);
/*echo '<b>xProcessing SQL</b>: '.$sql.'<br>';
echo '<b>Error ('.$code.'):</b> '.$msg.'<br>';*/
return $errorLevel == E_USER_ERROR ? false : true;
}
}
/**
* Default error handler
*
* @param int $errno
* @param string $errstr
* @param string $errfile
* @param int $errline
* @param Array $errcontext
*/
function handleError($errno, $errstr, $errfile = '', $errline = '', $errcontext = '')
{
if (defined('SILENT_LOG') && SILENT_LOG) {
if ( !(defined('DBG_IGNORE_STRICT_ERRORS') && DBG_IGNORE_STRICT_ERRORS && defined('E_STRICT') && ($errno == E_STRICT)) ) {
$fp = fopen(FULL_PATH.'/silent_log.txt','a');
$time = adodb_date('d/m/Y H:i:s');
fwrite($fp, '['.$time.'] #'.$errno.': '.strip_tags($errstr).' in ['.$errfile.'] on line '.$errline."\n");
fclose($fp);
}
}
$debug_mode = defined('DEBUG_MODE') && DEBUG_MODE;
$skip_reporting = defined('DBG_SKIP_REPORTING') && DBG_SKIP_REPORTING;
if (!$this->errorHandlers || ($debug_mode && $skip_reporting)) {
// when debugger absent OR it's present, but we actually can't see it's error report (e.g. during ajax request)
$ignore_fatal_errors = defined('DBG_IGNORE_FATAL_ERRORS') && DBG_IGNORE_FATAL_ERRORS;
if (($errno == E_USER_ERROR) && !$ignore_fatal_errors) {
echo (' <div style="background-color: #FEFFBF; margin: auto; padding: 10px; border: 2px solid red; text-align: center">
<strong>Fatal Error: </strong>'."$errstr in $errfile on line $errline".'
</div>');
exit;
}
if (!$this->errorHandlers) {
return true;
}
}
$res = false;
$i = 0; // while (not foreach) because it is array of references in some cases
$eh_count = count($this->errorHandlers);
while ($i < $eh_count) {
if ( is_array($this->errorHandlers[$i]) ) {
$object =& $this->errorHandlers[$i][0];
$method = $this->errorHandlers[$i][1];
$res = $object->$method($errno, $errstr, $errfile, $errline, $errcontext);
}
else {
$function = $this->errorHandlers[$i];
$res = $function($errno, $errstr, $errfile, $errline, $errcontext);
}
$i++;
}
return $res;
}
/**
* Returns & blocks next ResourceId available in system
*
* @return int
* @access public
* @author Alex
*/
function NextResourceId()
{
$table_name = TABLE_PREFIX.'IdGenerator';
$this->Conn->Query('LOCK TABLES '.$table_name.' WRITE');
$this->Conn->Query('UPDATE '.$table_name.' SET lastid = lastid + 1');
$id = $this->Conn->GetOne('SELECT lastid FROM '.$table_name);
if($id === false)
{
$this->Conn->Query('INSERT INTO '.$table_name.' (lastid) VALUES (2)');
$id = 2;
}
$this->Conn->Query('UNLOCK TABLES');
return $id - 1;
}
/**
* Returns genealogical main prefix for subtable prefix passes
* OR prefix, that has been found in REQUEST and some how is parent of passed subtable prefix
*
* @param string $current_prefix
* @param string $real_top if set to true will return real topmost prefix, regardless of its id is passed or not
* @return string
* @access public
* @author Kostja / Alex
*/
function GetTopmostPrefix($current_prefix, $real_top = false)
{
// 1. get genealogical tree of $current_prefix
$prefixes = Array ($current_prefix);
while ( $parent_prefix = $this->getUnitOption($current_prefix, 'ParentPrefix') ) {
if (!$this->prefixRegistred($parent_prefix)) {
// stop searching, when parent prefix is not registered
break;
}
$current_prefix = $parent_prefix;
array_unshift($prefixes, $current_prefix);
}
if ($real_top) {
return $current_prefix;
}
// 2. find what if parent is passed
$passed = explode(',', $this->GetVar('all_passed'));
foreach ($prefixes as $a_prefix) {
if (in_array($a_prefix, $passed)) {
return $a_prefix;
}
}
return $current_prefix;
}
/**
* Triggers email event of type Admin
*
* @param string $email_event_name
* @param int $to_user_id
* @param array $send_params associative array of direct send params, possible keys: to_email, to_name, from_email, from_name, message, message_text
* @return unknown
*/
function &EmailEventAdmin($email_event_name, $to_user_id = null, $send_params = false)
{
$event =& $this->EmailEvent($email_event_name, 1, $to_user_id, $send_params);
return $event;
}
/**
* Triggers email event of type User
*
* @param string $email_event_name
* @param int $to_user_id
* @param array $send_params associative array of direct send params, possible keys: to_email, to_name, from_email, from_name, message, message_text
* @return unknown
*/
function &EmailEventUser($email_event_name, $to_user_id = null, $send_params = false)
{
$event =& $this->EmailEvent($email_event_name, 0, $to_user_id, $send_params);
return $event;
}
/**
* Triggers general email event
*
* @param string $email_event_name
* @param int $email_event_type ( 0 for User, 1 for Admin)
* @param int $to_user_id
* @param array $send_params associative array of direct send params,
* possible keys: to_email, to_name, from_email, from_name, message, message_text
* @return unknown
*/
function &EmailEvent($email_event_name, $email_event_type, $to_user_id = -1, $send_params = false)
{
$params = array(
'EmailEventName' => $email_event_name,
'EmailEventToUserId' => $to_user_id,
'EmailEventType' => $email_event_type,
);
if ($send_params) {
$params['DirectSendParams'] = $send_params;
}
$event_str = isset($send_params['use_special']) ? 'emailevents.'.$send_params['use_special'].':OnEmailEvent' : 'emailevents:OnEmailEvent';
$this->HandleEvent($event, $event_str, $params);
return $event;
}
/**
* Allows to check if user in this session is logged in or not
*
* @return bool
*/
function LoggedIn()
{
// no session during expiration process
return is_null($this->Session) ? false : $this->Session->LoggedIn();
}
/**
* Check current user permissions based on it's group permissions in specified category
*
* @param string $name permission name
* @param int $cat_id category id, current used if not specified
* @param int $type permission type {1 - system, 0 - per category}
* @return int
*/
function CheckPermission($name, $type = 1, $cat_id = null)
{
$perm_helper =& $this->recallObject('PermissionsHelper');
return $perm_helper->CheckPermission($name, $type, $cat_id);
}
/**
* Set's any field of current visit
*
* @param string $field
* @param mixed $value
*/
function setVisitField($field, $value)
{
if ($this->isAdmin || !$this->ConfigValue('UseVisitorTracking')) {
// admin logins are not registred in visits list
return ;
}
$visit =& $this->recallObject('visits', null, Array ('raise_warnings' => 0));
/* @var $visit kDBItem */
if ($visit->isLoaded()) {
$visit->SetDBField($field, $value);
$visit->Update();
}
}
/**
* Allows to check if in-portal is installed
*
* @return bool
*/
function isInstalled()
{
return $this->InitDone && (count($this->ModuleInfo) > 0);
}
/**
* Allows to determine if module is installed & enabled
*
* @param string $module_name
* @return bool
*/
function isModuleEnabled($module_name)
{
return $this->findModule('Name', $module_name) !== false;
}
function reportError($class, $method)
{
$this->Debugger->appendTrace();
trigger_error('depricated method <b>'.$class.'->'.$method.'(...)</b>', E_USER_ERROR);
}
/**
* Returns Window ID of passed prefix main prefix (in edit mode)
*
* @param string $prefix
* @return mixed
*/
function GetTopmostWid($prefix)
{
$top_prefix = $this->GetTopmostPrefix($prefix);
$mode = $this->GetVar($top_prefix.'_mode');
return $mode != '' ? substr($mode, 1) : '';
}
/**
* Get temp table name
*
* @param string $table
* @param mixed $wid
* @return string
*/
function GetTempName($table, $wid = '')
{
if (preg_match('/prefix:(.*)/', $wid, $regs)) {
$wid = $this->GetTopmostWid($regs[1]);
}
return TABLE_PREFIX.'ses_'.$this->GetSID().($wid ? '_'.$wid : '').'_edit_'.$table;
}
function GetTempTablePrefix($wid = '')
{
if (preg_match('/prefix:(.*)/', $wid, $regs)) {
$wid = $this->GetTopmostWid($regs[1]);
}
return TABLE_PREFIX.'ses_'.$this->GetSID().($wid ? '_'.$wid : '').'_edit_';
}
function IsTempTable($table)
{
return preg_match('/'.TABLE_PREFIX.'ses_'.$this->GetSID().'(_[\d]+){0,1}_edit_(.*)/',$table);
}
/**
* Checks, that given prefix is in temp mode
*
* @param string $prefix
* @return bool
*/
function IsTempMode($prefix, $special = '')
{
$top_prefix = $this->Application->GetTopmostPrefix($prefix);
$var_names = Array (
$top_prefix,
rtrim($top_prefix . '_' . $special, '_'), // from post
rtrim($top_prefix . '.' . $special, '.'), // assembled locally
);
$var_names = array_unique($var_names);
$temp_mode = false;
foreach ($var_names as $var_name) {
$value = $this->Application->GetVar($var_name . '_mode');
if ($value && (substr($value, 0, 1) == 't')) {
$temp_mode = true;
break;
}
}
return $temp_mode;
}
/**
* Return live table name based on temp table name
*
* @param string $temp_table
* @return string
*/
function GetLiveName($temp_table)
{
if( preg_match('/'.TABLE_PREFIX.'ses_'.$this->GetSID().'(_[\d]+){0,1}_edit_(.*)/',$temp_table, $rets) )
{
// cut wid from table end if any
return $rets[2];
}
else
{
return $temp_table;
}
}
function CheckProcessors($processors)
{
foreach ($processors as $a_processor)
{
if (!isset($this->CachedProcessors[$a_processor])) {
$this->CachedProcessors[$a_processor] =& $this->recallObject($a_processor.'_TagProcessor');
}
}
}
function TimeZoneAdjustment($time_zone = null)
{
if ($time_zone == 'GMT') {
return (-1) * adodb_date('Z');
}
$target_zone = isset($time_zone) ? $time_zone : $this->ConfigValue('Config_Site_Time');
return 3600 * ($target_zone - $this->ConfigValue('Config_Server_Time'));
}
function ApplicationDie($message = '')
{
$message = ob_get_clean().$message;
if ($this->isDebugMode()) {
$message .= $this->Debugger->printReport(true);
}
echo $this->UseOutputCompression() ? gzencode($message, DBG_COMPRESSION_LEVEL) : $message;
exit;
}
/* moved from MyApplication */
function getUserGroups($user_id)
{
switch ($user_id) {
case -1:
$user_groups = $this->ConfigValue('User_LoggedInGroup');
break;
case -2:
$user_groups = $this->ConfigValue('User_LoggedInGroup') . ',' . $this->ConfigValue('User_GuestGroup');
break;
default:
$sql = 'SELECT GroupId
FROM ' . TABLE_PREFIX . 'UserGroup
WHERE PortalUserId = ' . (int)$user_id;
$res = $this->Conn->GetCol($sql);
$user_groups = Array( $this->ConfigValue('User_LoggedInGroup') );
if ($res) {
$user_groups = array_merge($user_groups, $res);
}
$user_groups = implode(',', $user_groups);
}
return $user_groups;
}
/**
* Allows to detect if page is browsed by spider (293 agents supported)
*
* @return bool
*/
function IsSpider()
{
static $is_spider = null;
if (!isset($is_spider)) {
$user_agent = trim($_SERVER['HTTP_USER_AGENT']);
$robots = file(FULL_PATH.'/core/robots_list.txt');
foreach ($robots as $robot_info) {
$robot_info = explode("\t", $robot_info, 3);
if ($user_agent == trim($robot_info[2])) {
$is_spider = true;
break;
}
}
}
return $is_spider;
}
/**
* Allows to detect table's presense in database
*
* @param string $table_name
* @return bool
*/
function TableFound($table_name)
{
return $this->Conn->TableFound($table_name);
}
/**
* Returns counter value
*
* @param string $name counter name
* @param Array $params counter parameters
* @param string $query_name specify query name directly (don't generate from parmeters)
* @param bool $multiple_results
* @return mixed
*/
function getCounter($name, $params = Array (), $query_name = null, $multiple_results = false)
{
$count_helper =& $this->Application->recallObject('CountHelper');
/* @var $count_helper kCountHelper */
return $count_helper->getCounter($name, $params, $query_name, $multiple_results);
}
/**
* Resets counter, whitch are affected by one of specified tables
*
* @param string $tables comma separated tables list used in counting sqls
*/
function resetCounters($tables)
{
if (constOn('IS_INSTALL')) {
return ;
}
$count_helper =& $this->Application->recallObject('CountHelper');
/* @var $count_helper kCountHelper */
return $count_helper->resetCounters($tables);
}
/**
* Sends XML header + optionally displays xml heading
*
* @param string $xml_version
* @return string
* @author Alex
*/
function XMLHeader($xml_version = false)
{
$lang =& $this->recallObject('lang.current');
header('Content-type: text/xml; charset='.$lang->GetDBField('Charset'));
return $xml_version ? '<?xml version="'.$xml_version.'" encoding="'.$lang->GetDBField('Charset').'"?>' : '';
}
/**
* Returns category tree
*
* @param int $category_id
* @return Array
*/
function getTreeIndex($category_id)
{
$category_template = $this->getFilename('c', $category_id); // to rebuild "category_tree" cache
$tree_index = $this->getCache('category_tree', $category_id);
if ($tree_index) {
$ret = Array ();
list ($ret['TreeLeft'], $ret['TreeRight']) = explode(';', $tree_index);
return $ret;
}
return false;
}
}
\ No newline at end of file
Index: branches/5.0.x/core/units/categories/categories_tag_processor.php
===================================================================
--- branches/5.0.x/core/units/categories/categories_tag_processor.php (revision 12952)
+++ branches/5.0.x/core/units/categories/categories_tag_processor.php (revision 12953)
@@ -1,1898 +1,1898 @@
<?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.
*/
class CategoriesTagProcessor extends kDBTagProcessor {
function SubCatCount($params)
{
$object =& $this->getObject($params);
if (isset($params['today']) && $params['today']) {
$sql = 'SELECT COUNT(*)
FROM '.$object->TableName.'
WHERE (ParentPath LIKE "'.$object->GetDBField('ParentPath').'%") AND (CreatedOn > '.(adodb_mktime() - 86400).')';
return $this->Conn->GetOne($sql) - 1;
}
return $object->GetDBField('CachedDescendantCatsQty');
}
/**
* Returns category count in system
*
* @param Array $params
* @return int
*/
function CategoryCount($params)
{
$count_helper =& $this->Application->recallObject('CountHelper');
/* @var $count_helper kCountHelper */
$today_only = isset($params['today']) && $params['today'];
return $count_helper->CategoryCount($today_only);
}
function IsNew($params)
{
$object =& $this->getObject($params);
return $object->GetDBField('IsNew') ? 1 : 0;
}
function IsPick($params)
{
return $this->IsEditorsPick($params);
}
/**
* Returns item's editors pick status (using not formatted value)
*
* @param Array $params
* @return bool
*/
function IsEditorsPick($params)
{
$object =& $this->getObject($params);
return $object->GetDBField('EditorsPick') == 1;
}
function ItemIcon($params)
{
$grids = $this->Application->getUnitOption($this->Prefix, 'Grids');
$grid = $grids[ $params['grid'] ];
if (!array_key_exists('Icons', $grid)) {
return '';
}
$icons = $grid['Icons'];
if (array_key_exists('name', $params)) {
$icon_name = $params['name'];
return array_key_exists($icon_name, $icons) ? $icons[$icon_name] : '';
}
$object =& $this->getObject($params);
/* @var $object kDBList */
if ($object->GetDBField('CreatedBySystem')) {
if (!$object->GetDBField('IsMenu')) {
return 'icon16_section_menuhidden_system.png';
}
return 'icon16_section_system.png';
}
$status = $object->GetDBField('Status');
if ($status == STATUS_DISABLED) {
return 'icon16_section_disabled.png';
}
if (!$object->GetDBField('IsMenu')) {
return 'icon16_section_menuhidden.png';
}
if ($status == STATUS_PENDING) {
return 'icon16_section_pending.png';
}
if ($object->GetDBField('IsNew')) {
return 'icon16_section_new.png';
}
return 'icon16_section.png';
}
function ItemCount($params)
{
$object =& $this->getObject($params);
$ci_table = $this->Application->getUnitOption('l-ci', 'TableName');
$sql = 'SELECT COUNT(*)
FROM ' . $object->TableName . ' c
LEFT JOIN ' . $ci_table . ' ci ON c.CategoryId = ci.CategoryId
WHERE (c.TreeLeft BETWEEN ' . $object->GetDBField('TreeLeft') . ' AND ' . $object->GetDBField('TreeRight') . ') AND NOT (ci.CategoryId IS NULL)';
return $this->Conn->GetOne($sql);
}
function ListCategories($params)
{
return $this->PrintList2($params);
}
function RootCategoryName($params)
{
return $this->Application->ProcessParsedTag('m', 'RootCategoryName', $params);
}
function CheckModuleRoot($params)
{
$module_name = getArrayValue($params, 'module') ? $params['module'] : 'In-Commerce';
$module_root_cat = $this->Application->findModule('Name', $module_name, 'RootCat');
$additional_cats = $this->SelectParam($params, 'add_cats');
if ($additional_cats) {
$additional_cats = explode(',', $additional_cats);
}
else {
$additional_cats = array();
}
if ($this->Application->GetVar('m_cat_id') == $module_root_cat || in_array($this->Application->GetVar('m_cat_id'), $additional_cats)) {
$home_template = getArrayValue($params, 'home_template');
if (!$home_template) return;
$this->Application->Redirect($home_template, Array('pass'=>'all'));
};
}
function CategoryPath($params)
{
$category_helper =& $this->Application->recallObject('CategoryHelper');
/* @var $category_helper CategoryHelper */
return $category_helper->NavigationBar($params);
}
/**
* Shows category path to specified category
*
* @param Array $params
* @return string
*/
function FieldCategoryPath($params)
{
$object =& $this->getObject();
/* @var $object kDBItem */
$field = $this->SelectParam($params, 'name,field');
$category_id = $object->GetDBField($field);
if ($category_id) {
$params['cat_id'] = $category_id;
return $this->CategoryPath($params);
}
return '';
}
function CurrentCategoryName($params)
{
$cat_object =& $this->Application->recallObject($this->getPrefixSpecial(), $this->Prefix.'_List');
$sql = 'SELECT '.$this->getTitleField().'
FROM '.$cat_object->TableName.'
WHERE CategoryId = '.(int)$this->Application->GetVar('m_cat_id');
return $this->Conn->GetOne($sql);
}
/**
* Returns current category name
*
* @param Array $params
* @return string
* @todo Find where it's used
*/
function CurrentCategory($params)
{
return $this->CurrentCategoryName($params);
}
function getTitleField()
{
$ml_formatter =& $this->Application->recallObject('kMultiLanguage');
return $ml_formatter->LangFieldName('Name');
}
/**
* Returns symlinked category for given category
*
* @param $category_id
*/
function getCategorySymLink($category_id)
{
static $cache = null;
if (!$category_id) {
// don't bother to get symlink for "Home" category
return $category_id;
}
if (!isset($cache)) {
$id_field = $this->Application->getUnitOption($this->Prefix, 'IDField');
$table_name = $this->Application->getUnitOption($this->Prefix, 'TableName');
// get symlinked categories, that are not yet deleted
$sql = 'SELECT c1.SymLinkCategoryId, c1.' . $id_field . '
FROM ' . $table_name . ' c1
JOIN ' . $table_name . ' c2 ON c1.SymLinkCategoryId = c2.' . $id_field;
$cache = $this->Conn->GetCol($sql, $id_field);
}
return array_key_exists($category_id, $cache) ? $cache[$category_id] : $category_id;
}
function CategoryLink($params)
{
$category_id = getArrayValue($params, 'cat_id');
if ($category_id === false) {
$category_id = $this->Application->GetVar($this->getPrefixSpecial() . '_id');
}
if ("$category_id" == 'Root') {
$category_id = $this->Application->findModule('Name', $params['module'], 'RootCat');
}
elseif ("$category_id" == 'current') {
$category_id = $this->Application->GetVar('m_cat_id');
}
$category_id = $this->getCategorySymLink( (int)$category_id );
unset($params['cat_id'], $params['module']);
$new_params = Array ('pass' => 'm', 'm_cat_id' => $category_id, 'pass_category' => 1);
$params = array_merge_recursive2($params, $new_params);
return $this->Application->ProcessParsedTag('m', 't', $params);
}
function CategoryList($params)
{
//$object =& $this->Application->recallObject( $this->getPrefixSpecial() , $this->Prefix.'_List', $params );
$object =& $this->GetList($params);
if ($object->RecordsCount == 0)
{
if (isset($params['block_no_cats'])) {
$params['name'] = $params['block_no_cats'];
return $this->Application->ParseBlock($params);
}
else {
return '';
}
}
if (isset($params['block'])) {
return $this->PrintList($params);
}
else {
$params['block'] = $params['block_main'];
if (isset($params['block_row_start'])) {
$params['row_start_block'] = $params['block_row_start'];
}
if (isset($params['block_row_end'])) {
$params['row_end_block'] = $params['block_row_end'];
}
return $this->PrintList2($params);
}
}
function Meta($params)
{
$object =& $this->Application->recallObject($this->Prefix); // .'.-item'
/* @var $object CategoriesItem */
$meta_type = $params['name'];
if ($object->isLoaded()) {
// 1. get module prefix by current category
$category_helper =& $this->Application->recallObject('CategoryHelper');
/* @var $category_helper CategoryHelper */
$category_path = explode('|', substr($object->GetDBField('ParentPath'), 1, -1));
$module_info = $category_helper->getCategoryModule($params, $category_path);
// In-Edit & Proj-CMS module prefixes doesn't have custom field with item template
if ($module_info && $module_info['Var'] != 'adm' && $module_info['Var'] != 'st') {
// 2. get item template by current category & module prefix
$mod_rewrite_helper = $this->Application->recallObject('ModRewriteHelper');
/* @var $mod_rewrite_helper kModRewriteHelper */
$category_params = Array (
'CategoryId' => $object->GetID(),
'ParentPath' => $object->GetDBField('ParentPath'),
);
$item_template = $mod_rewrite_helper->GetItemTemplate($category_params, $module_info['Var']);
if ($this->Application->GetVar('t') == $item_template) {
// we are located on item's details page
$item =& $this->Application->recallObject($module_info['Var']);
/* @var $item kCatDBItem */
// 3. get item's meta data
$value = $item->GetField('Meta'.$meta_type);
if ($value) {
return $value;
}
}
// 4. get category meta data
$value = $object->GetField('Meta'.$meta_type);
if ($value) {
return $value;
}
}
}
// 5. get default meta data
switch ($meta_type) {
case 'Description':
$config_name = 'Category_MetaDesc';
break;
case 'Keywords':
$config_name = 'Category_MetaKey';
break;
}
return $this->Application->ConfigValue($config_name);
}
function BuildListSpecial($params)
{
if (($this->Special != '') && !is_numeric($this->Special)) {
// When recursive category list is printed (like in sitemap), then special
// should be generated even if it's already present. Without it list on this
// level will erase list on previous level, because it will be stored in same object.
return $this->Special;
}
if ( isset($params['parent_cat_id']) ) {
$parent_cat_id = $params['parent_cat_id'];
}
else {
$parent_cat_id = $this->Application->GetVar($this->Prefix.'_id');
if (!$parent_cat_id) {
$parent_cat_id = $this->Application->GetVar('m_cat_id');
}
if (!$parent_cat_id) {
$parent_cat_id = 0;
}
}
$list_unique_key = $this->getUniqueListKey($params);
// check for "admin" variable, because we are parsing front-end template from admin when using template editor feature
if ($this->Application->GetVar('admin') || !$this->Application->isAdmin) {
// add parent category to special, when on Front-End,
// because there can be many category lists on same page
$list_unique_key .= $parent_cat_id;
}
if ($list_unique_key == '') {
return parent::BuildListSpecial($params);
}
return crc32($list_unique_key);
}
function IsCurrent($params)
{
$object =& $this->getObject($params);
if ($object->GetID() == $this->Application->GetVar('m_cat_id')) {
return true;
}
else {
return false;
}
}
/**
* Substitutes category in last template base on current category
* This is required becasue when you navigate catalog using AJAX, last_template is not updated
* but when you open item edit from catalog last_template is used to build opener_stack
* So, if we don't substitute m_cat_id in last_template, after saving item we'll get redirected
* to the first category we've opened, not the one we navigated to using AJAX
*
* @param Array $params
*/
function UpdateLastTemplate($params)
{
$category_id = $this->Application->GetVar('m_cat_id');
$wid = $this->Application->GetVar('m_wid');
list($index_file, $env) = explode('|', $this->Application->RecallVar(rtrim('last_template_'.$wid, '_')), 2);
$vars_backup = Array ();
$vars = $this->Application->HttpQuery->processQueryString( str_replace('%5C', '\\', $env) );
foreach ($vars as $var_name => $var_value) {
$vars_backup[$var_name] = $this->Application->GetVar($var_name);
$this->Application->SetVar($var_name, $var_value);
}
// update required fields
$this->Application->SetVar('m_cat_id', $category_id);
$this->Application->Session->SaveLastTemplate($params['template']);
foreach ($vars_backup as $var_name => $var_value) {
$this->Application->SetVar($var_name, $var_value);
}
}
function GetParentCategory($params)
{
$parent_id = 0;
$id_field = $this->Application->getUnitOption($this->Prefix, 'IDField');
$table = $this->Application->getUnitOption($this->Prefix,'TableName');
$cat_id = $this->Application->GetVar('m_cat_id');
if ($cat_id > 0) {
$sql = 'SELECT ParentId
FROM '.$table.'
WHERE '.$id_field.' = '.$cat_id;
$parent_id = $this->Conn->GetOne($sql);
}
return $parent_id;
}
function InitCacheUpdater($params)
{
safeDefine('CACHE_PERM_CHUNK_SIZE', 30);
$continue = $this->Application->GetVar('continue');
$total_cats = (int) $this->Conn->GetOne('SELECT COUNT(*) FROM '.TABLE_PREFIX.'Category');
if ($continue === false && $total_cats > CACHE_PERM_CHUNK_SIZE) {
// first step, if category count > CACHE_PERM_CHUNK_SIZE, then ask for cache update
return true;
}
if ($continue === false) {
// if we don't have to ask, then assume user selected "Yes" in permcache update dialog
$continue = 1;
}
$updater =& $this->Application->recallObject('kPermCacheUpdater', null, Array('continue' => $continue));
/* @var $updater kPermCacheUpdater */
if ($continue === '0') { // No in dialog
$updater->clearData();
$this->Application->Redirect($params['destination_template']);
}
$ret = false; // don't ask for update
if ($continue == 1) { // Initial run
$updater->setData();
}
if ($continue == 2) { // Continuing
// called from AJAX request => returns percent
$needs_more = true;
while ($needs_more && $updater->iteration <= CACHE_PERM_CHUNK_SIZE) {
// until proceeeded in this step category count exceeds category per step limit
$needs_more = $updater->DoTheJob();
}
if ($needs_more) {
// still some categories are left for next step
$updater->setData();
}
else {
// all done -> redirect
$updater->SaveData();
$this->Application->RemoveVar('PermCache_UpdateRequired');
$this->Application->Redirect($params['destination_template']);
}
$ret = $updater->getDonePercent();
}
return $ret;
}
/**
* Parses warning block, but with style="display: none;". Used during permissions saving from AJAX
*
* @param Array $params
* @return string
*/
function SaveWarning($params)
{
if ($this->Prefix == 'st') {
// don't use this method for other prefixes then Category, that use this tag processor
return parent::SaveWarning($params);
}
$main_prefix = getArrayValue($params, 'main_prefix');
if ($main_prefix && $main_prefix != '$main_prefix') {
$top_prefix = $main_prefix;
}
else {
$top_prefix = $this->Application->GetTopmostPrefix($this->Prefix);
}
$temp_tables = substr($this->Application->GetVar($top_prefix.'_mode'), 0, 1) == 't';
$modified = $this->Application->RecallVar($top_prefix.'_modified');
if (!$temp_tables) {
$this->Application->RemoveVar($top_prefix.'_modified');
return '';
}
$block_name = $this->SelectParam($params, 'render_as,name');
if ($block_name) {
$block_params = $this->prepareTagParams($params);
$block_params['name'] = $block_name;
$block_params['edit_mode'] = $temp_tables ? 1 : 0;
$block_params['display'] = $temp_tables && $modified ? 1 : 0;
return $this->Application->ParseBlock($block_params);
}
else {
return $temp_tables && $modified ? 1 : 0;
}
return ;
}
/**
* Allows to detect if this prefix has something in clipboard
*
* @param Array $params
* @return bool
*/
function HasClipboard($params)
{
$clipboard = $this->Application->RecallVar('clipboard');
if ($clipboard) {
$clipboard = unserialize($clipboard);
foreach ($clipboard as $prefix => $clipboard_data) {
foreach ($clipboard_data as $mode => $ids) {
if (count($ids)) return 1;
}
}
}
return 0;
}
/**
* Allows to detect if root category being edited
*
* @param Array $params
*/
function IsRootCategory($params)
{
$object =& $this->getObject($params);
return $object->IsRoot();
}
/**
* Returns home category id
*
* @param Array $params
* @return int
*/
function HomeCategory($params)
{
static $root_category = null;
if (!isset($root_category)) {
$root_category = $this->Application->findModule('Name', 'Core', 'RootCat');
}
return $root_category;
}
/**
* Used for disabling "Home" and "Up" buttons in category list
*
* @param Array $params
* @return bool
*/
function ModuleRootCategory($params)
{
return $this->Application->GetVar('m_cat_id') == $this->HomeCategory($params);
}
function CatalogItemCount($params)
{
$params['skip_quering'] = true;
$object =& $this->GetList($params);
if (!$object->Counted) {
$object->CountRecs();
}
return $object->NoFilterCount != $object->RecordsCount ? $object->RecordsCount.' / '.$object->NoFilterCount : $object->RecordsCount;
}
function InitCatalog($params)
{
$tab_prefixes = $this->Application->GetVar('tp'); // {all, <prefixes_list>, none}
if ($tab_prefixes === false) $tab_prefixes = 'all';
$skip_prefixes = isset($params['skip_prefixes']) && $params['skip_prefixes'] ? explode(',', $params['skip_prefixes']) : Array();
$replace_main = isset($params['replace_m']) && $params['replace_m'];
// get all prefixes available
$prefixes = Array();
foreach ($this->Application->ModuleInfo as $module_name => $module_data) {
$prefix = $module_data['Var'];
if ($prefix == 'adm'/* || $prefix == 'm'*/) continue;
if ($prefix == 'm' && $replace_main) {
$prefix = 'c';
}
$prefixes[] = $prefix;
}
if ($tab_prefixes == 'none') {
$skip_prefixes = array_unique(array_merge($skip_prefixes, $prefixes));
unset($skip_prefixes[ array_search($replace_main ? 'c' : 'm', $skip_prefixes) ]);
}
elseif ($tab_prefixes != 'all') {
// prefix list here
$tab_prefixes = explode(',', $tab_prefixes); // list of prefixes that should stay
$skip_prefixes = array_unique(array_merge($skip_prefixes, array_diff($prefixes, $tab_prefixes)));
}
$params['name'] = $params['render_as'];
$params['skip_prefixes'] = implode(',', $skip_prefixes);
return $this->Application->ParseBlock($params, 1);
}
/**
* Determines, that printed category/menu item is currently active (will also match parent category)
*
* @param Array $params
* @return bool
*/
function IsActive($params)
{
static $current_path = null;
if (!isset($current_path)) {
$sql = 'SELECT ParentPath
FROM ' . TABLE_PREFIX . 'Category
WHERE CategoryId = ' . (int)$this->Application->GetVar('m_cat_id');
$current_path = $this->Conn->GetOne($sql);
}
if (array_key_exists('parent_path', $params)) {
$test_path = $params['parent_path'];
}
else {
$template = $params['template'];
if ($template) {
// when using from "c:CachedMenu" tag
$sql = 'SELECT ParentPath
FROM ' . TABLE_PREFIX . 'Category
WHERE NamedParentPath = ' . $this->Conn->qstr('Content/' . $template);
$test_path = $this->Conn->GetOne($sql);
}
else {
// when using from "c:PrintList" tag
$cat_id = array_key_exists('cat_id', $params) && $params['cat_id'] ? $params['cat_id'] : false;
if ($cat_id === false) {
// category not supplied -> get current from PrintList
$category =& $this->getObject($params);
}
else {
if ("$cat_id" == 'Root') {
$cat_id = $this->Application->findModule('Name', $params['module'], 'RootCat');
}
$category =& $this->Application->recallObject($this->Prefix . '.-c' . $cat_id, $this->Prefix, Array ('skip_autoload' => true));
$category->Load($cat_id);
}
$test_path = $category->GetDBField('ParentPath');
}
}
return strpos($current_path, $test_path) !== false;
}
/**
* Checks if user have one of required permissions
*
* @param Array $params
* @return bool
*/
function HasPermission($params)
{
$perm_helper =& $this->Application->recallObject('PermissionsHelper');
/* @var $perm_helper kPermissionsHelper */
$params['raise_warnings'] = 0;
$object =& $this->getObject($params);
/* @var $object kDBItem */
$params['cat_id'] = $object->isLoaded() ? $object->GetDBField('ParentPath') : $this->Application->GetVar('m_cat_id');
return $perm_helper->TagPermissionCheck($params);
}
/**
* Prepares name for field with event in it (used only on front-end)
*
* @param Array $params
* @return string
*/
function SubmitName($params)
{
return 'events['.$this->Prefix.']['.$params['event'].']';
}
/**
* Returns last modification date of items in category / system
*
* @param Array $params
* @return string
*/
function LastUpdated($params)
{
$category_id = $this->Application->GetVar('m_cat_id');
$table_name = $this->Application->getUnitOption($this->Prefix, 'TableName');
if (isset($params['local']) && $params['local'] && $category_id > 0) {
// scan only current category & it's children
$sql = 'SELECT TreeLeft, TreeRight
FROM '.TABLE_PREFIX.'Category
WHERE CategoryId = '.$category_id;
$tree_info = $this->Conn->GetRow($sql);
$sql = 'SELECT MAX(c.Modified) AS ModDate, MAX(c.CreatedOn) AS NewDate
FROM '.TABLE_PREFIX.'Category c
WHERE c.TreeLeft BETWEEN '.$tree_info['TreeLeft'].' AND '.$tree_info['TreeRight'];
}
else {
// scan all categories in system
$sql = 'SELECT MAX(Modified) AS ModDate, MAX(CreatedOn) AS NewDate
FROM '.$table_name;
}
$row_data = $this->Conn->GetRow($sql);
if (!$row_data) {
return '';
}
$date = $row_data[ $row_data['NewDate'] > $row_data['ModDate'] ? 'NewDate' : 'ModDate' ];
// format date
$format = isset($params['format']) ? $params['format'] : '_regional_DateTimeFormat';
if (preg_match("/_regional_(.*)/", $format, $regs)) {
$lang =& $this->Application->recallObject('lang.current');
if ($regs[1] == 'DateTimeFormat') {
// combined format
$format = $lang->GetDBField('DateFormat').' '.$lang->GetDBField('TimeFormat');
}
else {
// simple format
$format = $lang->GetDBField($regs[1]);
}
}
return adodb_date($format, $date);
}
function CategoryItemCount($params)
{
$object =& $this->getObject($params);
/* @var $object kDBList */
$params['cat_id'] = $object->GetID();
$count_helper =& $this->Application->recallObject('CountHelper');
/* @var $count_helper kCountHelper */
return $count_helper->CategoryItemCount($params['prefix'], $params);
}
/**
* Returns prefix + any word (used for shared between categories per page settings)
*
* @param Array $params
* @return string
*/
function VarName($params)
{
return $this->Prefix.'_'.$params['type'];
}
/**
* Checks if current category is valid symbolic link to another category
*
* @param Array $params
* @return string
*/
function IsCategorySymLink($params)
{
$object =& $this->getObject($params);
/* @var $object kDBList */
$sym_category_id = $object->GetDBField('SymLinkCategoryId');
if (is_null($sym_category_id))
{
return false;
}
$id_field = $this->Application->getUnitOption($this->Prefix, 'IDField');
$table_name = $this->Application->getUnitOption($this->Prefix, 'TableName');
$sql = 'SELECT '.$id_field.'
FROM '.$table_name.'
WHERE '.$id_field.' = '.$sym_category_id;
return $this->Conn->GetOne($sql)? true : false;
}
/**
* Returns module prefix based on root category for given
*
* @param Array $params
* @return string
*/
function GetModulePrefix($params)
{
$object =& $this->getObject($params);
/* @var $object kDBItem */
$parent_path = explode('|', substr($object->GetDBField('ParentPath'), 1, -1));
$category_helper =& $this->Application->recallObject('CategoryHelper');
/* @var $category_helper CategoryHelper */
$module_info = $category_helper->getCategoryModule($params, $parent_path);
return $module_info['Var'];
}
function ImageSrc($params)
{
list ($ret, $tag_processed) = $this->processAggregatedTag('ImageSrc', $params, $this->getPrefixSpecial());
return $tag_processed ? $ret : false;
}
function PageLink($params)
{
$t = isset($params['template']) ? $params['template'] : '';
unset($params['template']);
if (!$t) $t = $this->Application->GetVar('t');
if (isset($params['page'])) {
$this->Application->SetVar($this->getPrefixSpecial().'_Page', $params['page']);
unset($params['page']);
}
$params['m_cat_page'] = $this->Application->GetVar($this->getPrefixSpecial().'_Page');
if (!isset($params['pass'])) {
$params['pass'] = 'm,'.$this->getPrefixSpecial();
}
return $this->Application->HREF($t, '', $params);
}
/**
* Returns spelling suggestions against search keyword
*
* @param Array $params
* @return string
*/
function SpellingSuggestions($params)
{
$keywords = unhtmlentities( trim($this->Application->GetVar('keywords')) );
if (!$keywords) {
return ;
}
// 1. try to get already cached suggestion
$suggestion = $this->Application->getCache('search.suggestion', $keywords);
if ($suggestion !== false) {
return $suggestion;
}
$table_name = $this->Application->getUnitOption('spelling-dictionary', 'TableName');
// 2. search suggestion in database
$sql = 'SELECT SuggestedCorrection
FROM ' . $table_name . '
WHERE MisspelledWord = ' . $this->Conn->qstr($keywords);
$suggestion = $this->Conn->GetOne($sql);
if ($suggestion !== false) {
$this->Application->setCache('search.suggestion', $keywords, $suggestion);
return $suggestion;
}
// 3. suggestion not found in database, ask webservice
$app_id = $this->Application->ConfigValue('YahooApplicationId');
$url = 'http://search.yahooapis.com/WebSearchService/V1/spellingSuggestion?appid=' . $app_id . '&query=';
$curl_helper =& $this->Application->recallObject('CurlHelper');
/* @var $curl_helper kCurlHelper */
$xml_data = $curl_helper->Send($url . urlencode($keywords));
$xml_helper =& $this->Application->recallObject('kXMLHelper');
/* @var $xml_helper kXMLHelper */
$root_node =& $xml_helper->Parse($xml_data);
$result = $root_node->FindChild('RESULT');
/* @var $result kXMLNode */
if (is_object($result)) {
// webservice responded -> save in local database
$fields_hash = Array (
'MisspelledWord' => $keywords,
'SuggestedCorrection' => $result->Data,
);
$this->Conn->doInsert($fields_hash, $table_name);
$this->Application->setCache('search.suggestion', $keywords, $result->Data);
return $result->Data;
}
return '';
}
/**
* Shows link for searching by suggested word
*
* @param Array $params
* @return string
*/
function SuggestionLink($params)
{
$params['keywords'] = $this->SpellingSuggestions($params);
return $this->Application->ProcessParsedTag('m', 'Link', $params);
}
function InitCatalogTab($params)
{
$tab_params['mode'] = $this->Application->GetVar('tm'); // single/multi selection possible
$tab_params['special'] = $this->Application->GetVar('ts'); // use special for this tab
$tab_params['dependant'] = $this->Application->GetVar('td'); // is grid dependant on categories grid
// set default params (same as in catalog)
if ($tab_params['mode'] === false) $tab_params['mode'] = 'multi';
if ($tab_params['special'] === false) $tab_params['special'] = '';
if ($tab_params['dependant'] === false) $tab_params['dependant'] = 'yes';
// pass params to block with tab content
$params['name'] = $params['render_as'];
$special = $tab_params['special'] ? $tab_params['special'] : $this->Special;
$params['prefix'] = trim($this->Prefix.'.'.$special, '.');
$prefix_append = $this->Application->GetVar('prefix_append');
if ($prefix_append) {
$params['prefix'] .= $prefix_append;
}
$default_grid = array_key_exists('default_grid', $params) ? $params['default_grid'] : 'Default';
$radio_grid = array_key_exists('radio_grid', $params) ? $params['radio_grid'] : 'Radio';
$params['cat_prefix'] = trim('c.'.($tab_params['special'] ? $tab_params['special'] : $this->Special), '.');
$params['tab_mode'] = $tab_params['mode'];
$params['grid_name'] = ($tab_params['mode'] == 'multi') ? $default_grid : $radio_grid;
$params['tab_dependant'] = $tab_params['dependant'];
$params['show_category'] = $tab_params['special'] == 'showall' ? 1 : 0; // this is advanced view -> show category name
if ($special == 'showall' || $special == 'user') {
$params['grid_name'] .= 'ShowAll';
}
return $this->Application->ParseBlock($params, 1);
}
/**
* Show CachedNavbar of current item primary category
*
* @param Array $params
* @return string
*/
function CategoryName($params)
{
// show category cachednavbar of
$object =& $this->getObject($params);
$category_id = isset($params['cat_id']) ? $params['cat_id'] : $object->GetDBField('CategoryId');
$category_path = $this->Application->getCache('category_paths', $category_id);
if ($category_path === false) {
// not chached
if ($category_id > 0) {
$cached_navbar = $object->GetField('CachedNavbar');
if ($category_id == $object->GetDBField('ParentId')) {
// parent category cached navbar is one element smaller, then current ones
$cached_navbar = explode('&|&', $cached_navbar);
array_pop($cached_navbar);
$cached_navbar = implode('&|&', $cached_navbar);
}
else {
// no relation with current category object -> query from db
$language_id = (int)$this->Application->GetVar('m_lang');
if (!$language_id) {
$language_id = 1;
}
$sql = 'SELECT l' . $language_id . '_CachedNavbar
FROM ' . $object->TableName . '
WHERE ' . $object->IDField . ' = ' . $category_id;
$cached_navbar = $this->Conn->GetOne($sql);
}
$cached_navbar = preg_replace('/^(Content&\|&|Content)/i', '', $cached_navbar);
$category_path = trim($this->CategoryName( Array('cat_id' => 0) ).' > '.str_replace('&|&', ' > ', $cached_navbar), ' > ');
}
else {
$category_path = $this->Application->Phrase( $this->Application->ConfigValue('Root_Name') );
}
$this->Application->setCache('category_paths', $category_id, $category_path);
}
return $category_path;
}
// structure related
/**
* Returns page object based on requested params
*
* @param Array $params
* @return PagesItem
*/
function &_getPage($params)
{
$page =& $this->Application->recallObject($this->Prefix . '.-virtual', null, $params);
/* @var $page kDBItem */
// 1. load by given id
$page_id = array_key_exists('page_id', $params) ? $params['page_id'] : false;
if ($page_id) {
if ($page_id != $page->GetID()) {
// load if different
$page->Load($page_id);
}
return $page;
}
// 2. load by template
$template = array_key_exists('page', $params) ? $params['page'] : '';
if (!$template) {
$template = $this->Application->GetVar('t');
}
// different path in structure AND design template differes from requested template
$structure_path_match = strtolower( $page->GetDBField('NamedParentPath') ) == strtolower('Content/' . $template);
$design_match = $page->GetDBField('CachedTemplate') == $template;
if (!$structure_path_match && !$design_match) {
// Same sql like in "c:getPassedID". Load, when current page object doesn't match requested page object
$themes_helper =& $this->Application->recallObject('ThemesHelper');
/* @var $themes_helper kThemesHelper */
$page_id = $themes_helper->getPageByTemplate($template);
$page->Load($page_id);
}
return $page;
}
/**
* Returns requested content block content of current or specified page
*
* @param Array $params
* @return string
*/
function ContentBlock($params)
{
$num = getArrayValue($params, 'num');
if (!$num) {
return 'NO CONTENT NUM SPECIFIED';
}
$page =& $this->_getPage($params);
/* @var $page kDBItem */
if (!$page->isLoaded()) {
// page is not created yet => all blocks are empty
return '';
}
$page_id = $page->GetID();
$content =& $this->Application->recallObject('content.-block', null, Array ('skip_autoload' => true));
/* @var $content kDBItem */
$data = Array ('PageId' => $page_id, 'ContentNum' => $num);
$content->Load($data);
if (!$content->isLoaded()) {
// bug: missing content blocks are created even if user have no SMS-management rights
$content->SetFieldsFromHash($data);
$content->Create();
}
$edit_code_before = $edit_code_after = '';
if (EDITING_MODE == EDITING_MODE_CONTENT) {
$bg_color = isset($params['bgcolor']) ? $params['bgcolor'] : '#ffffff';
$url_params = Array (
'pass' => 'm,c,content',
'm_opener' => 'd',
'c_id' => $page->GetID(),
'content_id' => $content->GetID(),
'front' => 1,
'admin' => 1,
'__URLENCODE__' => 1,
'__NO_REWRITE__'=> 1,
'escape' => 1,
'index_file' => 'index.php',
// 'bgcolor' => $bg_color,
// '__FORCE_SID__' => 1
);
// link from Front-End to admin, don't remove "index.php"
$edit_url = $this->Application->HREF('categories/edit_content', ADMIN_DIRECTORY, $url_params, 'index.php');
$edit_code_before = '
<div class="cms-edit-btn-container">
<div class="cms-edit-btn" onclick="$form_name=\'kf_cont_'.$content->GetID().'\'; std_edit_item(\'content\', \'categories/edit_content\');">
<div class="cms-btn-image">
<img src="' . $this->Application->BaseURL() . 'core/admin_templates/img/top_frame/icons/content_mode.png" width="15" height="16" alt=""/>
</div>
<div class="cms-btn-text">' . $this->Application->Phrase('la_btn_EditContent', false, true) . ' '.(defined('DEBUG_MODE') && DEBUG_MODE ? " - #{$num}" : '').'</div>
</div>
<div class="cms-btn-content">';
$edit_form = '<form method="POST" style="display: inline; margin: 0px" name="kf_cont_'.$content->GetID().'" id="kf_cont_'.$content->GetID().'" action="'.$edit_url.'">';
$edit_form .= '<input type="hidden" name="c_id" value="'.$page->GetID().'"/>';
$edit_form .= '<input type="hidden" name="content_id" value="'.$content->GetID().'"/>';
$edit_form .= '<input type="hidden" name="front" value="1"/>';
$edit_form .= '<input type="hidden" name="bgcolor" value="'.$bg_color.'"/>';
$edit_form .= '<input type="hidden" name="m_lang" value="'.$this->Application->GetVar('m_lang').'"/>';
$edit_form .= '</form>';
$edit_code_after = '</div></div>';
if (array_key_exists('forms_later', $params) && $params['forms_later']) {
$all_forms = $this->Application->GetVar('all_forms');
$this->Application->SetVar('all_forms', $all_forms . $edit_form);
}
else {
$edit_code_after .= $edit_form;
}
}
if ($this->Application->GetVar('_editor_preview_') == 1) {
$data = $this->Application->RecallVar('_editor_preview_content_');
} else {
$data = $content->GetField('Content');
}
$data = $edit_code_before . $this->_transformContentBlockData($data, $params) . $edit_code_after;
if ($data != '') {
$this->Application->Parser->DataExists = true;
}
return $data;
}
/**
* Apply all kinds of content block data transformations without rewriting ContentBlock tag
*
* @param string $data
* @return string
*/
function _transformContentBlockData(&$data, $params)
{
return $data;
}
/**
* Returns current page name or page based on page/page_id parameters
*
* @param Array $params
* @return string
* @todo Used?
*/
function PageName($params)
{
$page =& $this->_getPage($params);
return $page->GetDBField('Name');
}
/**
* Returns current/given page information
*
* @param Array $params
* @return string
*/
function PageInfo($params)
{
$page =& $this->_getPage($params);
if ($params['type'] == 'index_tools') {
$page_info = $page->GetDBField('IndexTools');
if ($page_info) {
return $page_info;
}
else {
if (PROTOCOL == 'https://') {
return $this->Application->ConfigValue('cms_DefaultIndextoolsCode_SSL');
}
else {
return $this->Application->ConfigValue('cms_DefaultIndextoolsCode');
}
}
}
switch ($params['type']) {
case 'title':
$db_field = 'Title';
break;
case 'htmlhead_title':
$db_field = 'Name';
break;
case 'meta_title':
$db_field = 'MetaTitle';
break;
case 'meta_keywords':
$db_field = 'MetaKeywords';
$cat_field = 'Keywords';
break;
case 'meta_description':
$db_field = 'MetaDescription';
$cat_field = 'Description';
break;
default:
return '';
}
$default = isset($params['default']) ? $params['default'] : '';
$val = $page->GetField($db_field);
if (!$default) {
if ($this->Application->isModuleEnabled('In-Portal')) {
if (!$val && ($params['type'] == 'meta_keywords' || $params['type'] == 'meta_description')) {
// take category meta if it's not set for the page
return $this->Application->ProcessParsedTag('c', 'Meta', Array('name' => $cat_field));
}
}
}
if (isset($params['force_default']) && $params['force_default']) {
return $default;
}
if (preg_match('/^_Auto:/', $val)) {
$val = $default;
/*if ($db_field == 'Title') {
$page->SetDBField($db_field, $default);
$page->Update();
}*/
}
elseif ($page->GetID() == false) {
return $default;
}
return $val;
}
/**
* Includes admin css and js, that are required for cms usage on Front-Edn
*
*
* @param Array $params
* @return string
*/
function EditingScripts($params)
{
if ($this->Application->GetVar('admin_scripts_included') || !EDITING_MODE) {
return ;
}
$this->Application->SetVar('admin_scripts_included', 1);
$js_url = $this->Application->BaseURL() . 'core/admin_templates/js';
$ret = '<link rel="stylesheet" href="' . $js_url . '/jquery/thickbox/thickbox.css" type="text/css" media="screen"/>' . "\n";
$ret .= '<link rel="stylesheet" href="' . $js_url . '/../incs/cms.css" type="text/css" media="screen"/>' . "\n";
if (EDITING_MODE == EDITING_MODE_DESIGN) {
$ret .= ' <style type="text/css" media="all">
div.movable-element .movable-header { cursor: move; }
</style>';
}
$ret .= '<script type="text/javascript" src="' . $js_url . '/jquery/jquery.pack.js"></script>' . "\n";
$ret .= '<script type="text/javascript" src="' . $js_url . '/jquery/jquery-ui.custom.min.js"></script>' . "\n";
$ret .= '<script type="text/javascript" src="' . $js_url . '/is.js"></script>' . "\n";
$ret .= '<script type="text/javascript" src="' . $js_url . '/application.js"></script>' . "\n";
$ret .= '<script type="text/javascript" src="' . $js_url . '/script.js"></script>' . "\n";
$ret .= '<script type="text/javascript" src="' . $js_url . '/jquery/thickbox/thickbox.js"></script>' . "\n";
$ret .= '<script type="text/javascript" src="' . $js_url . '/template_manager.js"></script>' . "\n";
$ret .= '<script language="javascript">' . "\n";
$ret .= "TB.pathToImage = '" . $js_url . "/jquery/thickbox/loadingAnimation.gif';" . "\n";
$template = $this->Application->GetVar('t');
$theme_id = $this->Application->GetVar('m_theme');
- $url_params = Array ('block' => '#BLOCK#', 'theme-file_event' => '#EVENT#', 'theme_id' => $theme_id, 'source' => $template, 'pass' => 'all,theme-file', 'front' => 1, 'm_opener' => 'd', 'no_amp' => 1);
+ $url_params = Array ('block' => '#BLOCK#', 'theme-file_event' => '#EVENT#', 'theme_id' => $theme_id, 'source' => $template, 'pass' => 'all,theme-file', 'front' => 1, 'm_opener' => 'd', '__NO_REWRITE__' => 1, 'no_amp' => 1);
$edit_template_url = $this->Application->HREF('themes/template_edit', ADMIN_DIRECTORY, $url_params, 'index.php');
- $url_params = Array ('theme-file_event' => 'OnSaveLayout', 'source' => $template, 'pass' => 'all,theme-file', 'no_amp' => 1);
+ $url_params = Array ('theme-file_event' => 'OnSaveLayout', 'source' => $template, 'pass' => 'all,theme-file', '__NO_REWRITE__' => 1, 'no_amp' => 1);
$save_layout_url = $this->Application->HREF('index', '', $url_params);
- $this_url = $this->Application->HREF('', '', Array ('editing_mode' => '#EDITING_MODE#', 'no_amp' => 1));
+ $this_url = $this->Application->HREF('', '', Array ('editing_mode' => '#EDITING_MODE#', '__NO_REWRITE__' => 1, 'no_amp' => 1));
$ret .= "var aTemplateManager = new TemplateManager('" . $edit_template_url . "', '" . $this_url . "', '" . $save_layout_url . "', " . (int)EDITING_MODE . ");\n";
$ret .= "var main_title = '" . addslashes( $this->Application->ConfigValue('Site_Name') ) . "';" . "\n";
$use_popups = (int)$this->Application->ConfigValue('UsePopups');
$ret .= "var \$use_popups = " . ($use_popups > 0 ? 'true' : 'false') . ";\n";
$ret .= "var \$modal_windows = " . ($use_popups == 2 ? 'true' : 'false') . ";\n";
if (EDITING_MODE != EDITING_MODE_BROWSE) {
$ret .= "var base_url = '" . $this->Application->BaseURL() . "';" . "\n";
$ret .= 'TB.closeHtml = \'<img src="' . $js_url . '/../img/close_window15.gif" width="15" height="15" style="border-width: 0px;" alt="close"/><br/>\';' . "\n";
- $url_params = Array('m_theme' => '', 'pass' => 'm', 'm_opener' => 'r', 'no_amp' => 1);
+ $url_params = Array('m_theme' => '', 'pass' => 'm', 'm_opener' => 'r', '__NO_REWRITE__' => 1, 'no_amp' => 1);
$browse_url = $this->Application->HREF('catalog/catalog', ADMIN_DIRECTORY, $url_params, 'index.php');
$browse_url = preg_replace('/&(admin|editing_mode)=[\d]/', '', $browse_url);
$ret .= '
var topmost = window.top;
topmost.document.title = document.title + \' - ' . addslashes($this->Application->Phrase('la_AdministrativeConsole', false)) . '\';
t = \''.$this->Application->GetVar('t').'\';
if (window.parent.frames["menu"] != undefined) {
if ( $.isFunction(window.parent.frames["menu"].SyncActive) ) {
window.parent.frames["menu"].SyncActive("' . $browse_url . '");
}
}
';
}
$ret .= '</script>' . "\n";
if (EDITING_MODE != EDITING_MODE_BROWSE) {
// add form, so admin scripts could work
$ret .= '<form id="kernel_form" name="kernel_form" enctype="multipart/form-data" method="post" action="' . $browse_url . '">
<input type="hidden" name="MAX_FILE_SIZE" id="MAX_FILE_SIZE" value="' . MAX_UPLOAD_SIZE . '" />
<input type="hidden" name="sid" id="sid" value="' . $this->Application->GetSID() . '" />
</form>';
}
return $ret;
}
/**
* Prints "Edit Page" button on cms page
*
* @param Array $params
* @return string
*/
function EditPage($params)
{
if (!EDITING_MODE) {
return '';
}
$display_mode = array_key_exists('mode', $params) ? $params['mode'] : false;
$edit_code = '';
$page =& $this->_getPage($params);
if (!$page->isLoaded() || (($display_mode != 'end') && (EDITING_MODE == EDITING_MODE_BROWSE))) {
// when "EditingScripts" tag is not used, make sure, that scripts are also included
return $this->EditingScripts($params);
}
// show "EditPage" button only for pages, that exists in structure
if ($display_mode != 'end') {
$edit_btn = '';
if (EDITING_MODE == EDITING_MODE_CONTENT) {
$url_params = Array(
'pass' => 'm,c',
'm_opener' => 'd',
'c_id' => $page->GetID(),
'c_mode' => 't',
'c_event' => 'OnEdit',
'front' => 1,
'__URLENCODE__' => 1,
'__NO_REWRITE__'=> 1,
'escape' => 1,
'index_file' => 'index.php',
);
$edit_url = $this->Application->HREF('categories/categories_edit', ADMIN_DIRECTORY, $url_params);
$edit_btn .= '
<div class="cms-section-properties-btn"' . ($display_mode === false ? ' style="margin: 0px;"' : '') . ' onmouseover="window.status=\''.$edit_url.'\'; return true" onclick="$form_name=\'kf_'.$page->GetID().'\'; std_edit_item(\'c\', \'categories/categories_edit\');">
<div class="cms-btn-image">
<img src="' . $this->Application->BaseURL() . 'core/admin_templates/img/top_frame/icons/section_properties.png" width="15" height="16" alt=""/>
</div>
<div class="cms-btn-text">' . $this->Application->Phrase('la_btn_SectionProperties', false, true) . '</div>
</div>' . "\n";
} elseif (EDITING_MODE == EDITING_MODE_DESIGN) {
$url_params = Array(
'pass' => 'm,theme',
'm_opener' => 'd',
'theme_id' => $this->Application->GetVar('m_theme'),
'theme_mode' => 't',
'theme_event' => 'OnEdit',
'theme-file_id' => $this->_getThemeFileId(),
'front' => 1,
'__URLENCODE__' => 1,
'__NO_REWRITE__'=> 1,
'escape' => 1,
'index_file' => 'index.php',
);
$edit_url = $this->Application->HREF('themes/file_edit', ADMIN_DIRECTORY, $url_params);
$edit_btn .= '
<div class="cms-layout-btn-container"' . ($display_mode === false ? ' style="margin: 0px;"' : '') . '>
<div class="cms-save-layout-btn" onclick="aTemplateManager.saveLayout(); return false;">
<div class="cms-btn-image">
<img src="' . $this->Application->BaseURL() . 'core/admin_templates/img/top_frame/icons/save_button.gif" width="16" height="16" alt=""/>
</div>
<div class="cms-btn-text">' . $this->Application->Phrase('la_btn_SaveChanges', false, true) . '</div>
</div>
<div class="cms-cancel-layout-btn" onclick="aTemplateManager.cancelLayout(); return false;">
<div class="cms-btn-image">
<img src="' . $this->Application->BaseURL() . 'core/admin_templates/img/top_frame/icons/cancel_button.gif" width="16" height="16" alt=""/>
</div>
<div class="cms-btn-text">' . $this->Application->Phrase('la_btn_Cancel', false, true) . '</div>
</div>
</div>
<div class="cms-section-properties-btn"' . ($display_mode === false ? ' style="margin: 0px;"' : '') . ' onmouseover="window.status=\''.$edit_url.'\'; return true" onclick="$form_name=\'kf_'.$page->GetID().'\'; std_edit_item(\'theme\', \'themes/file_edit\');">
<div class="cms-btn-image">
<img src="' . $this->Application->BaseURL() . 'core/admin_templates/img/top_frame/icons/section_properties.png" width="15" height="16" alt=""/>
</div>
<div class="cms-btn-text">' . $this->Application->Phrase('la_btn_SectionTemplate', false, true) . '</div>
</div>' . "\n";
}
if ($display_mode == 'start') {
// button with border around the page
$edit_code .= '<div class="cms-section-properties-btn-container">' . $edit_btn . '<div class="cms-btn-content">';
}
else {
// button without border around the page
$edit_code .= $edit_btn;
}
}
if ($display_mode == 'end') {
// draw border around the page
$edit_code .= '</div></div>';
}
if ($display_mode != 'end') {
$edit_code .= '<form method="POST" style="display: inline; margin: 0px" name="kf_'.$page->GetID().'" id="kf_'.$page->GetID().'" action="'.$edit_url.'"></form>';
// when "EditingScripts" tag is not used, make sure, that scripts are also included
$edit_code .= $this->EditingScripts($params);
}
return $edit_code;
}
function _getThemeFileId()
{
$template = $this->Application->GetVar('t');
if (!$this->Application->TemplatesCache->TemplateExists($template) && !$this->Application->isAdmin) {
$cms_handler =& $this->Application->recallObject($this->Prefix . '_EventHandler');
/* @var $cms_handler CategoriesEventHandler */
$template = ltrim($cms_handler->GetDesignTemplate(), '/');
}
$file_path = dirname($template) == '.' ? '' : '/' . dirname($template);
$file_name = basename($template);
$sql = 'SELECT FileId
FROM ' . TABLE_PREFIX . 'ThemeFiles
- WHERE (FilePath = ' . $this->Conn->qstr($file_path) . ') AND (FileName = ' . $this->Conn->qstr($file_name . '.tpl') . ')';
+ WHERE (ThemeId = ' . (int)$this->Application->GetVar('m_theme') . ') AND (FilePath = ' . $this->Conn->qstr($file_path) . ') AND (FileName = ' . $this->Conn->qstr($file_name . '.tpl') . ')';
return $this->Conn->GetOne($sql);
}
/**
* Builds site menu
*
* @param Array $params
* @return string
*/
function CachedMenu($params)
{
$menu_helper =& $this->Application->recallObject('MenuHelper');
/* @var $menu_helper MenuHelper */
return $menu_helper->menuTag($this->getPrefixSpecial(), $params);
}
/**
* Trick to allow some kind of output formatting when using CachedMenu tag
*
* @param Array $params
* @return bool
*/
function SplitColumn($params)
{
return $this->Application->GetVar($params['i']) > ceil($params['total'] / $params['columns']);
}
/**
* Returns direct children count of given category
*
* @param Array $params
* @return int
*/
function HasSubCats($params)
{
$sql = 'SELECT COUNT(*)
FROM ' . TABLE_PREFIX . 'Category
WHERE ParentId = ' . $params['cat_id'];
return $this->Conn->GetOne($sql);
}
/**
* Prints sub-pages of given/current page.
*
* @param Array $params
* @return string
* @todo This could be reached by using "parent_cat_id" parameter. Only difference here is new block parameter "path". Need to rewrite.
*/
function PrintSubPages($params)
{
$list =& $this->Application->recallObject($this->getPrefixSpecial(), $this->Prefix.'_List', $params);
/* @var $list kDBList */
$category_id = array_key_exists('category_id', $params) ? $params['category_id'] : $this->Application->GetVar('m_cat_id');
$list->addFilter('current_pages', TABLE_PREFIX . 'CategoryItems.CategoryId = ' . $category_id);
$list->Query();
$list->GoFirst();
$o = '';
$block_params = $this->prepareTagParams($params);
$block_params['name'] = $params['render_as'];
while (!$list->EOL()) {
$block_params['path'] = $list->GetDBField('Path');
$o .= $this->Application->ParseBlock($block_params, 1);
$list->GoNext();
}
return $o;
}
/**
* Builds link for browsing current page on Front-End
*
* @param Array $params
* @return string
*/
function PageBrowseLink($params)
{
$object =& $this->getObject($params);
$themes_helper =& $this->Application->recallObject('ThemesHelper');
/* @var $themes_helper kThemesHelper */
$url_params = Array (
'm_cat_id' => $object->GetID(),
'm_theme' => $themes_helper->getCurrentThemeId(),
'pass' => 'm',
'admin' => 1,
'index_file' => 'index.php'
);
return $this->Application->HREF($object->GetDBField('NamedParentPath'), '_FRONT_END_', $url_params);
}
/**
* Builds link to cms page (used?)
*
* @param Array $params
* @return string
*/
function ContentPageLink($params)
{
$object =& $this->getObject($params);
$params['t'] = $object->GetDBField('NamedParentPath');
$params['m_cat_id'] = 0;
return $this->Application->ProcessParsedTag('m', 'Link', $params);
}
/**
* Prepares cms page description for search result page
*
* @param Array $params
* @return string
*/
function SearchDescription($params)
{
$object =& $this->getObject($params);
$desc = $object->GetField('MetaDescription');
if (!$desc) {
$sql = 'SELECT *
FROM ' . TABLE_PREFIX . 'PageContent
WHERE PageId = ' . $object->GetID() . ' AND ContentNum = 1';
$content = $this->Conn->GetRow($sql);
if ($content['l'.$this->Application->GetVar('m_lang').'_Content']) {
$desc = $content['l'.$this->Application->GetVar('m_lang').'_Content'];
}
else {
$desc = $content['l'.$this->Application->GetDefaultLanguageId().'_Content'];
}
}
return mb_substr($desc, 0, 300).(mb_strlen($desc) > 300 ? '...' : '');
}
/**
* Simplified version of "c:CategoryLink" for "c:PrintList"
*
* @param Array $params
* @return string
* @todo Used? Needs refactoring.
*/
function EnterCatLink($params)
{
$object =& $this->getObject($params);
$url_params = Array ('pass' => 'm', 'm_cat_id' => $object->GetID());
return $this->Application->HREF($params['template'], '', $url_params);
}
/**
* Simplified version of "c:CategoryPath", that do not use blocks for rendering
*
* @param Array $params
* @return string
* @todo Used? Maybe needs to be removed.
*/
function PagePath($params)
{
$object =& $this->getObject($params);
$path = $object->GetField('CachedNavbar');
if ($path) {
$items = explode('&|&', $path);
array_shift($items);
return implode(' -&gt; ', $items);
}
return '';
}
/**
* Returns configuration variable value
*
* @param Array $params
* @return string
* @todo Needs to be replaced with "m:GetConfig" tag; Not used now (were used on structure_edit.tpl).
*/
function AllowManualFilenames($params)
{
return $this->Application->ConfigValue('ProjCMSAllowManualFilenames');
}
/**
* Draws path to current page (each page can be link to it)
*
* @param Array $params
* @return string
*/
function CurrentPath($params)
{
$block_params = $this->prepareTagParams($params);
$block_params['name'] = $block_params['render_as'];
$object =& $this->Application->recallObject($this->Prefix);
/* @var $object kDBItem */
$category_ids = explode('|', substr($object->GetDBField('ParentPath'), 1, -1));
$id_field = $this->Application->getUnitOption($this->Prefix, 'IDField');
$table_name = $this->Application->getUnitOption($this->Prefix, 'TableName');
$language = (int)$this->Application->GetVar('m_lang');
if (!$language) {
$language = 1;
}
$sql = 'SELECT l'.$language.'_Name AS Name, NamedParentPath
FROM '.$table_name.'
WHERE '.$id_field.' IN ('.implode(',', $category_ids).')';
$categories_data = $this->Conn->Query($sql);
$ret = '';
foreach ($categories_data as $index => $category_data) {
if ($category_data['Name'] == 'Content') {
continue;
}
$block_params['title'] = $category_data['Name'];
$block_params['template'] = preg_replace('/^Content\//i', '', $category_data['NamedParentPath']);
$block_params['is_first'] = $index == 1; // because Content is 1st element
$block_params['is_last'] = $index == count($categories_data) - 1;
$ret .= $this->Application->ParseBlock($block_params);
}
return $ret;
}
/**
* Synonim to PrintList2 for "onlinestore" theme
*
* @param Array $params
* @return string
*/
function ListPages($params)
{
return $this->PrintList2($params);
}
/**
* Returns information about parser element locations in template
*
* @param Array $params
* @return mixed
*/
function BlockInfo($params)
{
if (!EDITING_MODE) {
return '';
}
$template_helper =& $this->Application->recallObject('TemplateHelper');
/* @var $template_helper TemplateHelper */
return $template_helper->blockInfo( $params['name'] );
}
/**
* Hide all editing tabs except permission tab, when editing "Home" (ID = 0) category
*
* @param Array $params
*/
function ModifyUnitConfig($params)
{
$root_category = $this->Application->RecallVar('IsRootCategory_' . $this->Application->GetVar('m_wid'));
if (!$root_category) {
return ;
}
$edit_tab_presets = $this->Application->getUnitOption($this->Prefix, 'EditTabPresets');
$edit_tab_presets['Default'] = Array (
'permissions' => $edit_tab_presets['Default']['permissions'],
);
$this->Application->setUnitOption($this->Prefix, 'EditTabPresets', $edit_tab_presets);
}
/**
* Prints catalog export templates
*
* @param Array $params
* @return string
*/
function PrintCatalogExportTemplates($params)
{
$prefixes = explode(',', $params['prefixes']);
$ret = Array ();
foreach ($prefixes as $prefix) {
if ($this->Application->prefixRegistred($prefix)) {
$ret[$prefix] = $this->Application->getUnitOption($prefix, 'ModuleFolder') . '/export';
}
}
$json_helper =& $this->Application->recallObject('JSONHelper');
/* @var $json_helper JSONHelper */
return $json_helper->encode($ret);
}
/**
* Checks, that "view in browse mode" functionality available
*
* @param Array $params
* @return bool
*/
function BrowseModeAvailable($params)
{
$valid_special = $params['Special'] != 'user';
$not_selector = $this->Application->GetVar('type') != 'item_selector';
return $valid_special && $not_selector;
}
/**
* Returns a link for editing product
*
* @param Array $params
* @return string
*/
function ItemEditLink($params)
{
$object =& $this->getObject();
/* @var $object kDBList */
$edit_template = $this->Application->getUnitOption($this->Prefix, 'AdminTemplatePath') . '/' . $this->Application->getUnitOption($this->Prefix, 'AdminTemplatePrefix') . 'edit';
$url_params = Array (
'm_opener' => 'd',
$this->Prefix.'_mode' => 't',
$this->Prefix.'_event' => 'OnEdit',
$this->Prefix.'_id' => $object->GetID(),
'm_cat_id' => $object->GetDBField('ParentId'),
'pass' => 'all,'.$this->Prefix,
'no_pass_through' => 1,
);
return $this->Application->HREF($edit_template,'', $url_params);
}
function RelevanceIndicator($params)
{
$object =& $this->getObject($params);
$search_results_table = TABLE_PREFIX.'ses_'.$this->Application->GetSID().'_'.TABLE_PREFIX.'Search';
$sql = 'SELECT Relevance
FROM '.$search_results_table.'
WHERE ResourceId = '.$object->GetDBField('ResourceId');
$percents_off = (int)(100 - (100 * $this->Conn->GetOne($sql)));
$percents_off = ($percents_off < 0) ? 0 : $percents_off;
if ($percents_off) {
$params['percent_off'] = $percents_off;
$params['percent_on'] = 100 - $percents_off;
$params['name'] = $this->SelectParam($params, 'relevance_normal_render_as,block_relevance_normal');
}
else {
$params['name'] = $this->SelectParam($params, 'relevance_full_render_as,block_relevance_full');
}
return $this->Application->ParseBlock($params);
}
}
\ No newline at end of file

Event Timeline