Page MenuHomeIn-Portal Phabricator

in-portal
No OneTemporary

File Metadata

Created
Fri, Feb 7, 8:25 AM

in-portal

Index: branches/5.0.x/core/kernel/processors/main_processor.php
===================================================================
--- branches/5.0.x/core/kernel/processors/main_processor.php (revision 12703)
+++ branches/5.0.x/core/kernel/processors/main_processor.php (revision 12704)
@@ -1,1026 +1,1029 @@
<?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.net/license/ for copyright notices and details.
*/
defined('FULL_PATH') or die('restricted access!');
class kMainTagProcessor extends kTagProcessor {
function Init($prefix, $special, $event_params = null)
{
parent::Init($prefix, $special, $event_params);
$actions =& $this->Application->recallObject('kActions');
$actions->Set('t', $this->Application->GetVar('t'));
$actions->Set('sid', $this->Application->GetSID());
$actions->Set('m_opener', $this->Application->GetVar('m_opener') );
}
/**
* Base folder for all template includes
*
* @param Array $params
* @return string
*/
function TemplatesBase($params)
{
static $cached = Array ();
$cache_key = crc32( serialize($params) );
if (!array_key_exists($cache_key, $cached)) {
$force_admin = array_key_exists('force_admin', $params) && $params['force_admin'];
$module = array_key_exists('module', $params) ? $params['module'] : 'core';
if ($this->Application->IsAdmin() || $force_admin) {
if ($module == 'in-portal') {
$module = 'kernel';
}
$path = $force_admin ? '/core/admin_templates' : THEMES_PATH;
$path = preg_replace('/\/(.*?)\/(.*)/', $module.'/\\2', $path); // remove leading slash + substitute module
}
else {
$path = mb_substr(THEMES_PATH, 1);
if (mb_strtolower($module) == 'in-portal') {
$module_folder = 'platform';
}
else {
$module_folder = $this->Application->findModule('Name', $module, 'TemplatePath');
}
$path .= rtrim('/' . trim($module_folder, '/'), '/') . '/';
}
$cached[$cache_key] = $this->Application->BaseURL() . $path;
}
return $cached[$cache_key];
}
/**
* Creates <base href ..> HTML tag for all templates
* affects future css, js files and href params of links
*
* @return string
* @access public
*/
function Base_Ref($params)
{
return '<base href="'.$this->TemplatesBase($params).'/" />';
}
/**
* Returns base url for web-site
*
* @return string
* @access public
*/
function BaseURL()
{
return $this->Application->BaseURL();
}
//for compatability with K3 tags
function Base($params)
{
return $this->TemplatesBase($params).'/';
}
function ProjectBase($params)
{
return $this->Application->BaseURL();
}
/*function Base($params)
{
return $this->Application->BaseURL().$params['add'];
}*/
/**
* Used to create link to any template.
* use "pass" paramter if "t" tag to specify
* prefix & special of object to be represented
* in resulting url
*
* @param Array $params
* @return string
* @access public
*/
function T($params)
{
//by default link to current template
$t = $this->SelectParam($params, 't,template');
unset($params['t']);
unset($params['template']);
$prefix=isset($params['prefix']) ? $params['prefix'] : ''; unset($params['prefix']);
$index_file = isset($params['index_file']) ? $params['index_file'] : null; unset($params['index_file']);
return $this->Application->HREF($t, $prefix, $params, $index_file);
}
function Link($params)
{
if (isset($params['template'])) {
$params['t'] = $params['template'];
unset($params['template']);
}
if (!isset($params['pass']) && !isset($params['no_pass'])) $params['pass'] = 'm';
if (isset($params['no_pass'])) unset($params['no_pass']);
if ( $this->Application->GetVar('admin') ) {
$params['admin'] = 1;
if (!array_key_exists('editing_mode', $params)) {
$params['editing_mode'] = EDITING_MODE;
}
}
return $this->T($params);
}
function Env($params)
{
$t = $params['template'];
unset($params['template']);
return $this->Application->BuildEnv($t, $params, 'm', null, false);
}
function FormAction($params)
{
$params['pass'] = 'all,m';
$params['pass_category'] = 1;
return $this->Application->HREF('', '', $params);
}
/*// NEEDS TEST
function Config($params)
{
return $this->Application->ConfigOption($params['var']);
}
function Object($params)
{
$name = $params['name'];
$method = $params['method'];
$tmp =& $this->Application->recallObject($name);
if ($tmp != null) {
if (method_exists($tmp, $method))
return $tmp->$method($params);
else
echo "Method $method does not exist in object ".get_class($tmp)." named $name<br>";
}
else
echo "Object $name does not exist in the appliaction<br>";
}*/
/**
* Tag, that always returns true.
* For parser testing purposes
*
* @param Array $params
* @return bool
* @access public
*/
function True($params)
{
return true;
}
/**
* Tag, that always returns false.
* For parser testing purposes
*
* @param Array $params
* @return bool
* @access public
*/
function False($params)
{
return false;
}
/**
- * Returns block parameter by name (used only as "check" parameter value for "m_if" tag !)
+ * Returns block parameter by name (used only as "check" parameter value for "m_if" tag!)
*
* @param Array $params
* @return stirng
* @access public
*/
function Param($params)
{
$name = $params['name'];
- /*if (isset($this->Application->LateParsed[$name])) {
- $f = $this->Application->PreParsedBlocks['capture_'.$name.$this->Application->LateParsed[$name]];
- $this->Application->Parser->SetParam($name, $f(array()));
- }*/
-
- $res = $this->Application->Parser->GetParam($params['name']);
+ if (array_key_exists($name, $this->Application->Parser->Captures)) {
+ $capture_params = $params;
+ $capture_params['name'] = '__capture_' . $name;
+
+ $this->Application->Parser->SetParam($name, $this->Application->ParseBlock($capture_params));
+ }
+
+ $res = $this->Application->Parser->GetParam($name);
+
if ($res === false) {
$res = '';
}
- if (isset($params['plus'])) {
+ if (array_key_exists('plus', $params)) {
$res += $params['plus'];
}
return $res;
}
/**
* Compares block parameter with value specified
*
* @param Array $params
* @return bool
* @access public
*/
function ParamEquals($params)
{
$name = $this->SelectParam($params, 'name,var,param');
$value = $params['value'];
return ($this->Application->Parser->GetParam($name) == $value);
}
/*function PHP_Self($params)
{
return $HTTP_SERVER_VARS['PHP_SELF'];
}
*/
/**
* Returns session variable value by name
*
* @param Array $params
* @return string
* @access public
*/
function Recall($params)
{
$var_name = $this->SelectParam($params,'name,var,param');
if (isset($params['persistent']) && $params['persistent']) {
$ret = $this->Application->RecallPersistentVar($var_name);
}
else {
$ret = $this->Application->RecallVar($var_name);
}
$ret = ($ret === false && isset($params['no_null'])) ? '' : $ret;
if (getArrayValue($params, 'special') || getArrayValue($params, 'htmlchars')) {
$ret = htmlspecialchars($ret);
}
if (getArrayValue($params, 'urlencode')) {
$ret = urlencode($ret);
}
return $ret;
}
function RemoveVar($params)
{
$this->Application->RemoveVar( $this->SelectParam($params,'name,var,param') );
}
// bad style to store something from template to session !!! (by Alex)
// Used here only to test how session works, nothing more
function Store($params)
{
//echo"Store $params[name]<br>";
$name = $params['name'];
$value = $params['value'];
$this->Application->StoreVar($name,$value);
}
/**
* Sets application variable value(-s)
*
* @param Array $params
* @access public
*/
function Set($params)
{
foreach ($params as $param => $value) {
$this->Application->SetVar($param, $value);
}
}
/**
* Increment application variable
* specified by number specified
*
* @param Array $params
* @access public
*/
function Inc($params)
{
$this->Application->SetVar($params['param'], $this->Application->GetVar($params['param']) + $params['by']);
}
/**
* Retrieves application variable
* value by name
*
* @param Array $params
* @return string
* @access public
*/
function Get($params)
{
$ret = $this->Application->GetVar($this->SelectParam($params, 'name,var,param'), '');
return getArrayValue($params, 'htmlchars') ? htmlspecialchars($ret) : $ret;
}
/**
* Retrieves application constant
* value by name
*
* @param Array $params
* @return string
* @access public
*/
function GetConst($params)
{
$constant_name = $this->SelectParam($params, 'name,const');
return defined($constant_name) ? constant($constant_name) : '';
}
/**
* Retrieves configuration variable value by name
*
* @param Array $params
* @return string
* @access public
*/
function GetConfig($params)
{
$config_name = $this->SelectParam($params, 'name,var');
$ret = $this->Application->ConfigValue($config_name);
if( getArrayValue($params, 'escape') ) $ret = addslashes($ret);
return $ret;
}
function ConfigEquals($params)
{
$option = $this->SelectParam($params, 'name,option,var');
return $this->Application->ConfigValue($option) == getArrayValue($params, 'value');
}
/**
* Creates all hidden fields
* needed for kernel_form
*
* @param Array $params
* @return string
* @access public
*/
function DumpSystemInfo($params)
{
$actions =& $this->Application->recallObject('kActions');
$actions->Set('t', $this->Application->GetVar('t') );
$params = $actions->GetParams();
$o='';
foreach ($params AS $name => $val)
{
$o .= "<input type='hidden' name='$name' id='$name' value='$val'>\n";
}
return $o;
}
/**
* Used for search sidebox on front-end only
*
* @param Array $params
* @return string
* @author Alex
*/
function GetFormHiddens($params)
{
$t = $this->SelectParam($params, 'template,t');
unset($params['template']);
$form_fields = Array ();
if ($this->Application->RewriteURLs()) {
$session =& $this->Application->recallObject('Session');
if ($session->NeedQueryString()) {
$form_fields['sid'] = $this->Application->GetSID();
}
}
else {
$form_fields['env'] = $this->Application->BuildEnv($t, $params, 'm', null, false);
}
if ($this->Application->GetVar('admin') == 1) {
$form_fields['admin'] = 1;
}
$ret = '';
$field_tpl = '<input type="hidden" name="%1$s" id="%1$s" value="%2$s"/>'."\n";
foreach ($form_fields as $form_field => $field_value) {
$ret .= sprintf($field_tpl, $form_field, $field_value);
}
return $ret;
}
function Odd_Even($params)
{
$odd = $params['odd'];
$even = $params['even'];
if (!isset($params['var'])) {
$var = 'odd_even';
}
else {
$var = $params['var'];
}
if ($this->Application->GetVar($var) == 'even') {
if (!isset($params['readonly']) || !$params['readonly']) {
$this->Application->SetVar($var, 'odd');
}
return $even;
}
else {
if (!isset($params['readonly']) || !$params['readonly']) {
$this->Application->SetVar($var, 'even');
}
return $odd;
}
}
/**
* Returns phrase translation by name
*
* @param Array $params
* @return string
* @access public
*/
function Phrase($params)
{
// m:phrase name="phrase_name" default="Tr-alala" updated="2004-01-29 12:49"
$phrase_name = $this->SelectParam($params, 'label,name,title');
if (isset($params['source']) && $params['source']) {
$phrase_name = $this->Application->GetVar($phrase_name);
if (array_key_exists('default', $params) && !$phrase_name) {
$phrase_name = $params['default'];
}
}
$no_editing = array_key_exists('no_editing', $params) && $params['no_editing'];
$translation = $this->Application->Phrase($phrase_name, !$no_editing);
if (isset($params['escape']) && $params['escape']) {
$translation = htmlspecialchars($translation, ENT_QUOTES);
$translation = addslashes($translation);
}
return $translation;
}
// for tabs
function is_active($params)
{
$test_templ = $this->SelectParam($params, 'templ,template,t');
if ( !getArrayValue($params,'allow_empty') )
{
$if_true=getArrayValue($params,'true') ? $params['true'] : 1;
$if_false=getArrayValue($params,'false') ? $params['false'] : 0;
}
else
{
$if_true=$params['true'];
$if_false=$params['false'];
}
if ( preg_match("/^".str_replace('/', '\/', $test_templ)."/i", $this->Application->GetVar('t'))) {
return $if_true;
}
else {
return $if_false;
}
}
function IsNotActive($params)
{
return !$this->is_active($params);
}
function IsActive($params)
{
return $this->is_active($params);
}
function is_t_active($params)
{
return $this->is_active($params);
}
function CurrentTemplate($params)
{
return $this->is_active($params);
}
/**
* Checks if session variable
* specified by name value match
* value passed as parameter
*
* @param Array $params
* @return string
* @access public
*/
function RecallEquals($params)
{
$name = $this->SelectParam($params, 'name,var');
$value = $params['value'];
if (isset($params['persistent']) && $params['persistent']) {
return $this->Application->RecallPersistentVar($name) == $value;
}
return ($this->Application->RecallVar($name) == $value);
}
/**
* Checks if application variable
* specified by name value match
* value passed as parameter
*
* @param Array $params
* @return bool
* @access public
*/
function GetEquals($params)
{
$name = $this->SelectParam($params, 'var,name,param');
$value = $params['value'];
if ($this->Application->GetVar($name) == $value) {
return 1;
}
}
function ModuleInclude($params)
{
$ret = '';
$block_params = array_merge($params, Array('is_silent' => 2)); // don't make fatal errors in case if template is missing
$current_template = $this->Application->GetVar('t');
$replace_main = isset($params['replace_m']) && $params['replace_m'];
$skip_prefixes = isset($params['skip_prefixes']) ? explode(',', $params['skip_prefixes']) : Array();
$cms_mode = $this->Application->GetVar('admin');
$included = Array ();
foreach ($this->Application->ModuleInfo as $module_name => $module_data) {
$module_key = mb_strtolower($module_name);
if ($module_name == 'In-Portal') {
if (!$cms_mode && $this->Application->IsAdmin()) {
// don't process In-Portal templates in admin
continue;
}
// Front-End still relies on In-Portal module
$module_prefix = $module_data['TemplatePath'];
}
elseif ($this->Application->IsAdmin()) {
$module_prefix = $module_data['Path']; // was $module_key . '/';
}
else {
$module_prefix = $module_data['TemplatePath']; // always have trailing "/"
}
if (in_array($module_prefix, $included)) {
// template by this path was already included by other module (e.g. in-portal used core's template)
continue;
}
$block_params['t'] = $module_prefix.$this->SelectParam($params, $module_key.'_template,'.$module_key.'_t,template,t');
$check_prefix = $module_data['Var'];
if ($check_prefix == 'adm' && $replace_main) {
$check_prefix = 'c';
}
if ($block_params['t'] == $current_template || in_array($check_prefix, $skip_prefixes)) {
continue;
}
$no_data = $this->SelectParam($params, $module_key.'_block_no_data,block_no_data');
if ($no_data) {
$block_params['block_no_data'] = $module_prefix.'/'.$no_data;
}
$ret .= $this->Application->Parser->IncludeTemplate($block_params, isset($block_params['is_silent']) ? 1 : 0);
$included[] = $module_prefix;
}
return $ret;
}
function ModuleEnabled($params)
{
return $this->Application->isModuleEnabled( $params['module'] );
}
/**
* Checks if debug mode is on
*
* @param Array $params
* @return bool
* @access public
*/
function IsDebugMode($params)
{
return defined('DEBUG_MODE') && $this->Application->isDebugMode();
}
/*function MassParse($params)
{
$qty = $params['qty'];
$block = $params['block'];
$mode = $params['mode'];
$o = '';
if ($mode == 'func') {
$func = create_function('$params', '
$o = \'<tr>\';
$o.= \'<td>a\'.$params[\'param1\'].\'</td>\';
$o.= \'<td>a\'.$params[\'param2\'].\'</td>\';
$o.= \'<td>a\'.$params[\'param3\'].\'</td>\';
$o.= \'<td>a\'.$params[\'param4\'].\'</td>\';
$o.= \'</tr>\';
return $o;
');
for ($i=1; $i<$qty; $i++) {
$block_params['param1'] = rand(1, 10000);
$block_params['param2'] = rand(1, 10000);
$block_params['param3'] = rand(1, 10000);
$block_params['param4'] = rand(1, 10000);
$o .= $func($block_params);
}
return $o;
}
$block_params['name'] = $block;
for ($i=0; $i<$qty; $i++) {
$block_params['param1'] = rand(1, 10000);
$block_params['param2'] = rand(1, 10000);
$block_params['param3'] = rand(1, 10000);
$block_params['param4'] = rand(1, 10000);
$block_params['passed'] = $params['passed'];
$block_params['prefix'] = 'm';
$o.= $this->Application->ParseBlock($block_params, 1);
}
return $o;
}*/
function LoggedIn($params)
{
return $this->Application->LoggedIn();
}
/**
* Allows to check if permission exists directly in template and perform additional actions if required
*
* @param Array $params
* @return bool
*/
function CheckPermission($params)
{
$perm_helper =& $this->Application->recallObject('PermissionsHelper');
return $perm_helper->TagPermissionCheck($params);
}
/**
* Checks if user is logged in and if not redirects it to template passed
*
* @param Array $params
*/
function RequireLogin($params)
{
$t = $this->Application->GetVar('t');
if ($next_t = getArrayValue($params, 'next_template')) {
$t = $next_t;
}
// check by permissions: begin
if ((isset($params['perm_event']) && $params['perm_event']) ||
(isset($params['perm_prefix']) && $params['perm_prefix']) ||
(isset($params['permissions']) && $params['permissions'])) {
$perm_helper =& $this->Application->recallObject('PermissionsHelper');
/* @var $perm_helper kPermissionsHelper */
$perm_status = $perm_helper->TagPermissionCheck($params);
if (!$perm_status) {
list($redirect_template, $redirect_params) = $perm_helper->getPermissionTemplate($params);
$this->Application->Redirect($redirect_template, $redirect_params);
}
else {
return ;
}
}
// check by permissions: end
// check by configuration value: begin
$condition = getArrayValue($params, 'condition');
if (!$condition) {
$condition = true;
}
else {
if (substr($condition, 0, 1) == '!') {
$condition = !$this->Application->ConfigValue(substr($condition, 1));
}
else {
$condition = $this->Application->ConfigValue($condition);
}
}
// check by configuration value: end
// check by belonging to group: begin
$group = $this->SelectParam($params, 'group');
$group_access = true;
if ($group) {
$conn =& $this->Application->GetADODBConnection();
$group_id = $conn->GetOne('SELECT GroupId FROM '.TABLE_PREFIX.'PortalGroup WHERE Name = '.$conn->qstr($group));
if ($group_id) {
$groups = explode(',', $this->Application->RecallVar('UserGroups'));
$group_access = in_array($group_id, $groups);
}
}
// check by belonging to group: end
if ((!$this->Application->LoggedIn() || !$group_access) && $condition) {
$redirect_params = $this->Application->HttpQuery->getRedirectParams(true);
$redirect_params['next_template'] = $t;
if (array_key_exists('pass_category', $params)) {
$redirect_params['pass_category'] = $params['pass_category'];
}
if ( $this->Application->LoggedIn() && !$group_access) {
$this->Application->Redirect( $params['no_group_perm_template'], $redirect_params);
}
$this->Application->Redirect($params['login_template'], $redirect_params);
}
}
function IsMember($params)
{
$group = getArrayValue($params, 'group');
$conn =& $this->Application->DB;
$group_id = $conn->GetOne('SELECT GroupId FROM '.TABLE_PREFIX.'PortalGroup WHERE Name = '.$conn->qstr($group));
if ($group_id) {
$groups = explode(',', $this->Application->RecallVar('UserGroups'));
$group_access = in_array($group_id, $groups);
}
return $group_access;
}
/**
* Checks if SSL is on and redirects to SSL URL if needed
* If SSL_URL is not defined in config - the tag does not do anything
* If for_logged_in_only="1" exits if user is not logged in.
* If called without params forces https right away. If called with by_config="1" checks the
* Require SSL setting from General Config and if it is ON forces https
*
* @param unknown_type $params
*/
function CheckSSL($params)
{
$ssl = $this->Application->IsAdmin() ? $this->Application->ConfigValue('AdminSSL_URL') : false;
if (!$ssl) {
// not in admin or admin ssl url is empty
$ssl = $this->Application->ConfigValue('SSL_URL');
}
if (!$ssl) return; //SSL URL is not set - no way to require SSL
$require = false;
if (isset($params['mode']) && $params['mode'] == 'required') {
$require = true;
if (isset($params['for_logged_in_only']) && $params['for_logged_in_only'] && !$this->Application->LoggedIn()) {
$require = false;
}
if (isset($params['condition'])) {
if (!$this->Application->ConfigValue($params['condition'])) {
$require = false;
}
}
}
$http_query =& $this->Application->recallObject('HTTPQuery');
$pass = $http_query->getRedirectParams();
if ($require) {
if (PROTOCOL == 'https://') {
$this->Application->SetVar('__KEEP_SSL__', 1);
return;
}
$this->Application->Redirect('', array_merge_recursive2($pass, Array('__SSL__' => 1)));
}
else {
if (PROTOCOL == 'https://' && $this->Application->ConfigValue('Force_HTTP_When_SSL_Not_Required')) {
if ($this->Application->GetVar('__KEEP_SSL__')) return;
// $pass_more = Array ('pass' => 'm', 'm_cat_id' => 0, '__SSL__' => 0);
$this->Application->Redirect('', array_merge_recursive2($pass, Array('__SSL__' => 0))); // $pass_more
}
}
}
function ConstOn($params)
{
$name = $this->SelectParam($params,'name,const');
return constOn($name);
}
function SetDefaultCategory($params)
{
$category_id = $this->Application->findModule('Name', $params['module'], 'RootCat');
$this->Application->SetVar('m_cat_id', $category_id);
}
function XMLTemplate($params)
{
safeDefine('DBG_SKIP_REPORTING', 1);
if (isset($params['cache']) && $params['cache']) {
$nextyear = intval(date('Y') + 1);
$format = "D, d M Y H:i:s";
$expiration = gmdate($format, mktime() + $params['cache']).' GMT';
$last_modified = mktime();
header ('Cache-Control: public, cache, max-age='.$params['cache']);
header ("Expires: $expiration");
header ('Pragma: public');
// Getting headers sent by the client.
$headers = request_headers();
// Checking if the client is validating his cache and if it is current.
if (isset($headers['If-Modified-Since']) && (strtotime($headers['If-Modified-Since']) > $last_modified-$params['cache'])) {
// Client's cache IS current, so we just respond '304 Not Modified'.
header('Last-Modified: '.date($format, strtotime($headers['If-Modified-Since'])).' GMT', true, 304);
exit();
} else {
// Image not cached or cache outdated, we respond '200 OK' and output the image.
header('Last-Modified: '.gmdate($format, $last_modified).' GMT', true, 200);
}
}
// xml documents are usually long
set_time_limit(0);
ini_set('memory_limit', -1);
return $this->Application->XMLHeader(getArrayValue($params, 'xml_version'));
}
function Header($params)
{
header($params['data']);
}
function NoDebug($params)
{
if (!$this->Application->GetVar('debug')) {
define('DBG_SKIP_REPORTING', 1);
}
}
function RootCategoryName($params)
{
$phrase_name = $this->Application->ConfigValue('Root_Name');
$no_editing = array_key_exists('no_editing', $params) && $params['no_editing'];
return $this->Application->Phrase($phrase_name, !$no_editing);
}
/**
* Allows to attach file directly from email event template
*
* @param Array $params
*/
function AttachFile($params)
{
$esender =& $application->recallObject('EmailSender'.(isset($params['special']) ? '.'.$params['special'] : ''));
/* @var $esender kEmailSendingHelper */
$path = FULL_PATH.'/'.$params['path'];
if (file_exists($path)) {
$esender->AddAttachment($path);
}
}
function CaptchaImage($params)
{
$this->NoDebug($params);
$this->Application->SetVar('skip_last_template', 1);
$captcha_helper =& $this->Application->recallObject('CaptchaHelper');
/* @var $captcha_helper kCaptchaHelper */
// generate captcha code
$code = $captcha_helper->prepareCode( $this->Application->GetVar('var') );
$captcha_helper->GenerateCaptchaImage($code, $this->Application->GetVar('w'), $this->Application->GetVar('h'), true);
}
function SID($params)
{
return $this->Application->GetSID();
}
function ModuleInfo($params)
{
return $this->Application->findModule($params['key'], $params['value'], $params['return']);
}
function Random($params)
{
return rand(1, 100000000);
}
/**
* Prints parser params, available at current deep level
*
* @param Array $params
* @return string
*/
function PrintCurrentParams($params)
{
$current_params = $this->Application->Parser->Params;
foreach ($current_params as $param_name => $param_value) {
$current_params[$param_name] = $param_name . ' = "' . $param_value . '"';
}
return '<pre>' . implode("\n", $current_params) . '</pre>';
}
/**
* Gets previously defined counter result
*
* @param Array $params
* @return int
*/
function GetCounter($params)
{
return $this->Application->getCounter($params['name'], $params);
}
/**
* Increments PageHit counter
*
* @param Array $params
* @return int
*/
function RegisterPageHit($params)
{
if ($this->Application->ConfigValue('UsePageHitCounter')) {
$db =& $this->Application->GetADODBConnection();
// get current counte
$sql = 'SELECT VariableValue
FROM '.TABLE_PREFIX.'ConfigurationValues
WHERE VariableName = "PageHitCounter"';
$page_counter = (int)$db->GetOne($sql);
$sql = 'UPDATE LOW_PRIORITY '.TABLE_PREFIX.'ConfigurationValues
SET VariableValue = '.($page_counter + 1).'
WHERE VariableName = "PageHitCounter"';
$db->Query($sql);
}
}
function Timestamp($params)
{
$format = isset($params['format']) ? $params['format'] : 'd.m.Y H:i:s';
return adodb_date($format);
}
}
Index: branches/5.0.x/core/kernel/nparser/nparser.php
===================================================================
--- branches/5.0.x/core/kernel/nparser/nparser.php (revision 12703)
+++ branches/5.0.x/core/kernel/nparser/nparser.php (revision 12704)
@@ -1,726 +1,743 @@
<?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.net/license/ for copyright notices and details.
*/
defined('FULL_PATH') or die('restricted access!');
include_once(KERNEL_PATH.'/nparser/ntags.php');
define('TAG_NAMESPACE', 'inp2:');
define('TAG_NAMESPACE_LENGTH', 5);
class NParser extends kBase {
var $Stack = array();
var $Level = 0;
var $Buffers = array();
var $InsideComment = false;
var $Params = array();
var $ParamsStack = array();
var $ParamsLevel = 0;
var $Definitions = '';
var $Elements = array(); // holds dynamic elements to function names mapping during execution
/**
* Holds location of element definitions inside templates.
* key - element function name, value - array of 2 keys: {from_pos, to_pos}
*
* @var Array
*/
var $ElementLocations = Array ();
var $DataExists = false;
var $TemplateName = null;
var $TempalteFullPath = null;
var $CachePointers = array();
var $Cachable = array();
-
+
+ /**
+ * Parser parameter names, that are created via m_Capture tag are listed here
+ *
+ * @var Array
+ */
+ var $Captures = array();
+
/**
* Phrases, used on "Edit" buttons, that parser adds during block decoration
*
* @var Array
*/
var $_btnPhrases = Array ();
function NParser()
{
parent::kBase();
if (EDITING_MODE == EDITING_MODE_DESIGN) {
$this->_btnPhrases['design'] = $this->Application->Phrase('la_btn_EditDesign', false);
$this->_btnPhrases['block'] = $this->Application->Phrase('la_btn_EditBlock', false);
}
}
function Compile($pre_parsed, $template_name = 'unknown')
{
$data = file_get_contents($pre_parsed['tname']);
if (!$this->CompileRaw($data, $pre_parsed['tname'], $template_name)) {
// compilation failed during errors in template
// trigger_error('Template "<strong>' . $template_name . '</strong>" not compiled because of errors', E_USER_WARNING);
return false;
}
// saving compiled version (only when compilation was successful)
$this->Application->TemplatesCache->saveTemplate($pre_parsed['fname'], $this->Buffers[0]);
return true;
}
function Parse($raw_template, $name = null)
{
$this->CompileRaw($raw_template, $name);
ob_start();
$_parser =& $this;
eval('?'.'>'.$this->Buffers[0]);
return ob_get_clean();
}
function CompileRaw($data, $t_name, $template_name = 'unknown')
{
$code = "extract (\$_parser->Params);\n";
$code .= "\$_parser->ElementLocations['{$template_name}'] = Array('template' => '{$template_name}', 'start_pos' => 0, 'end_pos' => " . strlen($data) . ");\n";
// $code .= "__@@__DefinitionsMarker__@@__\n";
// $code .= "if (!\$this->CacheStart('".abs(crc32($t_name))."_0')) {\n";
$this->Buffers[0] = '<?'."php $code ?>\n";
$this->Cacheable[0] = true;
$this->Definitions = '';
// finding all the tags
$reg = '(.*?)(<[\\/]?)' . TAG_NAMESPACE . '([^>]*?)([\\/]?>)(\r\n){0,1}';
preg_match_all('/'.$reg.'/s', $data, $results, PREG_SET_ORDER + PREG_OFFSET_CAPTURE);
$this->InsideComment = false;
foreach ($results as $tag_data) {
$tag = array(
'opening' => $tag_data[2][0],
'tag' => $tag_data[3][0],
'closing' => $tag_data[4][0],
'line' => substr_count(substr($data, 0, $tag_data[2][1]), "\n")+1,
'pos' => $tag_data[2][1],
'file' => $t_name,
'template' => $template_name,
);
// the idea is to count number of comment openings and closings before current tag
// if the numbers do not match we inverse the status of InsideComment
if (substr_count($tag_data[1][0], '<!--') != substr_count($tag_data[1][0], '-->')) {
$this->InsideComment = !$this->InsideComment;
}
// appending any text/html data found before tag
$this->Buffers[$this->Level] .= $tag_data[1][0];
if (!$this->InsideComment) {
$tmp_tag = $this->Application->CurrentNTag;
$this->Application->CurrentNTag = $tag;
if ($this->ProcessTag($tag) === false) {
$this->Application->CurrentNTag = $tmp_tag;
return false;
}
$this->Application->CurrentNTag = $tmp_tag;
}
else {
$this->Buffers[$this->Level] .= $tag_data[2][0].$tag_data[3][0].$tag_data[4][0];
}
}
if ($this->Level > 0) {
$this->Application->handleError(E_USER_ERROR, 'Unclosed tag opened by '.$this->TagInfo($this->Stack[$this->Level]->Tag), $this->Stack[$this->Level]->Tag['file'], $this->Stack[$this->Level]->Tag['line']);
return false;
}
// appending text data after last tag (after its closing pos),
// if no tag was found at all ($tag_data is not set) - append the whole $data
$this->Buffers[$this->Level] .= isset($tag_data) ? substr($data, $tag_data[4][1]+strlen($tag_data[4][0])) : $data;
$this->Buffers[$this->Level] = preg_replace('/<!--##(.*?)##-->/s', '', $this->Buffers[$this->Level]); // remove hidden comments IB#23065
// $this->Buffers[$this->Level] .= '<?'.'php '."\n\$_parser->CacheEnd();\n}\n"." ?".">\n";
// $this->Buffers[$this->Level] = str_replace('__@@__DefinitionsMarker__@@__', $this->Definitions, $this->Buffers[$this->Level]);
return true;
}
function SplitParamsStr($params_str)
{
preg_match_all('/([\${}a-zA-Z0-9_.\\-\\\\#\\[\\]]+)=(["\']{1,1})(.*?)(?<!\\\)\\2/s', $params_str, $rets, PREG_SET_ORDER);
$values = Array();
// we need to replace all occurences of any current param $key with {$key} for correct variable substitution
foreach ($rets AS $key => $val){
$values[$val[1]] = str_replace('\\' . $val[2], $val[2], $val[3]);
}
return $values;
}
function SplitTag($tag)
{
if (!preg_match('/([^_ \t\r\n]*)[_]?([^ \t\r\n]*)[ \t\r\n]*(.*)$$/s', $tag['tag'], $parts)) {
// this is virtually impossible, but just in case
$this->Application->handleError(E_USER_ERROR, 'Incorrect tag format: '.$tag['tag'], $tag['file'], $tag['line']);
return false;
}
$splited['prefix'] = $parts[2] ? $parts[1] : '__auto__';
$splited['name'] = $parts[2] ? $parts[2] : $parts[1];
$splited['attrs'] = $parts[3];
return $splited;
}
function ProcessTag($tag)
{
$splited = $this->SplitTag($tag);
if ($splited === false) {
return false;
}
$tag = array_merge($tag, $splited);
$tag['processed'] = false;
$tag['NP'] = $this->SplitParamsStr($tag['attrs']);
$o = '';
$tag['is_closing'] = $tag['opening'] == '</' || $tag['closing'] == '/>';
if (class_exists('_Tag_'.$tag['name'])) { // block tags should have special handling class
if ($tag['opening'] == '<') {
$class = '_Tag_'.$tag['name'];
$instance = new $class($tag);
$instance->Parser =& $this;
/* @var $instance _BlockTag */
$this->Stack[++$this->Level] =& $instance;
$this->Buffers[$this->Level] = '';
$this->Cachable[$this->Level] = true;
$open_code = $instance->Open($tag);
if ($open_code === false) {
return false;
}
$o .= $open_code;
}
if ($tag['is_closing']) { // not ELSE here, because tag may be <empty/> and still has a handler-class
if ($this->Level == 0) {
$dump = array();
foreach ($this->Stack as $instance) {
$dump[] = $instance->Tag;
}
print_pre($dump);
$this->Application->handleError(E_USER_ERROR, 'Closing tag without an opening: '.$this->TagInfo($tag).' <b> - probably opening tag was removed or nested tags error</b>', $tag['file'], $tag['line']);
return false;
}
if ($this->Stack[$this->Level]->Tag['name'] != $tag['name']) {
$opening_tag = $this->Stack[$this->Level]->Tag;
$this->Application->handleError(E_USER_ERROR,
'Closing tag '.$this->TagInfo($tag).' does not match
opening tag at current nesting level ('.$this->TagInfo($opening_tag).'
opened at line '.$opening_tag['line'].')', $tag['file'], $tag['line']);
return false;
}
$o .= $this->Stack[$this->Level]->Close($tag); // DO NOT use $this->Level-- here because it's used inside Close
$this->Level--;
}
}
else { // regular tags - just compile
if (!$tag['is_closing']) {
$this->Application->handleError(E_USER_ERROR, 'Tag without a handler: '.$this->TagInfo($tag).' <b> - probably missing &lt;empty <span style="color: red">/</span>&gt; tag closing</b>', $tag['file'], $tag['line']);
return false;
}
if ($this->Level > 0) $o .= $this->Stack[$this->Level]->PassThrough($tag);
if (!$tag['processed']) {
$compiled = $this->CompileTag($tag);
if ($compiled === false) return false;
if (isset($tag['NP']['cachable']) && (!$tag['NP']['cachable'] || $tag['NP']['cachable'] == 'false')) {
$this->Cachable[$this->Level] = false;
}
$o .= '<?'.'php ' . $compiled . " ?>\n";
// $o .= '<?'.'php ';
// $o .= (isset($tag['NP']['cachable']) && (!$tag['NP']['cachable'] || $tag['NP']['cachable'] == 'false')) ? $this->BreakCache($compiled, $this->GetPointer($tag)) : $compiled;
// $o .= " ?".">\n";
}
}
$this->Buffers[$this->Level] .= $o;
return true;
}
function GetPointer($tag)
{
return abs(crc32($tag['file'])).'_'.$tag['line'];
}
function BreakCache($code, $pointer, $condition='')
{
return "\$_parser->CacheEnd();\n}\n" . $code."\nif ( !\$_parser->CacheStart('{$pointer}'" . ($condition ? ", {$condition}" : '') . ") ) {\n";
}
function TagInfo($tag, $with_params=false)
{
return "<b>{$tag['prefix']}_{$tag['name']}".($with_params ? ' '.$tag['attrs'] : '')."</b>";
}
function CompileParamsArray($arr)
{
$to_pass = 'Array(';
foreach ($arr as $name => $val) {
$to_pass .= '"'.$name.'" => "'.str_replace('"', '\"', $val).'",';
}
$to_pass .= ')';
return $to_pass;
}
function CompileTag($tag)
{
- $to_pass = $this->CompileParamsArray($tag['NP']);
-
$code = '';
+ $to_pass = $this->CompileParamsArray($tag['NP']);
+
if ($tag['prefix'] == '__auto__') {
$prefix = $this->GetParam('PrefixSpecial');
$code .= '$_p_ =& $_parser->GetProcessor($PrefixSpecial);'."\n";
$code .= 'echo $_p_->ProcessParsedTag(\''.$tag['name'].'\', '.$to_pass.', "$PrefixSpecial", \''.$tag['file'].'\', '.$tag['line'].');'."\n";
}
else {
$prefix = $tag['prefix'];
$code .= '$_p_ =& $_parser->GetProcessor("'.$tag['prefix'].'");'."\n";
$code .= 'echo $_p_->ProcessParsedTag(\''.$tag['name'].'\', '.$to_pass.', "'.$tag['prefix'].'", \''.$tag['file'].'\', '.$tag['line'].');'."\n";
}
- if (isset($tag['NP']['result_to_var'])) {
+
+ if (array_key_exists('result_to_var', $tag['NP']) && $tag['NP']['result_to_var']) {
$code .= "\$params['{$tag['NP']['result_to_var']}'] = \$_parser->GetParam('{$tag['NP']['result_to_var']}');\n";
$code .= "\${$tag['NP']['result_to_var']} = \$params['{$tag['NP']['result_to_var']}'];\n";
}
+
if ($prefix && strpos($prefix, '$') === false) {
$p =& $this->GetProcessor($prefix);
if (!is_object($p) || !$p->CheckTag($tag['name'], $tag['prefix'])) {
$this->Application->handleError(E_USER_ERROR, 'Unknown tag: '.$this->TagInfo($tag).' <b> - incorrect tag name or prefix </b>', $tag['file'], $tag['line']);
return false;
}
}
+
return $code;
}
function CheckTemplate($t, $silent = null)
{
$pre_parsed = $this->Application->TemplatesCache->GetPreParsed($t);
if (!$pre_parsed) {
if (!$silent) {
if ($this->Application->isDebugMode()) {
$this->Application->Debugger->appendTrace();
}
trigger_error('Cannot include "<strong>' . $t . '</strong>" - file does not exist', E_USER_ERROR);
}
return false;
}
$force_compile = defined('DBG_NPARSER_FORCE_COMPILE') && DBG_NPARSER_FORCE_COMPILE;
if (!$pre_parsed || !$pre_parsed['active'] || $force_compile) {
$inc_parser = new NParser();
if ($force_compile) {
// remove Front-End theme markings during total compilation
$t = preg_replace('/^theme:.*?\//', '', $t);
}
if (!$inc_parser->Compile($pre_parsed, $t)) {
return false;
}
}
return $pre_parsed;
}
function Run($t, $silent = null)
{
if ((strpos($t, '../') !== false) || (trim($t) !== $t)) {
// when relative paths or special chars are found template names from url, then it's hacking attempt
return false;
}
$pre_parsed = $this->CheckTemplate($t, $silent);
if (!$pre_parsed) {
return false;
}
$backup_template = $this->TemplateName;
$backup_fullpath = $this->TempalteFullPath;
$this->TemplateName = $t;
$this->TempalteFullPath = $pre_parsed['tname'];
$output =& $this->Application->TemplatesCache->runTemplate($this, $pre_parsed);
$this->TemplateName = $backup_template;
$this->TempalteFullPath = $backup_fullpath;
return $output;
}
function &GetProcessor($prefix)
{
static $Processors = array();
if (!isset($Processors[$prefix])) {
$Processors[$prefix] = $this->Application->recallObject($prefix.'_TagProcessor');
}
return $Processors[$prefix];
}
function SelectParam($params, $possible_names)
{
if (!is_array($params)) return;
if (!is_array($possible_names))
$possible_names = explode(',', $possible_names);
foreach ($possible_names as $name)
{
if( isset($params[$name]) ) return $params[$name];
}
return false;
}
function SetParams($params)
{
$this->Params = $params;
$keys = array_keys($this->Params);
}
function GetParam($name)
{
return isset($this->Params[$name]) ? $this->Params[$name] : false;
}
function SetParam($name, $value)
{
$this->Params[$name] = $value;
}
function PushParams($params)
{
$this->ParamsStack[$this->ParamsLevel++] = $this->Params;
$this->Params = $params;
}
function PopParams()
{
$this->Params = $this->ParamsStack[--$this->ParamsLevel];
}
function ParseBlock($params, $pass_params=false)
{
if (isset($params['cache_timeout']) && ($ret = $this->CacheGet($this->FormCacheKey('element_'.$params['name'])))) {
return $ret;
}
if (substr($params['name'], 0, 5) == 'html:') {
return substr($params['name'], 6);
}
if (!array_key_exists($params['name'], $this->Elements) && array_key_exists('default_element', $params)) {
// when given element not found, but default element name given, then render it instead
$params['name'] = $params['default_element'];
unset($params['default_element']);
return $this->ParseBlock($params, $pass_params);
}
$original_params = $params;
if ($pass_params || isset($params['pass_params'])) $params = array_merge($this->Params, $params);
$this->PushParams($params);
$data_exists_bak = $this->DataExists;
// if we are parsing design block and we have block_no_data - we need to wrap block_no_data into design,
// so we should set DataExists to true manually, otherwise the design block will be skipped because of data_exists in params (by Kostja)
//
// keep_data_exists is used by block RenderElement (always added in ntags.php), to keep the DataExists value
// from inside-content block, otherwise when parsing the design block DataExists will be reset to false resulting missing design block (by Kostja)
//
// Inside-content block parsing result is given to design block in "content" parameter (ntags.php) and "keep_data_exists"
// is only passed, when parsing design block. In case, when $this->DataExists is set to true, but
// zero-length content (in 2 cases: method NParser::CheckNoData set it OR really empty block content)
// is returned from inside-content block, then design block also should not be shown (by Alex)
$this->DataExists = (isset($params['keep_data_exists']) && isset($params['content']) && $params['content'] != '' && $this->DataExists) || (isset($params['design']) && isset($params['block_no_data']) && $params['name'] == $params['design']);
if (!array_key_exists($params['name'], $this->Elements)) {
$pre_parsed = $this->Application->TemplatesCache->GetPreParsed($params['name']);
if ($pre_parsed) {
$ret = $this->IncludeTemplate($params);
if (array_key_exists('no_editing', $params) && $params['no_editing']) {
// when individual render element don't want to be edited
return $ret;
}
return defined('EDITING_MODE') ? $this->DecorateBlock($ret, $params, true) : $ret;
}
if ($this->Application->isDebugMode()) {
$this->Application->Debugger->appendTrace();
}
$trace_results = debug_backtrace();
$this->Application->handleError(E_USER_ERROR, '<b>Rendering of undefined element '.$params['name'].'</b>', $trace_results[0]['file'], $trace_results[0]['line']);
return false;
}
$m_processor =& $this->GetProcessor('m');
$flag_values = $m_processor->PreparePostProcess($params);
$f_name = $this->Elements[$params['name']];
$ret = $f_name($this, $params);
$ret = $m_processor->PostProcess($ret, $flag_values);
$block_params = $this->Params; // input parameters, but modified inside rendered block
$this->PopParams();
+ if (array_key_exists('result_to_var', $flag_values) && $flag_values['result_to_var']) {
+ // when "result_to_var" used inside ParseBlock, then $$result_to_var parameter is set inside ParseBlock,
+ // but not outside it as expected and got lost at all after PopParams is called, so make it work by
+ // setting it's value on current parameter deep level (from where ParseBlock was called)
+ $this->SetParam($flag_values['result_to_var'], $block_params[ $flag_values['result_to_var'] ]);
+ }
+
$this->CheckNoData($ret, $params);
$this->DataExists = $data_exists_bak || $this->DataExists;
if (isset($original_params['cache_timeout'])) {
$this->CacheSet($this->FormCacheKey('element_'.$original_params['name']), $ret, $original_params['cache_timeout']);
}
if (array_key_exists('no_editing', $block_params) && $block_params['no_editing']) {
// when individual render element don't want to be edited
return $ret;
}
return defined('EDITING_MODE') ? $this->DecorateBlock($ret, $params) : $ret;
}
function DecorateBlock($block_content, $block_params, $is_template = false)
{
static $used_ids = Array (), $base_url = null;
if (!isset($base_url)) {
$base_url = $this->Application->BaseURL();
}
// $prepend = '[name: ' . $block_params['name'] . '] [params: ' . implode(', ', array_keys($block_params)) . ']';
$decorate = false;
$design = false;
if (EDITING_MODE == EDITING_MODE_DESIGN) {
$decorate = true;
if ($is_template) {
// content inside pair RenderElement tag
}
else {
if (strpos($block_params['name'], '__capture_') === 0) {
// capture tag (usually inside pair RenderElement)
$decorate = false;
}
elseif (array_key_exists('content', $block_params)) {
// pair RenderElement (on template, were it's used)
$design = true;
}
}
}
if (!$decorate) {
return $block_content;
}
else {
$block_content = /*$prepend .*/ $block_content;
}
$block_name = $block_params['name'];
$function_name = $is_template ? $block_name : $this->Elements[$block_name];
$block_title = '';
if (array_key_exists($function_name, $this->Application->Parser->ElementLocations)) {
$element_location = $this->Application->Parser->ElementLocations[$function_name];
$block_title .= $element_location['template'] . '.tpl';
$block_title .= ' (' . $element_location['start_pos'] . ' - ' . $element_location['end_pos'] . ')';
}
// ensure unique id for every div (used from print lists)
$container_num = 1;
$container_id = 'parser_block[' . $function_name . ']';
while (in_array($container_id . '_' . $container_num, $used_ids)) {
$container_num++;
}
$container_id .= '_' . $container_num;
$used_ids[] = $container_id;
// prepare parameter string
$param_string = $block_name . ':' . $function_name;
if ($design) {
$btn_text = $this->_btnPhrases['design'];
$btn_class = 'cms-edit-design-btn';
$btn_container_class = 'block-edit-design-btn-container';
$btn_name = 'design';
}
else {
$btn_text = $this->_btnPhrases['block'];
$btn_class = 'cms-edit-block-btn';
$btn_container_class = 'block-edit-block-btn-container';
$btn_name = 'content';
}
$block_editor = '
<div id="' . $container_id . '" params="' . $param_string . '" class="' . $btn_container_class . '" title="' . htmlspecialchars($block_title) . '">
<div class="' . $btn_class . '">
<div class="cms-btn-image">
<img src="' . $base_url . 'core/admin_templates/img/top_frame/icons/' . $btn_name . '_mode.png" width="15" height="16" alt=""/>
</div>
<div class="cms-btn-text" id="' . $container_id . '_btn">' . $btn_text . '</div>
</div>
<div class="cms-btn-content">
%s
</div>
</div>';
// 1 - text before, 2 - open tag, 3 - open tag attributes, 4 - content inside tag, 5 - closing tag, 6 - text after closing tag
if (preg_match('/^(\s*)<(td|span)(.*?)>(.*)<\/(td|span)>(.*)$/is', $block_content, $regs)) {
// div inside span -> put div outside span
return $regs[1] . '<' . $regs[2] . ' ' . $regs[3] . '>' . str_replace('%s', $regs[4], $block_editor) . '</' . $regs[5] . '>' . $regs[6];
}
return str_replace('%s', $block_content, $block_editor);
}
function IncludeTemplate($params, $silent=null)
{
$t = is_array($params) ? $this->SelectParam($params, 't,template,block,name') : $params;
if (isset($params['cache_timeout']) && ($ret = $this->CacheGet('template:'.$t))) {
return $ret;
}
$t = preg_replace('/\.tpl$/', '', $t);
$data_exists_bak = $this->DataExists;
$this->DataExists = false;
if (!isset($silent) && array_key_exists('is_silent', $params)) {
$silent = $params['is_silent'];
}
if (isset($params['pass_params'])) {
// ability to pass params from block to template
$params = array_merge($this->Params, $params);
}
$this->PushParams($params);
$ret = $this->Run($t, $silent);
$this->PopParams();
$this->CheckNoData($ret, $params);
$this->DataExists = $data_exists_bak || $this->DataExists;
if (isset($params['cache_timeout'])) {
$this->CacheSet('template:'.$t, $ret, $params['cache_timeout']);
}
return $ret;
}
function CheckNoData(&$ret, $params)
{
if (array_key_exists('data_exists', $params) && $params['data_exists'] && !$this->DataExists) {
$block_no_data = isset($params['BlockNoData']) ? $params['BlockNoData'] : (isset($params['block_no_data']) ? $params['block_no_data'] : false);
if ($block_no_data) {
$ret = $this->ParseBlock(array('name'=>$block_no_data));
}
else {
$ret = '';
}
}
}
function CacheGet($name)
{
if (!$this->Application->ConfigValue('SystemTagCache')) return false;
return $this->Application->CacheGet($name);
}
function CacheSet($name, $value, $expiration=0)
{
if (!$this->Application->ConfigValue('SystemTagCache')) return false;
return $this->Application->CacheSet($name, $value, $expiration);
}
function FormCacheKey($element, $file=null, $add_prefixes=null)
{
if (!isset($file)) {
$file = str_replace(FULL_PATH, '', $this->TempalteFullPath).':'.$this->Application->GetVar('t');
}
$parts = array(
'file_'.$file.'('.filemtime($this->TempalteFullPath).')' => 'serials:file_ts', // theme + template timestamp
'm_lang_'.$this->Application->GetVar('m_lang') => 'serials:lang_ts',
'm_cat_id_'.$this->Application->GetVar('m_cat_id') => 'serials:cat_'.$this->Application->GetVar('m_cat_id').'_ts',
'm_cat_page'.$this->Application->GetVar('m_cat_page') => false,
);
if (isset($add_prefixes)) {
foreach ($add_prefixes as $prefix) {
$parts[$prefix.'_id_'.$this->Application->GetVar("{$prefix}_id")] = "serials:$prefix_".$this->Application->GetVar("{$prefix}_id").'_ts';
$parts[$prefix.'_page_'.$this->Application->GetVar("{$prefix}_Page")] = false;
}
}
$key = '';
foreach ($parts as $part => $ts_name) {
if ($ts_name) {
$ts = $this->Application->CacheGet($ts_name);
$key .= "$part($ts):";
}
else {
$key .= "$part:";
}
}
$key .= $element;
return crc32($key);
}
function PushPointer($pointer)
{
$this->CachePointers[++$this->CacheLevel] = $this->FormCacheKey('pointer:'.$pointer);
return $this->CachePointers[$this->CacheLevel];
}
function PopPointer()
{
return $this->CachePointers[$this->CacheLevel--];
}
function CacheStart($pointer=null)
{
if ($ret = $this->CacheGet($this->PushPointer($pointer)) ) {
echo $ret;
$this->PopPointer();
return true;
}
ob_start();
return false;
}
function CacheEnd($elem=null)
{
$ret = ob_get_clean();
$this->CacheSet($this->PopPointer(), $ret); // . ($this->CurrentKeyPart ? ':'.$this->CurrentKeyPart : '')
echo $ret;
}
}
\ No newline at end of file
Index: branches/5.0.x/core/kernel/nparser/ntags.php
===================================================================
--- branches/5.0.x/core/kernel/nparser/ntags.php (revision 12703)
+++ branches/5.0.x/core/kernel/nparser/ntags.php (revision 12704)
@@ -1,603 +1,612 @@
<?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.net/license/ for copyright notices and details.
*/
defined('FULL_PATH') or die('restricted access!');
class _BlockTag extends kBase {
/**
* Enter description here...
*
* @var NParser
*/
var $Parser = null;
var $Tag = null;
/**
* Contains parameter names, that should be given to tag in any case
*
* @var Array
*/
var $_requiredParams = Array ();
function _BlockTag($tag)
{
parent::kBase();
$this->Tag = $tag;
}
function Open($tag)
{
if (!$this->_checkRequiredParams($tag)) {
return false;
}
return '';
}
/**
* Checks, that all required attributes for tag are passed
*
* @param Array $tag
* @return bool
*/
function _checkRequiredParams($tag)
{
$missing_params = array_diff($this->_requiredParams, array_keys($tag['NP']));
if (!$missing_params) {
return true;
}
$error_msg = 'Tag ' . $this->Parser->TagInfo($tag, true) . ' called <b> without required ' . implode(', ', $missing_params) . ' </b> attribute';
if (count($missing_params) > 1) {
$error_msg .= '(-s)';
}
$this->Application->handleError(E_USER_ERROR, $error_msg, $tag['file'], $tag['line']);
return false;
}
/**
* All tags inside block tag are passed through to this method
* Any returned result is appened to current level's buffer
* This can be used to implement special handling of such tags as <inp2:m_else/>
*
* @param unknown_type $tag
* @return unknown
*/
function PassThrough(&$tag)
{
return '';
}
function Close($tag)
{
return $this->Parser->Buffers[$this->Parser->Level];
}
function AppendCode(&$o, $code, $php_tags=true)
{
if ($php_tags) {
$o .= '<?'."php\n" . ( is_array($code) ? "\t".implode("\n\t", $code)."\n" : $code) .'?>';
}
else {
$o .= ( is_array($code) ? "\t".implode("\n\t", $code)."\n" : $code);
}
}
}
class _Tag_Comment extends _BlockTag {
function PassThrough(&$tag)
{
$tag['processed'] = true;
}
function Close($tag)
{
return '';
}
}
class _Tag_DefineElement extends _BlockTag {
/*var $ElemName;
function Open($tag)
{
$o = '';
$pointer = abs(crc32($tag['file'])).'_'.$tag['line'];
$f_name = $tag['NP']['name'].'_'.$pointer;
$this->ElemName = $tag['NP']['name'];
$code[] = "\$_parser->Elements['{$tag['NP']['name']}'] = '$f_name';";
// function_exists is required here, because a template may be included more than once
// leading to Cannot redeclare error
$code[] = "if (!function_exists('{$f_name}')) {";
$code[] = "function $f_name(&\$_parser, \$params) {";
$code[] = "global \$application;";
$code[] = "if (!\$_output = \$_parser->CacheStart('{$pointer}')) {";
$defaults = $this->Parser->CompileParamsArray($tag['NP']);
$code[] = "\$params = array_merge($defaults, \$params);";
$code[] = "if (!isset(\$params['PrefixSpecial']) && isset(\$params['prefix'])) {\$params['PrefixSpecial'] = \$params['prefix'];};";
$code[] = "extract(\$params);";
$code[] = "\$_parser->SetParams(\$params);";
$code[] = 'ob_start();';
$this->AppendCode($o, $code, false);
return $o . '?'.'>';
}
function Close($tag)
{
$o = $this->Parser->Buffers[$this->Parser->Level];
$code[] = "\$_parser->CacheEnd();\n";
$code[] = '$_output = ob_get_contents();';
$code[] = 'ob_end_clean();';
$code[] = '}';
$code[] = "return \$_output === true ? '' : \$_output;";
$code[] = '}}';
$code[] = "\$_parser->CachableElements['".$this->ElemName."'] = ".($this->Parser->Cachable[$this->Parser->Level] ? 'true':'false').';';
$o .= '<?'.'php';
$this->AppendCode($o, $code, false);
return $o;
// $this->Parser->Definitions .= $o."\n";
// return '';
} */
function _Tag_DefineElement($tag)
{
parent::_BlockTag($tag);
$this->_requiredParams = Array ('name');
}
function Open($tag)
{
$o = parent::Open($tag);
if ($o === false) {
// some required params not passed
return $o;
}
$f_name = $tag['NP']['name'].'_'.abs(crc32($tag['file'])).'_'.$tag['line'];
$this->Tag['function_name'] = $f_name; // for later use in closing tag
$code[] = "\$_parser->Elements['{$tag['NP']['name']}'] = '$f_name';";
// function_exists is required here, because a template may be included more than once
// leading to Cannot redeclare error
$code[] = "if (!function_exists('{$f_name}')) {";
$code[] = "function $f_name(&\$_parser, \$params) {";
$code[] = "global \$application;";
$tag['NP'] = $this->_extractParams($tag['NP']);
$defaults = $this->Parser->CompileParamsArray($tag['NP']);
$code[] = "\$params = array_merge($defaults, \$params);";
$code[] = "if (!isset(\$params['PrefixSpecial']) && isset(\$params['prefix'])) {\$params['PrefixSpecial'] = \$params['prefix'];};";
$code[] = "extract(\$params);";
$code[] = "\$_parser->SetParams(\$params);";
$code[] = 'ob_start();';
$this->AppendCode($o, $code);
return $o;
}
/**
* Converts $param_name to $params['param_name']
*
* @param Array $params
* @return Array
*/
function _extractParams($params)
{
foreach ($params as $param_name => $param_value) {
$params[$param_name] = preg_replace('/[\{]{0,1}([\$])(.*?[^\$\s\{\}]*)[\}]{0,1}/', '{$params[\'\\2\']}', $param_value);
}
return $params;
}
function Close($tag)
{
$o = $this->Parser->Buffers[$this->Parser->Level];
$code[] = '$_output = ob_get_contents();';
$code[] = 'ob_end_clean();';
$code[] = 'return $_output;';
$code[] = '}}';
$end_pos = $tag['pos'] + strlen($tag['opening']) + strlen($tag['tag']) + strlen($tag['closing']) + TAG_NAMESPACE_LENGTH;
$code[] = "\$_parser->ElementLocations['{$this->Tag['function_name']}'] = Array('template' => '{$this->Tag['template']}', 'start_pos' => {$this->Tag['pos']}, 'end_pos' => {$end_pos});";
$this->AppendCode($o, $code);
return $o;
}
}
class _Tag_Capture extends _Tag_DefineElement {
function _Tag_Capture($tag)
{
parent::_Tag_DefineElement($tag);
$this->_requiredParams = Array ('to_var');
}
function Open($tag)
{
if (!$this->_checkRequiredParams($tag)) {
return false;
}
$tag['NP']['name'] = '__capture_'.$tag['NP']['to_var'];
$o = '';
// $this->AppendCode($o, "\$_parser->Captures['{$tag['NP']['to_var']}'] = 1;", false);
$this->AppendCode($o, "\$_parser->Captures['{$tag['NP']['to_var']}'] = 1;");
$o .= parent::Open($tag);
return $o;
}
}
class _Tag_RenderElement extends _Tag_DefineElement {
var $Single = true;
var $OriginalTag;
var $_lambdaName = '';
function _Tag_RenderElement($tag)
{
parent::_Tag_DefineElement($tag);
if (!$tag['is_closing']) {
$this->_requiredParams = Array ('design');
}
}
function Open($tag)
{
if (!$this->_checkRequiredParams($tag)) {
return false;
}
$o = '';
if ($tag['is_closing']) {
if (isset($tag['NP']['design'])) {
$this->RenderDesignCode($o, $tag['NP']);
return $o;
}
$to_pass = $this->Parser->CompileParamsArray($tag['NP']);
/* $pointer = abs(crc32($tag['file'])).'_'.$tag['line'];
// $code[] = "}";
// $code[] = "if (!\$_parser->CachableElements['".$tag['NP']['name']."']) {";
// $code[] = "\$_parser->CacheEndInside();";
// $code[] = "}";
$o .= '<?'.'php ';
$this->AppendCode($o, $this->Parser->BreakCache('', $pointer.'a', "\$_parser->CachableElements['".$tag['NP']['name']."']"), false);
$this->AppendCode($o, "echo (\$_parser->ParseBlock($to_pass));\n", false);
$this->AppendCode($o, $this->Parser->BreakCache('', $pointer.'b') . " ?".">\n", false);
// $this->AppendCode($o, "if (!\$_parser->CacheStartOrContinue(\$_parser->CachableElements['".$tag['NP']['name']."'], '{$pointer}')) {".' ?'.'>', false);
*/
$this->AppendCode($o, "echo (\$_parser->ParseBlock($to_pass));");
return $o;
}
$this->Single = false;
$this->OriginalTag = $tag;
$tag['NP']['name'] = $tag['NP']['design'] . '_' . abs(crc32($tag['file'])) . '_' . $tag['line']; //'__lambda';
return parent::Open($tag);
}
function RenderDesignCode(&$o, $params)
{
$to_pass = $this->Parser->CompileParamsArray($params);
$code[] = "echo (\$_parser->ParseBlock(array_merge($to_pass, array('name'=>\"{$params['design']}\",'content'=>\$_parser->ParseBlock($to_pass), 'keep_data_exists'=>1))));";
$this->AppendCode($o, $code);
}
function Close($tag)
{
if ($this->Single) {
return $this->Parser->Buffers[$this->Parser->Level];
}
$o = parent::Close($tag);
$this->OriginalTag['NP']['name'] = $this->OriginalTag['NP']['design'] . '_' . abs(crc32($this->OriginalTag['file'])) . '_' . $this->OriginalTag['line']; //'__lambda';
$this->RenderDesignCode($o, $this->OriginalTag['NP']);
return $o;
}
}
class _Tag_RenderElements extends _BlockTag {
function _Tag_RenderElements($tag)
{
parent::_BlockTag($tag);
$this->_requiredParams = Array ('elements');
}
function Open($tag)
{
$o = parent::Open($tag);
if ($o === false) {
// some required params not passed
return $o;
}
$element_names = array_map('trim', explode(',', $tag['NP']['elements']));
unset($tag['NP']['elements']);
$class = '_Tag_RenderElement';
$instance = new $class($tag);
/* @var $instance _Tag_RenderElement */
$instance->Parser =& $this->Parser;
$skip_elements = array_key_exists('skip', $tag['NP']) ? array_map('trim', explode(',', $tag['NP']['skip'])) : Array ();
foreach ($element_names as $element_name) {
if (in_array($element_name, $skip_elements) || !$element_name) {
// empty element name OR element should be excluded
continue;
}
$tag['NP']['name'] = $element_name;
$o .= $instance->Open($tag);
}
return $o;
}
}
class _Tag_Param extends _BlockTag {
function _Tag_Param($tag)
{
parent::_BlockTag($tag);
$this->_requiredParams = Array ('name');
}
function Open($tag)
{
$o = parent::Open($tag);
if ($o === false) {
// some required params not passed
return $o;
}
$capture_params = $tag['NP'];
$capture_params['name'] = '__capture_' . $tag['NP']['name'];
$capture_to_pass = $this->Parser->CompileParamsArray($capture_params);
$code[] = "if (isset(\$_parser->Captures['{$tag['NP']['name']}'])) {";
$code[] = "\${$tag['NP']['name']} = \$_parser->ParseBlock($capture_to_pass);";
$code[] = "}";
$code[] = "else {";
$to_pass = $this->Parser->CompileParamsArray($tag['NP']);
$code[] = '$_p_ =& $_parser->GetProcessor(\'m\');';
$code[] = '$_tag_params = ' . $to_pass . ';';
$code[] = "\${$tag['NP']['name']} = \$_p_->PostProcess(\${$tag['NP']['name']}, \$_p_->PreparePostProcess(\$_tag_params));";
$code[] = "}";
-
- if (array_key_exists('plus', $tag['NP'])) {
+
+ if (array_key_exists('result_to_var', $tag['NP']) && $tag['NP']['result_to_var']) {
+ $code[] = "\$params['{$tag['NP']['result_to_var']}'] = \$_parser->GetParam('{$tag['NP']['result_to_var']}');";
+
+ if (array_key_exists('plus', $tag['NP'])) {
+ $code[] = "\$params['{$tag['NP']['result_to_var']}'] += {$tag['NP']['plus']};";
+ }
+
+ $code[] = "\${$tag['NP']['result_to_var']} = \$params['{$tag['NP']['result_to_var']}'];";
+ }
+ elseif (array_key_exists('plus', $tag['NP'])) {
$code[] = "\${$tag['NP']['name']} += {$tag['NP']['plus']};";
}
$code[] = "\$params['{$tag['NP']['name']}'] = \${$tag['NP']['name']};";
$code[] = "echo (\${$tag['NP']['name']});";
$this->AppendCode($o, $code);
return $o;
}
}
class _Tag_Include extends _BlockTag {
function Open($tag)
{
$o = '';
$to_pass = $this->Parser->CompileParamsArray($tag['NP']);
$this->AppendCode($o, "echo (\$_parser->IncludeTemplate($to_pass))");
return $o;
}
}
class _Tag_If extends _BlockTag {
/**
* Permanently inverses if tag (used in ifnot tag)
*
* @var bool
*/
var $_Inversed = false;
/**
* Count of "elseif" tags inside
*
* @var int
*/
var $_elseIfCount = 0;
function _Tag_If($tag)
{
parent::_BlockTag($tag);
$this->_requiredParams = Array ('check');
}
function Open($tag)
{
$o = parent::Open($tag);
if ($o === false) {
// some required params not passed
return $o;
}
$to_pass = $this->Parser->CompileParamsArray($tag['NP']);
$code[] = "\$_splited = \$_parser->SplitTag(array('tag'=>\"{$tag['NP']['check']}\", 'file'=>'{$tag['file']}', 'line'=>{$tag['line']}));";
$code[] = 'if ($_splited[\'prefix\'] == \'__auto__\') {$_splited[\'prefix\'] = $PrefixSpecial;}';
$code[] = '$_p_ =& $_parser->GetProcessor($_splited[\'prefix\']);';
if (isset($tag['NP']['inverse']) || $this->_Inversed) {
$code[] = "if (!\$_p_->ProcessParsedTag(\$_splited['name'], $to_pass, \$_splited['prefix'], '{$tag['file']}', {$tag['line']})) {";
}
else {
$code[] = "if (\$_p_->ProcessParsedTag(\$_splited['name'], $to_pass, \$_splited['prefix'], '{$tag['file']}', {$tag['line']})) {";
}
$this->AppendCode($o, $code);
return $o;
}
function PassThrough(&$tag)
{
$o = '';
if ($tag['name'] == 'else') {
$this->AppendCode($o, '} else {');
$tag['processed'] = true;
}
if ($tag['name'] == 'elseif') {
if (!$this->_checkRequiredParams($tag)) {
return '';
}
$to_pass = $this->Parser->CompileParamsArray($tag['NP']);
$this->_elseIfCount++; // add same count of closing brackets in closing tag
$this->AppendCode($o, "} else {");
$code[] = "\$_splited = \$_parser->SplitTag(array('tag'=>\"{$tag['NP']['check']}\", 'file'=>'{$tag['file']}', 'line'=>{$tag['line']}));";
$code[] = 'if ($_splited[\'prefix\'] == \'__auto__\') {$_splited[\'prefix\'] = $PrefixSpecial;}';
$code[] = '$_p_ =& $_parser->GetProcessor($_splited[\'prefix\']);';
if (isset($tag['NP']['inverse']) || $this->_Inversed) {
$code[] = "if (!\$_p_->ProcessParsedTag(\$_splited['name'], $to_pass, \$_splited['prefix'], '{$tag['file']}', {$tag['line']})) {";
}
else {
$code[] = "if (\$_p_->ProcessParsedTag(\$_splited['name'], $to_pass, \$_splited['prefix'], '{$tag['file']}', {$tag['line']})) {";
}
$this->AppendCode($o, $code);
$tag['processed'] = true;
}
return $o;
}
function Close($tag)
{
$o = $this->Parser->Buffers[$this->Parser->Level];
$code = str_repeat("}\n", $this->_elseIfCount + 1);
$this->AppendCode($o, $code);
return $o;
}
}
class _Tag_IfNot extends _Tag_If {
function _Tag_IfNot($tag)
{
parent::_Tag_If($tag);
$this->_Inversed = true;
}
}
class _Tag_DefaultParam extends _BlockTag {
function Open($tag)
{
$o = '';
foreach ($tag['NP'] as $key => $val) {
$code[] = 'if (!isset($' . $key . ')) $params[\'' . $key . '\'] = \'' . $val . '\';';
$code[] = '$' . $key . ' = isset($' . $key . ') ? $' . $key . ' : \'' . $val . '\';';
$code[] = '$_parser->SetParam(\'' . $key . '\', $' . $key . ');';
}
$this->AppendCode($o, $code);
return $o;
}
}
class _Tag_SetParam extends _BlockTag {
function Open($tag)
{
$o = '';
foreach ($tag['NP'] as $key => $val) {
$code[] = '$params[\'' . $key . '\'] = \'' . $val . '\';';
$code[] = '$' . $key . ' = \'' . $val . '\';';
$code[] = '$_parser->SetParam(\'' . $key . '\', $' . $key . ');';
}
$this->AppendCode($o, $code);
return $o;
}
}
class _Tag_Cache extends _BlockTag {
function Open($tag)
{
$pointer = abs(crc32($tag['file'])).'_'.$tag['line'];
$o = '';
$this->AppendCode($o, "if (!\$_parser->CacheStart('{$pointer}')) {\n");
return $o;
}
function Close($tag)
{
$o = $this->Parser->Buffers[$this->Parser->Level];
$this->AppendCode($o, "\$_parser->CacheEnd();\n}\n");
return $o;
}
}
class _Tag_IfDataExists extends _BlockTag {
function Open($tag)
{
$o = '';
$code = array();
$code[] = "ob_start();\n";
$code[] = '$_tmp_data_exists = $_parser->DataExists;';
$code[] = '$_parser->DataExists = false;';
$this->AppendCode($o, $code);
return $o;
}
function Close($tag)
{
$o = $this->Parser->Buffers[$this->Parser->Level];
$code = array();
$code[] = '$res = ob_get_clean();';
$code[] = 'if ($_parser->DataExists) {echo $res;}';
$code[] = '$_parser->DataExists = $_tmp_data_exists;';
$this->AppendCode($o, $code);
return $o;
}
}
\ No newline at end of file

Event Timeline